Giter VIP home page Giter VIP logo

swiftbluetooth's Introduction

SwiftBluetooth

Easily interface with Bluetooth peripherals in new or existing projects through modern async Swift API's.

Features

  • Parity with existing CoreBluetooth APIs for easy, incremental migration of existing projects
  • Modern, async-await API for discovery, connection, read/write, and more
  • Alternate callback-based API for codebases not using Swift Concurrency
  • Subscribe to peripheral discoveries, value updates, and more through AsyncStream
  • Easy await-ing of CentralManager state
  • Staticly typed characteristics
  • Thread safe
  • Zero inherited dependencies
  • Tested with included SwiftBluetoothMock library
  • SwiftUI support

Examples

API Documentation.

Migrate existing CoreBluetooth project

import CoreBluetooth
import SwiftBluetooth // Add this

// Override existing CoreBluetooth classes to use SwiftBluetooth
typealias CBCentralManager         = SwiftBluetooth.CentralManager
typealias CBCentralManagerDelegate = SwiftBluetooth.CentralManagerDelegate
typealias CBPeripheral             = SwiftBluetooth.Peripheral
typealias CBPeripheralDelegate     = SwiftBluetooth.PeripheralDelegate

// Your existing code should continue to work as normal.
// But now you have access to all the new API's!

Stream discovered peripherals

let central = CentralManager()
await central.waitUntilReady()

for await peripheral in await central.scanForPeripherals() {
  print("Discovered:", peripheral.name ?? "Unknown")
}

Define characteristics

// Define your characteristic UUID's as static members of the `Characteristic` type
extension Characteristic {
  static let someCharacteristic = Self("00000000-0000-0000-0000-000000000000")
}

// Use those characteristics later on your peripheral
await myPeripheral.readValue(for: .someCharacteristic)

Discover, connect, and read characteristic

let central = CentralManager()
await central.waitUntilReady()

// Find and connect to the first peripheral
let peripheral = await central.scanForPeripherals(withServices: [myService]).first!
try! await central.connect(peripheral)
defer { central.cancelPeripheralConnection(peripheral) }

// Discover services and characteristics
let service = try! await peripheral.discoverServices([myService]).first(where: { $0.uuid == myService })!
let _ = try! await peripheral.discoverCharacteristics([.someCharacteristic], for: service)

// Read characteristic value!
print("Got value:", await peripheral.readValue(for: .someCharacteristic))

Note Force-unwrapping is only used for brevity and is not recommended.

Callbacks

// Most of the stock CoreBluetooth methods have an additional new signature that takes a completionHandler

central.connect(peripheral) { result in
  if result == .failure(let error) {
    // Issue connecting
    return
  }

  // Connected!
}

Watching with callbacks

// Peristent tasks return a `CancellableTask` that needs to be cancelled when you're done

let task = central.scanForPeripherals { peripheral in
  print("Discovered:", peripheral.name ?? "Unknown")
}

// At some point later, cancel the task to stop scanning
task.cancel()

Note Calling central.stopScan() will also cancel any peripheral scanning tasks

Install

Xcode

Add https://github.com/exPHAT/SwiftBluetooth.git in the "Swift Package Manager" tab.

Swift Package Manager

Add SwiftBluetooth as a dependency in your Package.swift file:

let package = Package(
  ...
  dependencies: [
    // Add the package to your dependencies
    .package(url: "https://github.com/exPHAT/SwiftBluetooth.git", branch: "master"),
  ],
  ...
  targets: [
    // Add SwiftBluetooth as a dependency on any target you want to use it in
    .target(name: "MyTarget",
            dependencies: [.byName(name: "SwiftBluetooth")])
  ]
  ...
)

swiftbluetooth's People

Contributors

exphat avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.