我正在开发一个连接到 OBDII 设备的项目 (Swift)。目前我的问题与 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 委托(delegate)中...
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)")
}
}
}
只要我一一发送命令,我就能很好地接收数据(我现在使用的是表格 View )
问题!!!
如果我创建一个循环来发送命令,如下所示,则会发送多个命令,但只收到一个响应。我什至可以看到我的设备正在闪烁发送数据。
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 协议(protocol),这表明它具有类似串行的特性。在收到确认写入的响应之前,您将发送下一个值。 iOS 将此视为“将值设置为 1,不将其设置为 2,不将其设置为 3”,在这种情况下它可能只发送 3。添加 sleep 根本没有帮助,因为这只会阻止消息发送(您正在休眠发送消息的线程)。
相反,您需要将它们排队到一个数组中,当您收到每个响应 (didUpdateValueFor...) 时,发送下一个响应。
关于swift - 在循环上编写 BLE 命令无法获得所有响应 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65998509/