【问题标题】:Getting response from BLE device从 BLE 设备获取响应
【发布时间】:2016-12-08 09:24:02
【问题描述】:

我对使用蓝牙设备很陌生。到目前为止,一切都很完美。但是有个问题不知道怎么处理。 我有一个 LED 灯设备,我可以在其中更改从颜色到速度、闪烁、褪色等的所有内容。 现在我想读取当前的设备状态(例如设备是打开还是关闭)。我有一份设备文件,上面写着:

查询: a) 发送指令:【0XEF】+【0X01】+【0X77】 b) 控制器响应: 【0X66】+【8bit设备名称(0x14)】+【8bit开关开启/关闭】+【8bit模式值】+【8bit运行/暂停状态】+【8bit速度值】+【8bit红色数据】+【8bit绿色数据】+【8bit蓝色数据】+【8bit暖边】+【8bit版本号】+【0X99】

如何获得控制器响应? 无论 write 调用是否成功, didWriteValueFor 函数都会返回给我。

【问题讨论】:

  • 你应该使用func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest])来接收数据
  • 外围设备可能支持 notify 的该特性。使用setNotify 打开通知,您将收到对didUpdateValueForCharacteristic 委托方法的调用

标签: ios swift3 bluetooth-lowenergy response


【解决方案1】:

如果特性支持通知,您可以使用该行关闭通知:

peripheral.setNotifyValue(true, for: characteristic)

将具有该特性的外围设备的委托设置为正确的文件非常重要,在我的例子中是:

peripheral.delegate = self

之后,当某些事情发生变化时,外围设备将在您的代码中触发此方法:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    //data is in characteristic.value
}

如果您的特征不支持通知,您可以尝试将数据写入外围设备,并将响应类型设置为 .withReponse,如下所示:

peripheral.writeValue(data, for: characteristic, type: .withResponse)

记得设置外设委托,之后外设会在每次成功写入后触发此方法:

    //write response
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        //data is in characteristic.value
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 2021-05-05
    • 2021-04-02
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多