-
Notifications
You must be signed in to change notification settings - Fork 372
6. Reading & Writing to characteristic value
Once you've got characteristic, next common step is to read value from it.
In order to do that, you should use readValue()
function defined on Characteristic
. It returns Observable<Characteristic>
which emits element, when value of characteristic is ready to read.
We decided to return Characteristic
instead of NSData
due to one purpose - to allow you chain operations on characteristic in easy way.
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
})
While deciding to write to characteristic you have two writing options, that determine write behavior:
- .withResponse
- .withoutResponse
Choosing .withResponse, you're waiting to receive .next event on Observable while device has confirmed that value has been written to it. Also, if any error has occurred - you will receive .error on Observable
. On the other hand - if you decided to go with .withoutResponse - you'd receive Characteristic
just after write command has been called. Also, no errors will be emitted.
Let's jump over to the code:
characteristic.writeValue(data, type: .withResponse)
.subscribe { event in
//respond to errors / successful read
}