Skip to content

CoreBluetooth abstraction layer for iOS and macOS development environments. Powered by Combine.

License

Notifications You must be signed in to change notification settings

Henryforce/BLECombineKit

Repository files navigation

BLECombineKit

badge-platforms badge-spm

CoreBluetooth abstraction layer for iOS and macOS development environments.

  • Swift Concurrency compatible
  • SwiftUI compatible
  • Apple's APIs dependencies only

It is currently supported on:

iOS 13.0+ macOS 10.15+

How to use

As simple as creating a CBCentralManager and let the reactive magic of Combine do the rest:

import CoreBluetooth
import Combine
import BLECombineKit

...

let centralManager = BLECombineKit.buildCentralManager(with: CBCentralManager())

let serviceUUID = CBUUID(string: "0x00FF")
let characteristicUUID = CBUUID(string: "0xFF01")
// Connect to the first peripheral that matches the given service UUID and observe a specific
// characteristic in that service.
centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
    .first()
    .flatMap { $0.peripheral.connect(with: nil) }
    .flatMap { $0.discoverServices(serviceUUIDs: [serviceUUID]) }
    .flatMap { $0.discoverCharacteristics(characteristicUUIDs: nil) }
    .filter { $0.value.uuid == characteristicUUID }
    .flatMap { $0.observeValueUpdateAndSetNotification() }
    .sink(receiveCompletion: { completion in
        print(completion)
    }, receiveValue: { data in
        print(data.value)
    })
    .store(in: &disposables)

And with Swift Concurrency, it would look like this:

import CoreBluetooth
import Combine
import BLECombineKit

...

let centralManager = BLECombineKit.buildCentralManager(with: CBCentralManager())

let serviceUUID = CBUUID(string: "0x00FF")
let characteristicUUID = CBUUID(string: "0xFF01")
// Connect to the first peripheral that matches the given service UUID and observe a specific
// characteristic in that service.
let stream = centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
    .first()
    .flatMap { $0.peripheral.connect(with: nil) }
    .flatMap { $0.discoverServices(serviceUUIDs: [serviceUUID]) }
    .flatMap { $0.discoverCharacteristics(characteristicUUIDs: nil) }
    .filter { $0.value.uuid == characteristicUUID }
    .flatMap { $0.observeValueUpdateAndSetNotification() }
    .values
    
Task {
  for try await value in stream {
    print("Value received \(value)")
  }
}

Installation

Swift Package Manager

In Xcode, select File --> Swift Packages --> Add Package Dependency and then add the following url:

https://github.com/Henryforce/BLECombineKit

About

CoreBluetooth abstraction layer for iOS and macOS development environments. Powered by Combine.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages