gpt4 book ai didi

如果我 readValue,iOS BLE 外设 writeValue 不起作用

转载 作者:行者123 更新时间:2023-11-30 10:57:34 28 4
gpt4 key购买 nike

我在 MacOS 应用程序中有一个外围设备,在 iOS 应用程序中有一个中心设备。中央有如下代码:

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
print(characteristic.uuid)
switch characteristic.uuid {
case bleCharacteristics().read:
print("Read it!")
peripheral.setNotifyValue(true, for: characteristic)
peripheral.readValue(for: characteristic)
break
case bleCharacteristics().write:
print("Write to it!")
peripheral.writeValue("Heyooo".data(using: .utf8)!, for: characteristic, type: .withResponse)
break
case bleCharacteristics().notify:
print("Subscribe to it!")
peripheral.setNotifyValue(true, for: characteristic)
break
default:
print("Got to the characteristics default somehow")
}
}
}

readValue 工作正常,但 writeValue 根本不起作用(因为在 PeripheralManager 的 didReceiveWriteRequests 中永远不会被调用)。如果我注释掉 readValue 那么 writeValue 就可以正常工作。文档中没有任何地方说 readValue 是阻塞异步操作或类似的操作,所以我不知道发生了什么。

如果有人知道我做错了什么,我将非常感激。

最佳答案

有时候你必须发布问题才能找到答案。在我的外围代码中,我有:

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
let response = "Hey there".data(using: .utf8)
request.value = response
peripheral.updateValue(response!, for: characteristics![0] as! CBMutableCharacteristic, onSubscribedCentrals: [request.central])
}

由于 updateValue 方法,它正在“读取”值,但没有关闭读取请求。添加行:

peripheral.respond(to: request, withResult: .success)

是响应读取请求的正确方法,并使 writeValue 按预期工作。正确的外围代码:

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
let response = "Hey there".data(using: .utf8)
request.value = response
peripheral.respond(to: request, withResult: .success)
}

关于如果我 readValue,iOS BLE 外设 writeValue 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771712/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com