سؤال

I'm having problems finding the correct way to write the characteristics of a Bluetooth device. This one has a 3 bytes password and after writing all the characteristics, I have to write this password into its last field (named FFFF), in order for it to save.

The password is 000015 or 0x00000f in hexadecimal and I'm using this code:

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];
}

The problem is that although the conversion from int to hex seems to be done correctly, when trying to write it as NSData, I get an error saying "Encryption is insufficient". The manufacturer says that this means "wrong password" (and they don't have any iOS sample code of how to write it).

هل كانت مفيدة؟

المحلول

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];
}

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top