-
Notifications
You must be signed in to change notification settings - Fork 369
8. Convenience helper methods
In order to enable even easier interaction with RxBluetooth, we've provided custom protocols we advice you to implement.
These are ServiceIdentifier
, CharacteristicIdentifier
and DescriptorIdentifier
. Most of the time you're writing Bluetooth code to communicate with specific device, while knowing its specification like services and characteristic. That's exactly the case, where you should implement these protocols. Sample implementation might look like:
enum DeviceCharacteristic: String, CharacteristicIdentifier {
case manufacturerName = "2A29"
var uuid: CBUUID {
return CBUUID(string: self.rawValue)
}
//Service to which characteristic belongs
var service: ServiceIdentifier {
switch self {
case .ManufacturerName:
return XXXService.DeviceInformation
}
}
}
enum DeviceService: String, ServiceIdentifier {
case deviceInformation = "180A"
var uuid: CBUUID {
return CBUUID(string: self.rawValue)
}
}
After implementing these types, the whole set of new new methods becomes available. Earlier implementation of reading from characteristic looked like that:
peripheral.establishConnection()
.flatMap { $0.discoverServices([serviceId]) }.asObservable()
.flatMap { Observable.from($0) }
.flatMap { $0.discoverCharacteristics([characteristicId])}.asObservable()
.flatMap { Observable.from($0) }
.flatMap { $0.readValue() }
.subscribe(onNext: {
let data = $0.value
})
When you use new CharacteristicIdentifier
protocol, you could do it way simpler:
peripheral.establishConnection()
.flatMap { $0.readValue(for: DeviceCharacteristic.manufacturerName)
.subscribe(onNext: {
let data = $0.value
})
The set of methods that are taking instances conforming CharacteristicIdentifier or DescriptorIdentifier does all of the heavy lifting like discovering services, characteristics and descriptors for you. Moreover, in order to optimise - when one of these is available in cache, discovery is not called at all.
We really encourage you to use these versions of methods in order to make your code even shorter and cleaner.