如何解决在循环中编写 BLE 命令不会得到所有响应 - Swift
我正在开发一个项目 (Swift) 以连接到 OBDII 设备。目前我的问题是 BLE 设备。
当我单独发送命令时,我能够成功发送命令(写入):
private func sendBT_Command(theCommand: String) {
if let myPeripheral = myPeripheral,let writeCharacteristic = writeCharacteristic {
let completeCommand = "\(theCommand)\r\n"
let commandData = Data(completeCommand.utf8)
myPeripheral.writeValue(commandData,for: writeCharacteristic,type: .withResponse)
} else {
print("NO CONNECTION")
}
}
我单独发送的命令是:
ATZ、ATST32、ATH1、ATE0 .... 等。
在 didUpdateValues 委托中...
func peripheral(_ peripheral: CBPeripheral,didUpdateValueFor characteristic: CBCharacteristic,error: Error?) {
if let value = characteristic.value {
let resultString = String(decoding: value,as: UTF8.self)
if hasTermination(aResponse: resultString) {
receivedResponse = true
}
let finalString = resultString.replacingOccurrences(of: "\n",with: "")
.replacingOccurrences(of: "\r",with: "")
.replacingOccurrences(of: ">",with: "")
if !finalString.isEmpty {
print("Data received : \(finalString)")
}
}
}
我收到数据很好,只要我一个一个发送命令(我现在使用的是表格视图)
问题!!!
如果我创建一个循环来发送命令,如下所示,会发送多个命令,但只收到一个响应。我什至可以看到我的设备在发送数据时闪烁。
while runLoop == true {
// Even If I make it sleep for a second,doesn't wok
// Thread.sleep(forTimeInterval: 1.0)
sendBT_Command(theCommand: "0105")
}
知道为什么我可以在使用 LOOP 时发送和接收响应吗?
提前致谢!
解决方法
该设备具有 AT 协议,这表明它具有类似串行的特性。在收到确认写入的响应之前,您正在发送下一个值。 iOS 将此视为“将值设置为 1,不将其设置为 2,不将其设置为 3”,并且在这种情况下它可能只发送 3。添加 sleep 根本没有帮助,因为这只会阻止发送消息(您正在休眠发送消息的线程)。
相反,您需要将它们排列成一个数组,并在收到每个响应 (didUpdateValueFor...) 时发送下一个。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。