Bluetooth Logo

Writing an SDK With Core Bluetooth – 16 – The Central Code

This entry is part 20 of 24 in the series Writing an SDK With Core Bluetooth

In this entry, we will walk through the code that we needed to add to the SDK/Central Mode to discover and register devices.

WALKTHROUGH

The Starting Repo Tag

The Ending Repo Tag

The Comparison Between the Two Tags

The ITCB_SDK_Central_internal.swift File

NOTE: We need to make sure that we keep a strong reference to instances of CBPeripheral that are returned in the discovery callback. This does not need to be done for instances of CBService or CBCharacteristic, as they are aggregated by CBPeripheral and CBService, respectively.

If we do not keep a strong reference, then the CBPeripheral instance will be deallocated when the context leaves the callback.

This is accomplished when we create an instance of ITCB_SDK_Device_Peripheral, and add it to the devices array in the SDK instance.

The ITCB_SDK_Peripheral_internal.swift File

  • Added a signal strength check to the Peripheral Discovery callback.
    We should be checking signal strength. I had left it out of the initial implementation to keep things simpler.
  • Extend the native Swift Array type to look for instances that have already been created.
    This searches our aggregated instances for a CBPeripheral, and returns true, if it is found. This allows us to avoid repeatedly adding Peripherals.
    This is a classic “coolness” of Swift. We can create custom extensions that can be specialized to the needs of the moment.
extension Array where Element == ITCB_Device_Peripheral_Protocol {
    func contains(_ inCBPeripheral: CBPeripheral) -> Bool {
        let peripheralStringID = inCBPeripheral.identifier.uuidString
        guard let myself = self as? [ITCB_SDK_Device_Peripheral], !peripheralStringID.isEmpty else { return false }
        return myself.reduce(false) { (current, nextItem) in
            return current || nextItem.uuid == peripheralStringID
        }
    }
}

WHERE WE ARE NOW

We now actually have the Central discovering Peripherals in the real world (not just in the mock).

If we run the app on the Mac, in Central Mode, we will get this:

The Initial Center Screen Now

Followed by this screen (once we start another device in Peripheral Mode):

The Screen After Finding A Device

It should be noted that it could take up to 30 seconds or so to see the Peripheral (or it could happen instantly).

Clicking on the device now gives us this screen:

Note The Device Name, Now

Unfortunately, you can ask a question, and it won’t do anything. We need to establish the Peripheral capabilities to handle questions, and the Central’s capabilities to receive the answer.

Next, let’s get the Central working the rest of the way…