A small library that adds concurrency to CoreBluetooth APIs.
Start scanning by calling the central manager's scanForPeripherals
function. It returns an AsyncStream
you can use to iterate over the
discovered peripherals. Once you're satisfied with your scan, you can
break from the loop and stop scanning.
let centralManager = CentralManager()
try await centralManager.waitUntilReady()
let scanDataStream = try await centralManager.scanForPeripherals(withServices: nil)
for await scanData in scanDataStream {
// Check scan data...
}
await centralManager.stopScan()
Once you have your peripheral, you can use the central manager to connect to it. Note you must hold a reference to the Peripheral while it's connected.
try await centralManager.connect(peripheral, options: nil)
The central manager publishes several events. You can subscribe to them by using the eventPublisher
.
centralManager.eventPublisher
.sink {
switch $0 {
case .didConnectPeripheral(let peripheral):
print("Connected to \(peripheral.identifier)")
default:
break
}
}
.store(in: &cancellables)
See CentralManagerEvent to see available events.
You can use convenience functions for reading characteristics. They will find the characteristic by using a UUID
, and
parse the data into the appropriate type.
let value: String? = try await peripheral.readValue(
forCharacteristicWithUUID: UUID(uuidString: "")!,
ofServiceWithUUID: UUID(uuidString: "")!
)
Similar to reading, we have convenience functions for writing to characteristics.
try await peripheral.writeValue(
value,
forCharacteristicWithUUID: UUID(uuidString: "")!,
ofServiceWithUUID: UUID(uuidString: "")!
)
To get notified when a characteristic's value is updated, we provide a publisher you can subscribe to:
let characteristicUUID = CBUUID()
peripheral.characteristicValueUpdatedPublisher
.filter { $0.uuid == characteristicUUID }
.map { try? $0.parsedValue() as String? } // replace `String?` with your type
.sink { value in
print("Value updated to '\(value)'")
}
.store(in: &cancellables)
You can find practical, tasty recipes for how to use AsyncBluetooth
in the
AsyncBluetooth Cookbook.
This library can be installed using the Swift Package Manager by adding it to your Package Dependencies.
Licensed under MIT license.
link |
Stars: 110 |
Last commit: 3 days ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics