Wrap Core Bluetooth Callbacks to Async/Wait

189 views Asked by At

I would like to convert the concept of Core-Bluetooth's methods with callbacks into methods that use async/wait to make my code more readable.

eg: Reading a characteristic requires

  • Read: peripheral.readValue(for: characteristic)
  • Handle the response in public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)

I'd like to have something like: func read(for characteristic: CBCharacteristic) async throws -> [UInt8] and this tried using withCheckedThrowingContinuation to implements this

So for reading I use

let (_, char) = try await withCheckedThrowingContinuation({ (continuation: ReadValueCheckedContinuation) in
   self.readContinuation = continuation
   peripheral.readValue(for: characteristic)
})

In the callback I have

// in case of success
r.resume(returning: (peripheral, characteristic))

This works fine for single reads. If I run multiple reads in a sequence, the reads don't wait for the result of the previous callbacks, which causes trouble. Any suggestion on how to synchronize this?

0

There are 0 answers