peripheral:didUpdateValueForCharacteristic can't be reached - ios

My code is based on Apple's the CoreBluetooth sample code named "TemperatureSenor".
I find a phenomena that if I set peripheral to repeat sending message, then call peripheral:setNotifyValue:YES forCharacteristic: , at last peripheral:didUpdateValueForCharacteristic: is called.
If I call peripheral:setNotifyValue:YES forCharacteristic: to listen messages from peripheral, then set peripheral to send message to central, the central will not call peripheral:didUpdateValueForCharacteristic:.
What's the reason?

Maybe you should be sure that whether your characteristic that you use to send message has the notify property which is decided by peripheral.If your characteristic doesn't has notify property but you still call "peripheral:setNotifyValue:YES forCharacteristic:",you will receive unknown error 2.
If your characteristic has notify property and you call "peripheral:setNotifyValue:YES forCharacteristic:",the central will call "peripheral:didUpdateValueForCharacteristic:"

Related

RxBluetoothKit: How to subscribe to Bluetooth state + Peripheral connection state and Write/Notify characteristics at same time?

I just started to study about RxBluetoothKit as easy solution to interact with BLE devices and I have very basic knowledge of Rx programing.
As i can see from examples, every time i have to write some characteristic i have to scan + establishConnection to Peripheral + discover Services and only then write and subscribe for confirmation of this specific Characteristic.
Same happen for read Characteristic.
If I understand correctly, this way I can subscribe only to one sequence/ connection at same time.
But what i need is to subscribe to Bluetooth state and to Peripheral connection state and to notify Characteristic, in addition i have send write commands to same Peripheral sometimes.
Need help to understand how should i handle this scenario by using RXBluetoothKit library?
Links to similar approachment on GitHub are welcomed.
Thank you!
This exact case isn't covered by RxBluetooth kit, so you'll have to manage this case by yourself. Not the most ideal, but you could go with something like this:
// Get an observable to the Peripheral, then share it so
// it can be used for multiple observing chains
let connectedPeripheral: Observable<Peripheral> = peripheral
.establishConnection()
.share(replay: 1, scope: .whileConnected)
// Establish a subscription to read characteristic first
// so no notifications are lost
let readDisposable = connectedPeripheral
.flatMap { $0.observeValueAndSetNotification(for: Characteristic.read) }
.subscribe()
// Write something to the write characteristic and observe
// responses in the chain above
let writeDisposable = connectedPeripheral
.flatMap { $0.writeValue(data, for: Characteristic.write, type: .withResponse) }
.subscribe()
The example above is just a gist, but the general idea should work since I'm doing a similar thing in a project of my own. Be careful to dispose the observables when done, either by .take or disposeBags.

get and display peripheral bluetooth RSSI signal strength in IOS app

I'm having trouble within an IOS swift application trying to get bluetooth RSSI signal strength from the peripheral. I've been trying to use readRSSI() (see code below) which returns a Future, but I've so far been unable to map that Future into another usable variable such as an Int or String. I'm new to Swift, so not sure if I'm missing an async step or other. I'm used to working in R, python, JS and having some challenges wrapping my head around the syntax. Any help is greatly appreciated.
I've tried switching multiple ways of extracting the content from within extensions to the ViewController without luck. I get errors on type-mismatches no matter how I try to pass the Future type value.
let strengthCharacteristic = self.peripheral.readRSSI()
let thisRet = self.strengthChar.map({ avar in
return avar
})
self.strengthLabel.text = String(thisRet ?? 0)
Apple docs for readRSSI() method:
On iOS and tvOS, when you call this method to retrieve the RSSI of the peripheral while connected to the central manager, the peripheral calls the peripheral:didReadRSSI:error: method of its delegate object, which includes the RSSI value as a parameter.
In order to read the RSSI from a peripheral, implement the peripheral:didReadRSSI:error: in the delegate object of the peripheral. This method will be fired when you call the readRSSI() method of the peripheral object. You can retrieve the RSSI value directly in this method as an input parameter. Don't forget to assign the delegate to the peripheral object.

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.

CoreBluetooth peripheral.setNotifyValue(true, characteristic) is not notifying

I have two programs, one for Mac and one for iOS. When I connect to the iOS device from the Mac, it finds the services I want, and the characteristics I want. After finding the characteristic, I use peripheral.setNotifyValue(true, forCharacteristic: characteristic), but the peripheralManager:central:didSubscribeToCharacteristic: method isn't being called on the iOS side. When I check if characteristic.isNotifying it is false. From what I understand when I set the notify value to true, it should be notifying, and whenever i change the value is updates. Why is it not updating? Thanks in advance.
Here is the code that sets up the characteristic in question -
self.characteristic = CBMutableCharacteristic(type: UUID_CHARACTERISTIC, properties: CBCharacteristicProperties.Read, value: self.dataToSend, permissions: CBAttributePermissions.Readable)
theService = CBMutableService(type: UUID_SERVICE, primary: true)
theService.characteristics = [characteristic]
self.peripheralManager.addService(theService)
If you want your characteristic to support notify operations then you need to set this on its properties -
self.characteristic = CBMutableCharacteristic(type: UUID_CHARACTERISTIC, properties: CBCharacteristicProperties.Read|CBCharacteristicProperties.Notifiy, value: self.dataToSend, permissions: CBAttributePermissions.Readable);
An attempt to set notification on a characteristic that doesn't state support for notification is ignored by Core Bluetooth.
Also, be aware that by setting a value when the characteristic is created, you will not be able to change the value of this characteristic in the future - therefore notification is somewhat pointless. If you want to be able to change the value you must specify nil for value when you create the characteristic.
From the CBMutableCharacteristic documentation -
Discussion
If you specify a value for the characteristic, the value is
cached and its properties and permissions are set to
CBCharacteristicPropertyRead and CBAttributePermissionsReadable,
respectively. Therefore, if you need the value of a characteristic to
be writeable, or if you expect the value to change during the lifetime
of the published service to which the characteristic belongs, you must
specify the value to be nil. So doing ensures that the value is
treated dynamically and requested by the peripheral manager whenever
the peripheral manager receives a read or write request from a
central. When the peripheral manager receives a read or write request
from a central, it calls the peripheralManager:didReceiveReadRequest:
or the peripheralManager:didReceiveWriteRequests: methods of its
delegate object, respectively.

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

Resources