我正在尝试使用BluetoothGattCharacteristic方法setValue(..)在香水分配器设备中写入十六进制值0xFF。我在回调方法onCharacteristicWrite()中获得成功状态代码0但是设备不执行任何操作,理想情况下应散发香味。
下面是我要写入特征的示例代码
private void writeCharacteristic(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID, byte[] data, int writeType) {
boolean success = false;
if (gatt == null) {
callbackContext.error("BluetoothGatt is null");
return;
}
BluetoothGattService service = gatt.getService(serviceUUID);
BluetoothGattCharacteristic characteristic = findWritableCharacteristic(service, characteristicUUID, writeType);
if (characteristic == null) {
callbackContext.error("Characteristic " + characteristicUUID + " not found.");
} else {
int data2=0xFF;
characteristic.setValue(data2, BluetoothGattCharacteristic.FORMAT_UINT16, 0);
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
writeCallback = callbackContext;
if (gatt.writeCharacteristic(characteristic)) {
success = true;
System.out.println(" writeCharacteristic success");
} else {
writeCallback = null;
callbackContext.error("Write failed");
}
}
请建议在BluetoothGattCharacteristic的setValue()方法中写入十六进制数据。
由于
答案 0 :(得分:1)
您可以将字节数组发送到特性。
使用以下方法将十六进制转换为字节数组。link
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
首先将您的号码转换为十六进制......
public static String toHex(String arg)
{
try
{
return String.format("%01x", new BigInteger(1, arg.getBytes("UTF-8")));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
}
//set data
characteristic.setValue(hexStringToByteArray(toHex(255+""));
答案 1 :(得分:0)
BluetoothGattCharacteristic.FORMAT_UINT16
in
FF 00
表示您将发送0xFF
,因为您将其设置为发送16位无符号数字。要仅发送UINT8
(我不知道这是否有所不同),您必须将格式设置为characteristic.setValue(data2, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
。
if (!(i >= 1 && i <= 50)) {
System.out.print("guesses = ");
i = r.nextInt(50)+1;
System.out.println(i);
count++;
}