欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

BluetoothGatt 踩坑

程序员文章站 2024-03-24 23:27:28
...

1.BluetoothGatt 超过20个字节,导致后面的数据丢了

注:与仪器通信,我们这里发送的是16进制的数据,发送的时候需要先将其装载到byte[]数组中,例如我发送 7e 14 00 00 00 aa这个指令,我需要把它转化为ew byte[] {0x7e, 0x14, 0x00, 0x00,0x00,(byte) 0xaa }这样去发送,因为BLE传输过程每次最大只能传输20个字节,所以如果发送的指令大于20字节的话要分包发送,例如现在要发送28个字节的,可以先write(前20个字节),开启线程sleep(几十毫秒)后在write(后面8个字节)。

WriteBytes = writeBytes;
        BluetoothGattCharacteristic gg;
        gg=mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_TX));
        //byte t[]={51,1,2};
        gg.setValue(WriteBytes);
        mBluetoothGatt.writeCharacteristic(gg);
        if (writeBytes.length>20) {
            byte[] secondBytes = new byte[writeBytes.length-20];
            try {
                Thread.sleep(10);
                for (int i = 20,j=0; i < writeBytes.length; i++,j++) {
                    secondBytes[j] = writeBytes[i];
                }
                gg.setValue(secondBytes);
                mBluetoothGatt.writeCharacteristic(gg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
相关标签: ble