问题描述
我正在尝试实现一个 BLE UART 服务,其中中央可以发送请求,外设接收该请求并将其转发给外设应用程序进行处理,然后将响应返回给中央。该设计类似于 https://punchthrough.com/serial-over-ble/
中的图 2最后一部分无法将数据返回到中央。
以下是我在实现 UART 时遇到的 tx/rx 特性
class TxCharacteristic(Characteristic):
def __init__(self,bus,index,service):
Characteristic.__init__(self,UART_TX_CHaraCTERISTIC_UUID,['notify'],service)
self.notifying = False
GLib.io_add_watch(sys.stdin,GLib.IO_IN,self.on_console_input)
def on_console_input(self,fd,condition):
s = fd.readline()
if s.isspace():
pass
else:
self.send_tx(s)
return True
def send_tx(self,s):
if not self.notifying:
return
value = []
for c in s:
value.append(dbus.Byte(c.encode()))
self.PropertiesChanged(GATT_CHRC_IFACE,{'Value': value},[])
def StartNotify(self):
if self.notifying:
return
self.notifying = True
def StopNotify(self):
if not self.notifying:
return
self.notifying = False
class RxCharacteristic(Characteristic):
def __init__(self,UART_RX_CHaraCTERISTIC_UUID,['write'],service)
def WriteValue(self,value,options):
data = bytearray(value).decode('utf-8')
print(f'Incoming UART data: {data}')
handle_request(data)
使用 BLE 扫描仪手机应用程序,我可以将数据写入 RxCharacteristic OK,当 RxCharacteristic 收到它时,我会调用 handle_request(data) 进行处理。
这就是我被卡住的地方。如何获取句柄或引用 TxCharacteristic 以便我可以调用 send_tx()? “通知”特征标志是我想要的还是我想要“写入”标志?
解决方法
通常使用 UART over BLE 的人使用 Notify
标志。中央设备(手机应用)需要启用通知,以便在值发生变化时收到通知。
使用 Nordic UART Service
(NUS) 通常是一个很好的例子。如果您确实实施了 NUS,那么有几个应用程序可以使用它。
查看您的代码,似乎有管道将您的控制台连接到 send_tx
方法。我怀疑您的应用没有执行 StartNotify
这是我在下图中用柠檬绿圈起来的图标。这来自 nRF Connect,它是一个通用的低功耗蓝牙扫描和探索工具。
像 Serial Bluetooth Terminal 这样的应用会自动为 NUS 做StartNotify