Bluetooth mapping in Swift

Overview

Bluetonium: Bluetooth library in Swift

Bluetonium is part of the E-sites iOS Suite.


Bluetonium is a Swift Library that makes it easy to communicate with Bluetooth devices.

forthebadge forthebadge forthebadge

Build Status CocoaPods Compatible codecov Carthage compatible Platform Quality

Features

  • 🎲 Services and characteristics mapping
  • 👓 Default data transformers
  • 🔧 Reading & writing to peripherals
  • 🌔 Background mode
  • 📻 Scanning and connecting to peripherals
  • 🦅 Swift 3 & 4

Requirements

  • iOS 8.0+
  • Xcode 7.2+

Installation

CocoaPods

Add the following to your Podfile:

pod 'Bluetonium'

Make sure that you are integrating your dependencies using frameworks: add use_frameworks! to your Podfile. Then run pod install.

Carthage

Add the following to your Cartfile:

github "e-sites/Bluetonium"

Run carthage update and follow the steps as described in Carthage's README.

Usage

Get devices

The Manager will handle searching for devices and connecting to them.

import Bluetonium

let manager = Manager()
manager.delegate = self
manager.startScanForDevices()

If a device is found you will get notified by the func manager(_ manager: Manager, didFindDevice device: Device) delegate call. You can also get all found devices in the foundDevices array of your manager.

Connect to a device

Connecting to a device is simple.

manager.connect(with: device)

The device is a device form the foundDevices array.

Create and register a ServiceModel

A ServiceModel subclass will represents a Service, all the properties represent the Characteristics.

This example represents the Battery Service

class BatteryServiceModel: ServiceModel {
	enum Characteristic : String {
		case batteryLevel = "2A19"
	}

	var batteryLevel: UInt8 = 0
	
	override var serviceUUID:String {
		return "180F"
	}
	
	override func mapping(_ map: Map) {
		batteryLevel <- map[Characteristic.batteryLevel.rawValue]
	}
	
}

Register a ServiceModel subclass. Make sure you do this before the device is actually connected.

let batteryServiceModel = BatteryServiceModel()

func manager(_ manager: Manager, willConnectToDevice device: Device) {
	device.register(serviceModel: batteryServiceModel)
}

ServiceModel subclass

A ServiceModel subclass will represents a Service, all the properties represent the Characteristics. Interacting with the peripheral is only possible once the characteristic did became available through the func characteristicBecameAvailable(withUUID UUID: String) function.
Or when the serviceReady boolean is set to true.

It's recommended to create a struct containing static properties of the UUID's along with your ServiceModel this way your app doesn't have to hardcode the UUID in different places and prevents errors. (See example: HeartRateServiceModel in project)

Reading

batteryServiceModel.readValue(withUUID: "2A19")

// Or with completion
batteryServiceModel.readValue(withUUID: "2A19") { value in
	print(value)
}

Writing

batteryServiceModel.batteryLevel = 10
batteryServiceModel.writeValue(withUUID: "2A19")

Custom DataTransformers

It is possible that your characteristic has a custom data format or has a data format not yet supported. Then you can create your own custom DataTransformer for that property.

The custom DataTransformer needs to conform to the DataTransformer protocol which has two functions.

class HeartRateDataTransformer: DataTransformer {
    
    func transform(dataToValue data: Data?) -> MapValue {
    	// Used when reading from the characteristic.
    	// Transform Data to your property MapValue.
    }
    
    func transform(valueToData value: MapValue?) -> Data {
    	// Used when writing to the characteristic.
    	// Transform your property MapValue to Data.
    }
    
}

To register your custom DataTransform you can add it to the mapping function:

func mapping(_ map: Map) {
	heartRate <- (map["2A37"], HeartRateDataTransformer())
}

Set notifications for a characteristic

The ServiceModel has a function that will let you register for value changes on the peripheral. When you return true for one of you characteristics it will automatically update the property.

func registerNotifyForCharacteristic(withUUID UUID: String) -> Bool

Contributions

Feedback is appreciated and pull requests are always welcome. Let's make this list longer!

License

Bluetonium is released under the MIT license. See LICENSE for details.

You might also like...
Bluetooth mesh messaging SDK for apps

Berkanan SDK Berkanan SDK enables Bluetooth mesh messaging between nearby apps. It's the framework used by Berkanan Messenger (Product Hunt, TechCrunc

Fluetooth - Flutter library for sending bytes to Bluetooth devices on Android/iOS

A Flutter library for sending bytes to Bluetooth devices. Available on Android a

MiniVendingMachine - SwiftUI demo Apple Watch app to open a mini vending machine via bluetooth

Mini Vending Machine Use Apple Watch to open vending machine cells. Note: This a

