Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreBluetooth Characteristic value

I'm confused on how long the value of a characteristic for CBMutableCharacteristic can be. If I have an archived array of objects, can I set the value of the Characteristic to this archived array? Or am I better off having a separate characteristic for each archived object in the array?

like image 640
Ethan Blackburn Avatar asked Dec 31 '13 06:12

Ethan Blackburn


1 Answers

The specification limits the maximum length of a characteristic value in 512 octets (Bluetooth specification V4.0 Vol 3. Part F 3.2.9). On the central side you start a read request with the readValueForCharacteristic: API. Then on the peripheral side you receive the corresponding callback:

CBMutableCharacteristic *characteristic = // the characteristic with long data

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
  // Ensure offset is in the valid range
  if (request.offset > characteristic.value.length) {
   // respond with error
   [self.peripheralManager respondToRequest:request withResult:CBATTErrorInvalidOffset];  
   return;
  }

  NSRange range = NSMakeRange(request.offset, characteristic.value.length - request.offset);
  request.value = [characteristic.value subdataWithRange:range];

  [self.peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];  
}

The callback will be called with increasing offset values as long as the response is not less than the Maximum Transferrable Unit (MTU). The MTU is negotiated by the system and you have no way to query it in advance. For this reason the range is set up to stretch all the way to the data length so the system can decide how much of the data it is going to send to the central. By default it is 20 but iOS 7 has some tweaks that enable greater sizes. Check out the WWDC videos for more detail.

With this info you should be able to figure out a way to expose your data. Keep in mind that the more services and characteristics you have, the longer the discovery will take. Using long reads and long writes is just a convenience.

like image 147
allprog Avatar answered Nov 15 '22 01:11

allprog