package pl.niekoniecznie.polar.io;

import com.codeminders.hidapi.HIDDevice;

import java.io.IOException;

public class PolarService {

    private final HIDDevice device;

    public PolarService(final HIDDevice device) {
        this.device = device;
    }

    public void write(byte[] message) throws IOException {
        byte[] buffer = new byte[PolarPacket.BUFFER_LENGTH];
        PolarPacket packet = new PolarPacket(buffer);

        packet.setType(0x01);
        packet.setMore(false);
        packet.setSequence(0);
        packet.setData(message);

        device.write(buffer);
    }

    public PolarResponse recv() throws IOException {
        PolarResponse response = new PolarResponse();

        byte[] buffer = new byte[PolarPacket.BUFFER_LENGTH];
        PolarPacket packet = new PolarPacket(buffer);

        while (true) {
            device.read(buffer);
            response.append(packet.getData());

            if (!packet.hasMore()) {
                break;
            }

            packet.setType(0x01);
            packet.setSize(0);

            device.write(buffer);
        }

        return response;
    }
}

@@ -304,32 +304,92 @@
 s IOException %7B%0A
+        byte%5B%5D chunk = new byte%5BPolarPacket.MAX_DATA_SIZE%5D;%0A
         byte%5B%5D b
@@ -480,32 +480,466 @@
 acket(buffer);%0A%0A
+        int count = (int) Math.ceil((double) message.length / PolarPacket.MAX_DATA_SIZE);%0A%0A        for (int i = 0; i %3C count; i++) %7B%0A            boolean last = i == count - 1;%0A            int start = i * PolarPacket.MAX_DATA_SIZE;%0A            int size = PolarPacket.MAX_DATA_SIZE;%0A%0A            if (last) %7B%0A                size = message.length %25 size;%0A            %7D%0A%0A            System.arraycopy(message, start, chunk, 0, size);%0A%0A    
         packet.s
@@ -952,32 +952,36 @@
 (0x01);%0A        
+    
 packet.setMore(f
@@ -983,16 +983,20 @@
 ore(
-false);%0A
+!last);%0A    
     
@@ -1018,17 +1018,17 @@
 equence(
-0
+i
 );%0A     
@@ -1022,32 +1022,36 @@
 nce(i);%0A        
+   
+ 
 packet.setData(m
@@ -1053,19 +1053,55 @@
 ata(
-messag
+chunk);%0A            packet.setSize(siz
 e);%0A%0A
+    
     
@@ -1121,24 +1121,111 @@
 ite(buffer);
+%0A%0A            if (!last) %7B%0A                device.read(buffer);%0A            %7D%0A        %7D
 %0A    %7D%0A%0A    

Enable multipart message sending