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.
Related
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.
I have several custom BLE LED lights (peripherals). I've implemented a bluetooth helper class (CBCentralManager and associated delegate methods), and can connect and control each light individually without issue. I have handled all of the basic retrieve / connect / notify logic, and it works great.
My next step was to connect to multiple lights and control them essentially simultaneously (or as near as possible). To manage the different active peripherals, I created a dictionary to store them in, using the UUID as the key like so (BLEDevice contains a peripheral property where I store the reference):
class BLEDevice {
var uuid: String!
var peripheral: CBPeripheral!
var rssi: NSNumber!
var name: String!
var advertData: [String: Any]!
var type = 0
init() {
}
}
var bleDeviceDict: [String: BLEDevice] = [:]
This dictionary gets populated during the retrieval process, and then I do a connection request for each one. Upon success of connection, service discovery, characteristic discovery...etc, I update the dictionary object. I'm able to connect to each device without any issue, but when I attempt to send any commands (with or without a response flag) I get unreliable operation. Sometimes it works great, and other times it throws the following error:
[CoreBluetooth] WARNING: <CBCharacteristic: 0x129701430, UUID = FFE1, properties = 0x1C, value = <45080154>, notifying = YES> is not a valid characteristic for peripheral <CBPeripheral: 0x127e0ad70, identifier = 44CDB018-2A5C-D776-7641-7F193470945A, name = 3CA5090A21AFED, state = connected>
To send the group commands, I set up a basic for loop to iterate through and send the command to each peripheral, and I'm almost certain this brute force approach is the wrong way to accomplish this. I've done some searching, but have been unable to find any literature on the proper way to control devices at the same time. I could really use some advice or direction to help solve this problem. What is the best practice for achieving this behavior?
You need to store a specific instance of the relevant characteristic for each peripheral you are connected to.
Add properties to your BLEDevice to store references to the relevant characteristics you find during discovery.
There is no other way to send the data to each of the peripherals; You need to iterate over your peripheral collection and write the data to each one.
I am working with iOS 8's Core Bluetooth API. I have written some simple Swift code that creates a Central Manager and that implements the CBManager & CBPeripheral protocols. When the callbacks are executed they perform logging:
2015-09-04 14:08:33.719 CentralManager - Did update state to Powered on
2015-09-04 14:08:33.745 CentralManager - Did discover peripheral: CBPeripheral: 0x1700f5080, identifier = 3DD113C3-D175-7374-CF88- F471BB470169, name = Apple TV, state = disconnected
2015-09-04 14:08:33.955 CentralManager - Did connect peripheral: CBPeripheral: 0x1700f5080, identifier = 3DD113C3-D175-7374-CF88-F471BB470169, name = Apple TV, state = connected
2015-09-04 14:08:34.462 Peripheral - Did discover service: CBService: 0x174075600, isPrimary = YES, UUID = Continuity
2015-09-04 14:08:34.582 Peripheral: Did discover characteristic for service Continuity : ()
Everything looks good. As you can see, log statements 2 and 3 print the value of the CBPeripheral argument that was passed to the callback function. I am using Swift's string interpolation capability to accomplish this - ex. "The value is \(peripheral)".
Now for the problem: When I set a breakpoint in one of the callback functions and examine the CBPeripheral argument via Xcode's debug pane, I am not able to view any of the values that are revealed by the logging statements. When I expand the CBPeripheral (i.e. click on the triangle next to it) I see that it is a CBPeer. When I expand the CBPeer I see that it is an NSObject. But, no variables or properties are revealed.
Does anyone have an explanation for this?
Cheers, Robert
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
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:"