manolofdez / AsyncBluetooth

A small library that adds concurrency to CoreBluetooth APIs.
MIT License
160 stars 30 forks source link

Notify support #25

Closed conrad-scherb closed 1 year ago

conrad-scherb commented 1 year ago

Does this library support subscribing to notifications? I can't find anywhere to attach a callback to execute on receiving a notify message. If so, could an example please be provided and placed on the "Usage" page in the readme for this library, as notifications aren't mentioned at all on that page or in the examples cookbook.

manolofdez commented 1 year ago

Hi! The library supports notifications for some central manager events (didUpdateState, willRestoreState, didConnectPeripheral and didDisconnectPeripheral), and for characteristic value updates from a peripheral. It uses Combine instead of NotificationCenter to publish events.

To subscribe to the central manager:

centralManager.eventPublisher
    .sink {
        switch $0 {
        case .didConnectPeripheral(let peripheral): // replace with the event you want to listen to
            print("Connected to \(peripheral.identifier)")
        default:
            break
        }
    }
    .store(in: &cancellables)

To subscribe to a peripheral:

peripheral.characteristicValueUpdatedPublisher
    .filter { $0.uuid == characteristicUUID } // replace `characteristicUUID` with your UUID
    .map { try? $0.parsedValue() as String? } // replace `String?` with your type
    .sink { value in
        // do something with value
    }
    .store(in: &cancellables)

I'll add this to the README. Thanks for flagging!

conrad-scherb commented 1 year ago

Cheers for providing that documentation - have notify working now, thanks!