这**不是**你手机的 BLE 管理器。市面上已经有很多这样的管理器了。BluetoothMessageProtocol 提供了用于编码和解码蓝牙特征数据的函数。
BluetoothMessageProtocol 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod 'BluetoothMessageProtocol'
Swift Package Manager(Swift 包管理器)
dependencies: [
.package(url: "https://github.com/FitnessKit/BluetoothMessageProtocol", from: "2.0.1")
]
Service 类有助于描述 BLE 服务。它不假设该服务包含哪些特征。
使用 CoreBluetooth 的示例
centralManager.scanForPeripherals(withServices: [CBUUID(string: ServiceHeartRate.uuidString),],
options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
每个蓝牙特征都有一个编码和解码方法。当您从传感器接收到数据时,您调用静态解码方法将数据转换为特征对象,如下面的示例所示
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)
}
}
}
此软件包由 Kevin A. Hoogheem 开发和维护
BluetoothMessageProtocol 在 MIT 许可证下可用