In my previous article “Mastering the fundamentals of BLE for iOS using Swift” I have already presented the core principles of BLE functionality but this time I am going to elucidate the internals of the BLE data transmission process.
Initially, let us remember the BLE data flow. The flow diagram is depicted below.
Apparently, concerning reading the data from the peripheral, it is mandatory to define the following methods from the “CBPeripheralDelegate” protocol in your class:
Firstly, the peripheral has to provide the central manager with services available before initializing the channels of data transmission as it was described in my last article.
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)
Secondly, the “didDiscoverCharacteristicsFor service” method is the inception of the data exchange process via BLE protocol. Similarly, the BLE characteristics are the endpoints in networking terms through which the packets are sent (Wi-Fi or Ethernet) that have their unique identifiers known as UUID.
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)
Thirdly, as soon as the desired characteristic is selected, the central manager subscribes to the peripheral’s characteristics notifications that have the payload.
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?)
Besides, if the peripheral transmits binary data, the “didUpdateValueFor characteristic” method is called where the contents of the incoming parcel can be investigated.
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
By the way, when the data from the central manager has been sent, the “didWriteValueFor characteristic” is invoked where the contents of the outcoming parcel can be examined.
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?)
To sum up, the algorithm of a BLE connection consists of two essential things:
- Adjusting the methods for the central manager from the “CBCentralManagerDelegate” protocol.
- Configuring the methods for the peripheral from the “CBPeripheralDelegate” protocol.
Ultimately, to make this candid, I attached the demo code displaying the steps to access the BLE protocol on iOS.
Happy coding!