Crash in CBPeripheral writeValue: forDescriptor: - ios

After establishing a connection with a TI BLE Keyfob and retrieving the descriptors for a characteristic, I attempt the call
[peripheral writeValue: nsData forDescriptor: descriptor];
The various objects look reasonable in the debugger. nsData has a single byte of 1, peripheral is a valid looking CBPeripheral object returned from iOS, and descriptor is a valid looking CBDescriptor returned by iOS.
My app crashes with the error
* Assertion failure in -[CBConcretePeripheral writeValue:forDescriptor:],
/SourceCache/CoreBluetooth/CoreBluetooth-59.3/CBConcretePeripheral.m:358
Any thoughts on why this is happening or how to debug it?

Note from the documentation of writeValue:forDescriptor
Client characteristic configuration descriptors cannot be written
using this method, and should instead use setNotifyValue:forCharacteristic:
So if you are trying to write the descriptor of the connected peripheral, then it will fail.
For writing the characteristic, use the - writeValue:forCharacteristic:type: method.

Related

What will the flow be like for connecting two BLE Peripherals?

I have been reading a lot of posts here on the forum and I saw quite a few relating to my case. However I still don't have the clarity that I was looking for.
I want to connect to two CBPeripherals and to write data to both of them. From what I have read, I have the idea that before connecting to a second device I have to disconnect the current peripheral. Okay, so suppose I were to write a command onto one of the peripherals and then I want to write another command to the other one, will I have to disconnect from the current peripheral? If I did disconnect to connect to the other, will the previous command still hold effect? What are the best practises for this on iOS?
my bluetooth friend, first of all it isn't necessary to disconnect current Peripheral to connect another if u want to send both messages. But many apps limit number of connected devices(CBPeripheral) to 5 - 10, because more than 5-10 connected devices, can spontaneously be lost, I know about it a little (I worked only with 4 devices). For example:
[[RKCentralManager sharedManager] scanForPeripheralsWithServices:nil options:#{CBCentralManagerScanOptionAllowDuplicatesKey:#NO} onUpdated:^(RKPeripheral *peripheral)
{
//first of all u should start a scan
[[RKCentralManager sharedManager] connectPeripheral: peripheral options:nil onFinished:^(RKPeripheral * connectedperipheral, NSError *error)
{
//after u can connect to Peripheral immediately
[connectedperipheral discoverServices:nil onFinish:^(NSError *error)
{
// services - a collection of data and associated behaviors for accomplishing a function or feature of a device
[connectedperipheral discoverCharacteristics:nil forService: [connectedperipheral.services lastObject] onFinish:^(CBService *service, NSError *error)
{
//after u should take a characteristic - Represents a service's characteristic
CBCharacteristic * characteristic = service.characteristics[0];
//and at last u can write value in characteristic in which you are going to write down something
NSData * data = [NSData dataWithHexString: newstring];
CBCharacteristicWriteType type = CBCharacteristicWriteWithoutResponse;
[connectedperipheral writeValue:data forCharacteristic:characteristic type:type onFinish:nil];
}];
}];
}];
}];
The approximate scheme of sending the message for bluetooth device, it isn't obligatory to do an investment of methods, they can be distributed on actions.
You shouldn't worry about connection and sendings data
to several devices because it is work for CBCentralManager, if U use it correctly.
CBCentralManager objects are used to manage discovered or connected remote peripheral devices (represented by CBPeripheral objects), including scanning for, discovering, and connecting to advertising peripherals.
You can connect at once some devices and send them messages, and all be ok.
If you have questions, will try to answer.
This is good example, u can see how its work : https://github.com/ruiking/ble
About max count of devices https://stackoverflow.com/a/17282862/4912496

Reading Bluetooth LE CBCharacteristic returns a smaller value on iOS 7 [duplicate]

