Reading a BLE Peripheral Characteristic and checking its value?

女生的网名这么多〃 提交于 2019-11-28 23:58:04
Travis Griggs

Updated For Swift3

After you execute that method, the delegate of your peripheral is going to asynchronously receive the peripheral(_:didUpdateValueFor:error:) method. In that method you can query the value of the passed characteristic parameter. value will be an NSData which you can pull the bytes out of. E.g.

// MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if let e = error {
        print("ERROR didUpdateValue \(e)")
        return
    }
    guard let data = characteristic.value else { return }
    ...
}

The value method actually returns an Optional around the expected Data, so a let guard is the way to go.

Usually a characteristic will have a simple value encoded in it's up-to-20-byte Data payload. E.g. maybe it's a simple UInt16 counter. To

To convert between these Data glumps and meaningful numbers, have a look at the answer to round trip Swift number types to/from Data (I've included my own implementation of that below).

So for example, if you know that the characteristic of interest is some counter that is a meant to be extracted as a UInt16, I would fill out the above example with something like:

// MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if let e = error {
        print("ERROR didUpdateValue \(e)")
        return
    }
    guard let data = characteristic.value else { return }
    print("counter is \(UInt16(data:data))")
}



// Data Extensions:
protocol DataConvertible {
    init(data:Data)
    var data:Data { get }
}

extension DataConvertible {
    init(data:Data) {
        guard data.count == MemoryLayout<Self>.size else {
            fatalError("data size (\(data.count)) != type size (\(MemoryLayout<Self>.size))")
        }
        self = data.withUnsafeBytes { $0.pointee }
    }

    var data:Data {
        var value = self
        return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }
}

extension UInt8:DataConvertible {}
extension UInt16:DataConvertible {}
extension UInt32:DataConvertible {}
extension Int32:DataConvertible {}
extension Int64:DataConvertible {}
extension Double:DataConvertible {}
extension Float:DataConvertible {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!