You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RxCharacteristic的WriteValue中调用TxCharacteristic的send_tx方法?

解决方案

直接调用TxCharacteristic类肯定没用,因为send_tx是实例方法,必须用该类的具体实例来调用。两个特征都属于同一个UartService,所以通过服务来关联是最直接的方式,下面给两种可行的修改方式:

方式一:在服务中保存Tx特征实例(推荐)

先修改UartService的初始化方法,把Tx特征的实例存为服务的属性:

class UartService(Service):
    def __init__(self, bus, index):
        Service.__init__(self, bus, index, UART_SERVICE_UUID, True)
        # 保存Tx特征实例为服务属性
        self.tx_characteristic = TxCharacteristic(bus, 0, self)
        self.add_characteristic(self.tx_characteristic)
        self.add_characteristic(RxCharacteristic(bus, 1, self))

然后修改RxCharacteristic的WriteValue方法,通过服务拿到Tx实例并调用send_tx:

def WriteValue(self, value, options):
    received_content = bytearray(value).decode()
    print('remote: {}'.format(received_content))
    # 调用Tx特征的send_tx方法
    self.service.tx_characteristic.send_tx(received_content)

方式二:从服务的特征列表中查找Tx实例

如果不想修改UartService,可以在Rx的WriteValue里遍历服务的特征,找到TxCharacteristic的实例:

def WriteValue(self, value, options):
    received_content = bytearray(value).decode()
    print('remote: {}'.format(received_content))
    # 遍历服务的所有特征,找到TxCharacteristic实例
    for char in self.service.characteristics:
        if isinstance(char, TxCharacteristic):
            char.send_tx(received_content)
            break

为什么之前直接调用失败?

TxCharacteristic是类,send_tx是属于类实例的方法,直接用类调用实例方法会报错,必须拿到已创建的Tx特征实例才能正常调用。而通过所属的UartService来获取实例,是符合BLE服务-特征结构的合理做法。

内容的提问来源于stack exchange,提问作者GG BB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:05:32