我需要使用 Android ble 类发送以下结构,但不幸的是 java 不支持结构类型,我必须将结构转换为类。实际上我可以创建一个类似结构的类,但我的大问题是,java也不支持uint8和uint32类型。
我在 BluethootGattChracteristic 下找到了 Format_UINT32 和 Format_UINT8 方法,但它无法运行我的代码。我总是使用以下代码将相同的数组发送到目标设备
我的标准 C 结构如下
struct test{
Time1 uint32;
Time2 uint32;
Time3 uint32;
Time4 uint32;
Time5 uint32;
Time6 uint32;
Speed uint8;
Speed2 uint8;
Speed3 uint8;
}
我在 java 中创建相同的类型,如下所示
long Time1= 4000000000L;
long Time2= 1500L;
long Time3= 0L;
long Time4= 0L;
long Time5= 0L;
long Time6= 0L;
int speed = 01;
int speed2 = 02;
int speed3 = 04;
然后我尝试使用这样的 ble write 方法发送此数据;
Time1= BluetoothGattCharacteristic.FORMAT_UINT32;
Time2= BluetoothGattCharacteristic.FORMAT_UINT32;
Time3= BluetoothGattCharacteristic.FORMAT_UINT32;
Time4= BluetoothGattCharacteristic.FORMAT_UINT32;
Time5= BluetoothGattCharacteristic.FORMAT_UINT32;
Time6= BluetoothGattCharacteristic.FORMAT_UINT32;
speed= BluetoothGattCharacteristic.FORMAT_UINT8;
speed2= BluetoothGattCharacteristic.FORMAT_UINT8;
speed3= BluetoothGattCharacteristic.FORMAT_UINT8;
ByteBuffer buffer = ByteBuffer.allocate(27);
buffer.put((byte)Time1);
buffer.put((byte)Time2);
buffer.put((byte)Time3);
buffer.put((byte)Time4);
buffer.put((byte)Time5);
buffer.put((byte)Time6);
buffer.put((byte)speed);
buffer.put((byte)speed2);
buffer.put((byte)speed3);
buffer.order(ByteOrder.LITTLE_ENDIAN);
charac.setValue(buffer.array());
这段代码以某种方式发送了像 0x1414141411111110000 这样的数据数组……但这完全是错误的。
如何解决这个问题?或者如何创建一个像上面的结构一样的类?
谢谢
最佳答案
您的代码有一些好的元素,但您只发送 BluetoothGattCharacteristic.FORMAT_UINT32
的常量值,而不发送实际数据。您不需要 BluetoothGattCharacteristic.FORMAT_UINT32
。
所以让我们用一个简单的类来保存数据:
class Payload {
int time1;
int time2;
int time3;
int time4;
int time5;
int time6;
byte speed1;
byte speed2;
byte speed3;
}
然后,您可以使用ByteBuffer
从中创建一个字节数组:
byte[] createBytes(Payload payload) {
ByteByffer buffer = ByteBuffer.allocate(28).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(payload.time1);
buffer.putInt(payload.time2);
buffer.putInt(payload.time3);
buffer.putInt(payload.time4);
buffer.putInt(payload.time5);
buffer.putInt(payload.time6);
buffer.putByte(payload.speed1);
buffer.putByte(payload.speed2);
buffer.putByte(payload.speed3);
buffer.putByte(0);
return buffer.array();
}
额外的 0 是将数据长度填充为 4 的倍数,即 28。最有可能的是,C 结构体将是 28 字节长。
最后,您传输数据:
byte[] data = createBytes(payload);
gattCharacteristic.setValue(data);
请注意,Java 整数类型是有符号的(例如 -128 到 127 表示 byte),而 C 类型是无符号的(例如 0 到 255 表示 uint8_t)。这可能需要在 Java 中进行一些额外的处理。
关于java - 如何使用android ble接口(interface)作为结构发送uint8和uint32数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058801/