kan*_*tar 3 ios core-bluetooth bluetooth-lowenergy
我在找到正确的方法来编写蓝牙设备的特性时遇到了问题.这个密码有3个字节,在写完所有特征之后,我必须将这个密码写入其最后一个字段(命名FFFF),以便保存.
密码是000015或0x00000f十六进制,我使用此代码:
if([characteristic.UUID isEqual: [CBUUID UUIDWithString: @"FFFF"]]) {
bt = 15;
NSString *hex = [NSString stringWithFormat:@"0x%06x", (unsigned int) bt];
NSLog(@"Hex value: %@", hex);
[peripheral writeValue:[NSData dataWithBytes:&hex length:3]forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
Run Code Online (Sandbox Code Playgroud)
问题是虽然从int到hex的转换似乎是正确完成的,但在尝试将其编写为时NSData,我得到一个错误说法"Encryption is insufficient".制造商说这意味着"错误的密码"(他们没有任何关于如何编写它的iOS示例代码).
It is simpler to use a byte buffer as shown below. This assumes the password is little endian (least significant byte first). If it is expecting big endian, you simply need to reverse the byte order.
if([characteristic.UUID isEqual: [CBUUID UUIDWithString: @"FFFF"]]) {
Byte byteArray[] = { 0x0F, 0x00, 0x00 };
[peripheral writeValue:[[NSData alloc] initWithBytes: byteArray length: 3]forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
Run Code Online (Sandbox Code Playgroud)
The code in the question does not work because it will convert a hex string to bytes, which is not what you want at all. You end up getting one byte for each of the the eight characters in the string, "0x00000F". You want three bytes.