I have a characteristic value which contains the data for an image. In the peripheral I setup the value like this:
_photoUUID = [CBUUID UUIDWithString:bPhotoCharacteristicUUID];
_photoCharacteristic = [[CBMutableCharacteristic alloc] initWithType:_photoUUID
properties:CBCharacteristicPropertyRead
value:Nil
permissions:CBAttributePermissionsReadable];
My understanding is that when this value is requested, the didReceiveReadRequest callback will be called:
-(void) peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
if ([request.characteristic.UUID isEqual:_photoUUID]) {
if (request.offset > request.characteristic.value.length) {
[_peripheralManager respondToRequest:request withResult:CBATTErrorInvalidOffset];
return;
}
else {
// Get the photos
if (request.offset == 0) {
_photoData = [NSKeyedArchiver archivedDataWithRootObject:_myProfile.photosImmutable];
}
request.value = [_photoData subdataWithRange:NSMakeRange(request.offset, request.characteristic.value.length - request.offset)];
[_peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
}
}
}
This comes pretty much from Apple's documentation. On the Central side in the didDiscoverCharacteristic callback I have the following code:
if ([characteristic.UUID isEqual:_photoUUID]) {
_photoCharacteristic = characteristic;
[peripheral readValueForCharacteristic:characteristic];
}
Which in turn calls the didUpdateValueForCharacteristic callback:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(#"updated value for characteristic");
if ([characteristic.UUID isEqual:_photoUUID]) {
NSArray * photos = [NSKeyedUnarchiver unarchiveObjectWithData:characteristic.value];
}
}
All of the callbacks are called but when I try to re-construct the array, it's corrupted because not all of the data is transferred correctly. I would expect the didRecieveReadRequest callback to be called multiple times with a different offset each time. However it's only called once.
I was wondering if anyone knew what I'm doing wrong?
I'm guessing you're bumping up against the 512 byte limit on characteristic length. You'll need to move to subscriptions to characteristics and processing of updates to get around this:
On the central:
Subscribe to the characteristic by calling -[CBPeripheral setNotifyValue:forCharacteristic] (with YES as the notify value).
In -peripheral:didUpdateValueForCharacteristic:error, every update will either be data to append, or something you choose to use on the peripheral side to indicate end-of-data (I use an empty NSData for this). Update your -peripheral:didUpdateValueForCharacteristic:error code so that:
If you're starting to read a value, initialize a sink for the incoming bytes (e.g. an NSMutableData).
If you're in the middle of reading a value, you append to the sink.
If you see the EOD marker, you consider the transfer complete. You may wish to unsubscribe from the characteristic at this state, by calling -[CBPeripheral setNotifyValue:forCharacteristic] with a notify value of NO.
-peripheral:didUpdateNotificationStateForCharacteristic:error: is a good spot to manage the initialization and later use of the sink into which you read chunks. If characteristic.isNotifying is updated to YES, you have a new subscription; if it's updated to NO then you're done reading. At this point, you can use NSKeyedUnarchiver to unarchive the data.
On the peripheral:
In -[CBMutableCharacteristic initWithType:properties:value:permissions], make sure the properties value includes CBCharacteristicPropertyNotify.
Use -peripheralManager:central:didSubscribeToCharacteristic: to kick off the chunking send of your data, rather than -peripheral:didReceiveReadRequest:result:.
When chunking your data, make sure your chunk size is no larger than central.maximumUpdateValueLength. On iOS7, between an iPad 3 and iPhone 5, I've typically seen 132 bytes. If you're sending to multiple centrals, use the least common value.
You'll want to check the return code of -updateValue:forCharacteristic:onSubscribedCentrals; if underlying queue backs up, this will return NO, and you'll have to wait for a callback on -peripheralManagerIsReadyToUpdateSubscribers: before continuing (this is one of the burrs in an otherwise smooth API, I think). Depending upon how you handle this, you could paint yourself into a corner because:
If you're constructing and sending your chunks on the same queue that the peripheral is using for its operations, AND doing the right thing and checking the return value from -updateValue:forCharacteristic:onSubscribedCentrals:, it's easy to back yourself into a non-obvious deadlock. You'll either want to make sure that you yield the queue after each call to -updateValue:forCharacteristic:onSubscribedCentrals:, perform your chunking loop on a different queue than the peripheral's queue (-updateValue:forCharacteristic:onSubscribedCentrals: will make sure its work is done in the right place). Or you could get fancier; just be mindful of this.
To see this in action, the WWDC 2012 Advanced Core Bluetooth video contains an example (sharing VCards) that covers most of this. It doesn't however, check the return value on the update, so they avoid the pitfalls in #4 altogether.
Hope that helps.
I tried the approach described by Cora Middleton, but couldn't get it to work. If I understand her approach correctly, she would send all partial data through the update notifications. The problem for me seemed to be that there was no guarantee each update would be read by the central if the values in these notifications would change often in short succession.
So because that approach didn't work, I did the following:
There's some characteristic that I use to keep track of the state of the peripheral. This characteristic would only contain some flags and would send out notifications if one or more flags change. Interactions by the user on the peripheral would change the state and there's one action on the peripheral that the user can perform to trigger a download from a connected central.
The data to be downloaded from the central is added to a stack on the peripheral. The last item on the stack is a terminator indicator (an empty NSData object)
The central registers to receive notifications of the aforementioned state characteristic. If some flag is set, a download is triggered.
On the peripheral side, every time I receive a read request for a certain characteristic, I remove 1 item from the stack and return this item.
On the central side I add all data that is returned from the read requests. If the empty data value is retrieved, then I create an object from the returned data (in my case it's a JSON string).
On the peripheral side I also know the download is finished after returning the empty NSData object, so afterwards I can change the state once again for the peripheral.

ios ble - Write Without Response" property - ignoring response-less write

On iOS7.1.1, the following BLE operation succeeds - it assumes I have a BLE connection setup etc...
[[self peripheral]writeValue:dataToWrite forCharacteristic:nextCharacteristic type:CBCharacteristicWriteWithResponse];
But If I switch the "type" to CBCharacteristicWriteWithoutResponse, I get the following warning and the peripheral does not receive the command :(
[[self peripheral]writeValue:dataToWrite forCharacteristic:nextCharacteristic type:CBCharacteristicWriteWithoutResponse];
Error:
CoreBluetooth[WARNING] Characteristic <CBCharacteristic: 0x178081f90 UUID = 249C2001-00D7-4D91-AC75-22D57AE2FFB8, Value = (null), Properties = 0x28, Notifying = YES, Broadcasting = NO> does not specify the "Write Without Response" property - ignoring response-less write**
Any clues appreciated!
When a BLE peripheral advertises characteristics the advertisement includes the properties of those characteristics. These include what operations are supported on that characteristic - read, notify, write without response and write with response.
In this case it seems that the characteristic supports write with response but not write without response, so when you attempt a write without response you get the warning and the write operations doesn't complete

IOS BLE communication write value;

I am writing my first IOS App, to communicate with the Bluegiga BLE chip. I need to read and write values. The issue I am having is that, I am not able to write the value the first time I run the program. I do not get any error. It shows the last value which was written as the current value. When I re-run the program the correct value is updated correctly. Its delaying my project. Any suggestion will be of great help. I am using the following code snippet.
CBPeripheral *servicePeripheral;
NSData *readIndex;
CBCharacteristic *readIdxCharacteristic;
[servicePeripheral writeValue:readIndex forCharacteristic:readIdxCharacteristic type:CBCharacteristicWriteWithResponse];
- (void) peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if ([characteristic isEqual:readIdxCharacteristic] ){
[peripheral readValueForCharacteristic:readIdxCharacteristic];
NSLog(#"Read Index Characteristic Written Check%#",characteristic.value);
}
}
Your problem is that you are accessing the characteristic.value immediately after the call to readValueForCharacteristic, but it takes some time for Core-Bluetooth to contact the peripheral, request a value for the characteristic and for the peripheral to reply.
If you refer to the documentation for this method you will see -
Discussion
When you call this method to read the value of a
characteristic, the peripheral calls the
peripheral:didUpdateValueForCharacteristic:error: method of its
delegate object. If the value of the characteristic is successfully
retrieved, you can access it through the characteristic’s value
property.
So, you need to access characteristic.value in your didUpdateValueForCharacteristic: CBPeripheral delegate method

Reading long characteristic values using CoreBluetooth

I have a characteristic value which contains the data for an image. In the peripheral I setup the value like this:
_photoUUID = [CBUUID UUIDWithString:bPhotoCharacteristicUUID];
_photoCharacteristic = [[CBMutableCharacteristic alloc] initWithType:_photoUUID
properties:CBCharacteristicPropertyRead
value:Nil
permissions:CBAttributePermissionsReadable];
My understanding is that when this value is requested, the didReceiveReadRequest callback will be called:
-(void) peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
if ([request.characteristic.UUID isEqual:_photoUUID]) {
if (request.offset > request.characteristic.value.length) {
[_peripheralManager respondToRequest:request withResult:CBATTErrorInvalidOffset];
return;
}
else {
// Get the photos
if (request.offset == 0) {
_photoData = [NSKeyedArchiver archivedDataWithRootObject:_myProfile.photosImmutable];
}
request.value = [_photoData subdataWithRange:NSMakeRange(request.offset, request.characteristic.value.length - request.offset)];
[_peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
}
}
}
This comes pretty much from Apple's documentation. On the Central side in the didDiscoverCharacteristic callback I have the following code:
if ([characteristic.UUID isEqual:_photoUUID]) {
_photoCharacteristic = characteristic;
[peripheral readValueForCharacteristic:characteristic];
}
Which in turn calls the didUpdateValueForCharacteristic callback:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(#"updated value for characteristic");
if ([characteristic.UUID isEqual:_photoUUID]) {
NSArray * photos = [NSKeyedUnarchiver unarchiveObjectWithData:characteristic.value];
}
}
All of the callbacks are called but when I try to re-construct the array, it's corrupted because not all of the data is transferred correctly. I would expect the didRecieveReadRequest callback to be called multiple times with a different offset each time. However it's only called once.
I was wondering if anyone knew what I'm doing wrong?
I'm guessing you're bumping up against the 512 byte limit on characteristic length. You'll need to move to subscriptions to characteristics and processing of updates to get around this:
On the central:
Subscribe to the characteristic by calling -[CBPeripheral setNotifyValue:forCharacteristic] (with YES as the notify value).
In -peripheral:didUpdateValueForCharacteristic:error, every update will either be data to append, or something you choose to use on the peripheral side to indicate end-of-data (I use an empty NSData for this). Update your -peripheral:didUpdateValueForCharacteristic:error code so that:
If you're starting to read a value, initialize a sink for the incoming bytes (e.g. an NSMutableData).
If you're in the middle of reading a value, you append to the sink.
If you see the EOD marker, you consider the transfer complete. You may wish to unsubscribe from the characteristic at this state, by calling -[CBPeripheral setNotifyValue:forCharacteristic] with a notify value of NO.
-peripheral:didUpdateNotificationStateForCharacteristic:error: is a good spot to manage the initialization and later use of the sink into which you read chunks. If characteristic.isNotifying is updated to YES, you have a new subscription; if it's updated to NO then you're done reading. At this point, you can use NSKeyedUnarchiver to unarchive the data.
On the peripheral:
In -[CBMutableCharacteristic initWithType:properties:value:permissions], make sure the properties value includes CBCharacteristicPropertyNotify.
Use -peripheralManager:central:didSubscribeToCharacteristic: to kick off the chunking send of your data, rather than -peripheral:didReceiveReadRequest:result:.
When chunking your data, make sure your chunk size is no larger than central.maximumUpdateValueLength. On iOS7, between an iPad 3 and iPhone 5, I've typically seen 132 bytes. If you're sending to multiple centrals, use the least common value.
You'll want to check the return code of -updateValue:forCharacteristic:onSubscribedCentrals; if underlying queue backs up, this will return NO, and you'll have to wait for a callback on -peripheralManagerIsReadyToUpdateSubscribers: before continuing (this is one of the burrs in an otherwise smooth API, I think). Depending upon how you handle this, you could paint yourself into a corner because:
If you're constructing and sending your chunks on the same queue that the peripheral is using for its operations, AND doing the right thing and checking the return value from -updateValue:forCharacteristic:onSubscribedCentrals:, it's easy to back yourself into a non-obvious deadlock. You'll either want to make sure that you yield the queue after each call to -updateValue:forCharacteristic:onSubscribedCentrals:, perform your chunking loop on a different queue than the peripheral's queue (-updateValue:forCharacteristic:onSubscribedCentrals: will make sure its work is done in the right place). Or you could get fancier; just be mindful of this.
To see this in action, the WWDC 2012 Advanced Core Bluetooth video contains an example (sharing VCards) that covers most of this. It doesn't however, check the return value on the update, so they avoid the pitfalls in #4 altogether.
Hope that helps.
I tried the approach described by Cora Middleton, but couldn't get it to work. If I understand her approach correctly, she would send all partial data through the update notifications. The problem for me seemed to be that there was no guarantee each update would be read by the central if the values in these notifications would change often in short succession.
So because that approach didn't work, I did the following:
There's some characteristic that I use to keep track of the state of the peripheral. This characteristic would only contain some flags and would send out notifications if one or more flags change. Interactions by the user on the peripheral would change the state and there's one action on the peripheral that the user can perform to trigger a download from a connected central.
The data to be downloaded from the central is added to a stack on the peripheral. The last item on the stack is a terminator indicator (an empty NSData object)
The central registers to receive notifications of the aforementioned state characteristic. If some flag is set, a download is triggered.
On the peripheral side, every time I receive a read request for a certain characteristic, I remove 1 item from the stack and return this item.
On the central side I add all data that is returned from the read requests. If the empty data value is retrieved, then I create an object from the returned data (in my case it's a JSON string).
On the peripheral side I also know the download is finished after returning the empty NSData object, so afterwards I can change the state once again for the peripheral.

Resources