张世豪
昨天 13d032241e1a2938a8be4f64c9171e1240e9ea1e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package yaokong;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;
 
public class PathCommandSender extends WaitForAck {
 
    public PathCommandSender(InputStream inputStream, OutputStream outputStream) {
        super(inputStream, outputStream);
    }
 
    // 发送多点路径数据给设备端执行
    public boolean sendPathCommand(List<Point> points) throws IOException {
        if (points == null || points.isEmpty() || points.size() > 255) {
            return false;
        }
        
        int pointCount = points.size();
        int dataLength = 1 + pointCount * 16; // 1字节点数 + 每个点16字节
        
    ByteBuffer buffer = ByteBuffer.allocate(2 + 1 + 2 + 2 + dataLength + 2 + 1);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        
        // 帧头
        buffer.put(BluetoothProtocol.FRAME_HEADER);
        // 指令类型
        buffer.put(BluetoothProtocol.CMD_PATH);
        // 数据长度
        buffer.putShort((short) dataLength);
        // 序列号
        buffer.putShort((short) BluetoothProtocol.getNextSequence());
        // 路径点数量
        buffer.put((byte) pointCount);
        // 路径点数据
        for (Point point : points) {
            buffer.putDouble(point.x);
            buffer.putDouble(point.y);
        }
        
        // 计算CRC16(从指令类型到数据内容结束)
        byte[] dataForCRC = new byte[1 + 2 + 2 + dataLength];
        System.arraycopy(buffer.array(), 2, dataForCRC, 0, dataForCRC.length);
        int crc = CRC16.calculateCRC16(dataForCRC, 0, dataForCRC.length);
        buffer.putShort((short) crc);
        
        // 帧尾
        buffer.put(BluetoothProtocol.FRAME_FOOTER);
        
        // 发送数据
        outputStream.write(buffer.array());
        outputStream.flush();
        
        return waitForAck(BluetoothProtocol.CMD_PATH);
    }
    
    public static class Point {
        public double x;
        public double y;
        
        // 使用指定坐标构造路径点
        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
}