我打算使用Twisted实施python程序来与蓝牙设备进行通信。以下是我已实现的示例代码:

from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic

class DeviceBluetooth(basic.Int16StringReceiver):

    def connectionMade(self):
        print 'Connection made!'
        self.sendString('[01] help\n')

    def dataReceived(self, data):
        print"Response: {0}".format(data)

        print "-----"
        print "choose message to send: "
        print "1. Stim on"
        print "2. Stim off"
        print "3. Stim status"
        print "4. Help"
        # user input
        ch = input("Choose command :: ")
        if int(ch) == 1:
            self.sendString('[02] stim on\n')
        elif int(ch) == 2:
            self.sendString('[03] stim off\n')
        elif int(ch) == 3:
            self.sendString('[04] stim ?\n')
        elif int(ch) == 4:
            self.sendString('[05] help\n')
        else:
            reactor.stop()

SerialPort(DeviceBluetooth(), 'COM20', reactor, baudrate=115200)
reactor.run()


运行该程序时,有时会收到响应,而其他时候却什么也没收到。在大多数情况下,长时间的响应分散在下一条消息中。我必须通过超级终端确保通过蓝牙设备获得适当的响应。因此,问题必须出在我的代码上。

我的代码有做错什么吗?



附加修改/更正

当我将上述代码中的dataReceived()函数替换为stringReceived()时,程序永远不会进入此函数。

我还尝试使用LineReceiver协议在上述程序中进行如下操作:

from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic

class DeviceBluetooth(basic.LineReceiver):

    def connectionMade(self):
        print 'Connection made!'
        self.sendLine('[01] help')

    def dataReceived(self, data):
        print"Response: {0}".format(data)

        print "-----"
        print "choose message to send: "
        print "1. Stim on"
        print "2. Stim off"
        print "3. Stim status"
        print "4. Help"
        # user input
        ch = input("Choose command :: ")
        if int(ch) == 1:
            self.sendLine('[02] stim on')
        elif int(ch) == 2:
            self.sendLine('[03] stim off')
        elif int(ch) == 3:
            self.sendLine('[04] stim ?')
        elif int(ch) == 4:
            self.sendLine('[05] help')
        else:
            reactor.stop()

SerialPort(DeviceBluetooth(), 'COM20', reactor, baudrate=115200)
reactor.run()


与dataReceived函数中的碎片数据一样,我也遇到了同样的问题。

最佳答案

您的协议子类Int16StringReceiver使用两个字节(16位)长度的前缀实现消息成帧。但是,它会覆盖dataReceived,这是实现该框架的方法。这将禁用成帧,并且仅提供碰巧从连接中读取的任何字节-以碰巧要读取的任何大小。

当您为Int16StringReceiver子类时,您将改写stringReceived

关于python - 扭曲的串行端口dataReceived()提供分段数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18514015/

10-09 07:15