BluetoothMessageProtocol
这不是手机端的 BLE 管理器。那里有大量的选择。BluetoothMessageProtocol 提供了编解码蓝牙特性数据的功能。
安装
BluetoothMessageProtocol 可通过 CocoaPods 获得。要安装它,只需将以下行添加到 Podfile 中:
pod 'BluetoothMessageProtocol'
Swift Package Manager
dependencies: [
.package(url: "https://github.com/FitnessKit/BluetoothMessageProtocol", from: "2.0.0")
]
Swift4
dependencies: [
.package(url: "https://github.com/FitnessKit/BluetoothMessageProtocol", .branch("swift42")),
]
使用方法
服务
Service 类有助于描述 BLE 服务。没有做出服务包含哪些特性的假设。
使用 CoreBluetooth 的示例
centralManager.scanForPeripherals(withServices: [CBUUID(string: ServiceHeartRate.uuidString),],
options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
支持的服务
- BLE SIG 服务
- 家居配件访问协议 (HAP)
- BLE 网状网
特征值
每个蓝牙特征值都有一个编码和解码方法。当您从传感器接收数据时,您调用静态解码方法将数据转换成特征值对象,如下例所示:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let sensorData = characteristic.value {
if characteristic.uuid.uuidString == CharacteristicHeartRateMeasurement.uuidString {
doDecodeHRMess(sensorData: sensorData)
}
if characteristic.uuid.uuidString == CharacteristicBodySensorLocation.uuidString {
doDecodeBody(sensorData: sensorData)
}
}
}
func doDecodeHRMess(sensorData: Data) {
let hrData: Result<CharacteristicHeartRateMeasurement, BluetoothDecodeError> = CharacteristicHeartRateMeasurement.decode(with: sensorData)
switch hrData {
case .success(let char):
print("HR: \(char.heartRate)")
case .failure(let error):
print(error)
}
/// Or you can stil use the doCatch
do {
let hrData = try CharacteristicHeartRateMeasurement.decode(with: sensorData).get()
print("HR: \(hrData.heartRate)")
} catch {
print(error)
}
}
func doDecodeBody(sensorData: Data) {
let sensor: Result<CharacteristicBodySensorLocation, BluetoothDecodeError> = CharacteristicBodySensorLocation.decode(with: sensorData)
switch sensor {
case .success(let char):
print("Location: \(char.sensorLocation.stringValue)")
case .failure(let error):
print(error)
}
/// Or you can stil use the doCatch
do {
let sensor = try CharacteristicBodySensorLocation.decode(with: sensorData).get()
print("Location: \(sensor.sensorLocation.stringValue)")
} catch {
print(error)
}
}
制造商特定数据
制造商特定数据包含一个由公司分配的编号和制造商定义的特定数据。
使用 Apple iBeacon 的示例
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let advertData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
switch ManufacturerDataAppleiBeacon.decode(with: advertData) {
case .success(let beacon):
print(beacon.proximityUUID.uuidString)
case .failure(let error):
print(error)
}
/// Or you can stil use the doCatch
if let beacon = try? ManufacturerDataAppleiBeacon.decode(with: advertData).get() {
print(beacon.proximityUUID.uuidString)
}
}
}
制造商特定数据
- Apple iBeacon
- AltBeacon
- HomeKit
- HomeKit 加密通知广告
- Polar 心率
作者
此软件包由 Kevin A. Hoogheem 开发和维护
许可证
BluetoothMessageProtocol 在 MIT 许可协议 下提供