An open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps

PeerKit An open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps Usage // Automatically detect and attach to

FileManagerExample - File Manager Example With Swift

FileManagerExample FileManager를 쉽게 설명하기 위한 문서입니다. let fileManager = FileMana

An app for questioning people to try on different names and pronouns. A winner of the Swift Student Challenge 2022.
An app for questioning people to try on different names and pronouns. A winner of the Swift Student Challenge 2022.

DiscoverMe is an app for questioning, trans, nonbinary, and gender-nonconforming people to try on different names and pronouns that better suit their

The official Swift Library for Vital API, HealthKit and Devices

vital-ios The official Swift Library for Vital API, HealthKit and Devices Install We currently support SPM. Documentation Please refer to the official

Swift implementation of Xiaomi's BLE authentication

MiAuth Xiaomi M365/Mi Authentication library written in Swift. Features M365 Authentication Mi Authentication (WIP - Login doesn't work reliably yet)

BLE (Bluetooth LE) for U🎁 Bleu is the best in the Bluetooth library.
BLE (Bluetooth LE) for U🎁 Bleu is the best in the Bluetooth library.

Bleu Bleu is a Bluetooth library. Bleu is the easiest way to operate CoreBluetooth. Bleu is possible to operate by replacing Bluetooth 's Peripheral a

Swift Featured Projects in brain Mapping
Swift Featured Projects in brain Mapping

Swift 开源精选   自 2014年 WWDC 发布 Swift 语言以来,本项目 一直致力于将主流 Swift 中文学习、开发资源汇集于此,并且尽力紧密地跟踪、甄选优秀 Swift 开源项目,以方便开发者快速获得并使用。考虑 Swift 已经正式发布超过四年半(更无力管理维护海量的 Swift

Decodable Simple and strict, yet powerful object mapping made possible by Swift 2's error handling.

Decodable Simple and strict, yet powerful object mapping made possible by Swift 2's error handling. Greatly inspired by Argo, but without a bizillion

CRUD is an object-relational mapping (ORM) system for Swift 4+.

CRUD is an object-relational mapping (ORM) system for Swift 4+. CRUD takes Swift 4 Codable types and maps them to SQL database tables. CRUD can create tables based on Codable types and perform inserts and updates of objects in those tables. CRUD can also perform selects and joins of tables, all in a type-safe manner.

Simple JSON Object mapping written in Swift

ObjectMapper ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

iOS App that allows a pilot to check drone photo collection after a mapping mission for any issues
iOS App that allows a pilot to check drone photo collection after a mapping mission for any issues

DronePhotoChecker iOS App that allows a pilot to check drone photo collection after a mapping mission for any issues. Features: Connects to DJI drone

Campus Atlas -- a Mapping & GIS solution which provides easy access to navigating the campus around you.
Campus Atlas -- a Mapping & GIS solution which provides easy access to navigating the campus around you.

Campus Atlas Welcome to Campus Atlas -- a Mapping & GIS solution which provides easy access to navigating the campus around you. Technical Implementat

WhirlyGlobe-Maply is a mapping toolkit with two parts, hence the dash.
WhirlyGlobe-Maply is a mapping toolkit with two parts, hence the dash.

What is WhirlyGlobe-Maply? WhirlyGlobe-Maply is a mapping toolkit with two parts, hence the dash. The WhirlyGlobe part is an interactive 3D globe. The

Manage multi-domain url auto mapping ip address table.
Manage multi-domain url auto mapping ip address table.

Domainer Multi-domain mapper. This library provides manage multi-domain table. Features Manage multi-domain mapping main domain. Find best domain whic

DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features 🛡 Typed network resources 🏠 Value oriented architecture 🔀 Exchangeable implementations 🚄 Extendable API 🎹 Composable

Comments
  • Fix: Carthage support is broken

    Fix: Carthage support is broken

    In the current master, using the repository with carthage fails as it cannot find the shared framework scheme for the framework as no target exists. The proper way is to have a project with two targets: one for the framework and one for the example.

    This pull request does that and also maintain compatibility with Cocoapod.

    opened by zittix 3
  • Problem when writing to a Serial Service

    Problem when writing to a Serial Service

    I implemented a serial service model, that will write and read. A problem when trying to write...in the writeValue() method of ServiceModel the transformer(forUUID: UUID) return nill as no characteristic for this was found.

    What is happening?

    This is my SerialServiceMode:

    import Foundation
    import Bluetonium
    import CoreBluetooth
    
    struct SerialServiceModelConstants {
        static let serviceUUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
        static let serialWriteUUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
        static let serialReadUUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
    
    }
    
    class SerialServiceModel : ServiceModel{
        weak var delegate : SerialServiceModelDelegate?
    
        var recentMessage : NSData = NSData()
        var sendMessage : NSData = NSData()
    
        override func serviceUUID() -> String {
            return SerialServiceModelConstants.serviceUUID
        }
    
        override func mapping(map: Map) {
            recentMessage <- map[SerialServiceModelConstants.serialReadUUID]
            sendMessage <- map[SerialServiceModelConstants.serialWriteUUID]
        }
    
        override func registerNotifyForCharacteristic(withUUID UUID: String) -> Bool {
            print("Serial Register Notify Become Available \(UUID)")
            return true
        }
    
        override func characteristicBecameAvailable(withUUID UUID: String) {
            readValue(withUUID: UUID)
            print("Serial Service Characteristic Become Available \(UUID)")
        }
    
        override func characteristicDidUpdateValue(withUUID UUID: String) {
            if UUID == SerialServiceModelConstants.serialReadUUID{
                dispatch_async(dispatch_get_main_queue()) { () -> Void in
                    self.delegate?.receiveFromSerial(String(data: self.recentMessage, encoding: NSUTF8StringEncoding)!)
                }
            }
        }
    
    
        func writeToSerial(withInfo text : String){
            self.sendMessage = text.dataUsingEncoding(NSUTF8StringEncoding)!
            self.writeValue(withUUID: SerialServiceModelConstants.serialWriteUUID)
            self.sendMessage = NSData()
        }
    
    }
    
    protocol SerialServiceModelDelegate: class {
        func receiveFromSerial(serialPrint : String)
    }
    
    opened by bocalexandru 1
  • Correct the spelling of CocoaPods in README

    Correct the spelling of CocoaPods in README

    This pull requests corrects the spelling of CocoaPods 🤓 https://github.com/CocoaPods/shared_resources/tree/master/media

    opened by ReadmeCritic 0
  • Connect but no write

    Connect but no write

    I’m having this issue I am able to list devices, then to connect to the chosen one but when I trie to write value, nothing happens I’m ina hurry and didn’t mind to pay for the service of helping me out solving this as is due on Thursday contact please at [email protected]

    opened by bastida117 1
Releases(1.0.1)
Owner
E-sites
E-sites is a full service internet agency with offices in Breda (NL)
E-sites
Bluejay is a simple Swift framework for building reliable Bluetooth LE apps.

Bluejay is a simple Swift framework for building reliable Bluetooth LE apps. Bluejay's primary goals are: Simplify talking to a single Bluetooth LE pe

Steamclock Software 1k Dec 13, 2022
The Bluetooth LE library for iOS and Mac. 100% Swift.

iOS-BLE-Library An in-development Bluetooth Low Energy Library by Nordic Semiconductor to interact with the , which is not complicated, but requires w

Nordic Semiconductor 6 Dec 19, 2022
iOS Bluetooth LE framework

Features A futures interface replacing protocol implementations. Timeout for Peripheral connection, Service scan, Service + Characteristic discovery a

Troy Stribling 696 Dec 25, 2022
RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant.

RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant. It's backed by RxSwift and CoreBluetooth and it prov

Polidea 1.3k Jan 6, 2023
Omnipod Bluetooth PumpManager For Loop

OmniBLE Omnipod Bluetooth PumpManager For Loop Status This module is at the very beginning stages of development and does not even compile yet. DO NOT

Randall Knutson 20 Apr 21, 2022
Build your own 'AirTags' 🏷 today! Framework for tracking personal Bluetooth devices via Apple's massive Find My network.

OpenHaystack is a framework for tracking personal Bluetooth devices via Apple's massive Find My network.

Secure Mobile Networking Lab 5.8k Jan 9, 2023
Diabetes: test the FreeStyle Libre glucose sensor as a Bluetooth Low Energy device, even directly from an Apple Watch.

Since the FreeStyle Libre 2 / 3 glucose sensors are Bluetooth Low Energy devices, I am trying to leverage their capabilities to implement something ne

Guido Soranzio 6 Jan 2, 2023
Simple, block-based, lightweight library over CoreBluetooth. Will clean up your Core Bluetooth related code.

LGBluetooth Simple, block-based, lightweight library over CoreBluetooth. Steps to start using Drag and Drop it into your project Import "LGBluetooth.h

null 170 Sep 19, 2022
The easiest way to use Bluetooth (BLE )in ios,even bady can use.

The easiest way to use Bluetooth (BLE )in ios,even bady can use.

刘彦玮 4.6k Dec 27, 2022
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.

ExtendaBLE Introduction ExtendaBLE provides a very flexible syntax for defining centrals and peripherals with ease. Following a blocks based builder a

Anton 94 Nov 29, 2022