python - 如何用python找到串行流的第一个字节?

标签 python python-3.3 pyserial

我正在尝试使用 python 3.3.2 和 pyserial 从 RS232 读取数据流。我开始直播:

ser = serial.Serial('/dev/ttyUSB0', baudrate=19200, timeout=3, stopbits=serial.STOPBITS_TWO)
ser.write(bytes([0x05, 0x69, 0x02, 0x0A, 0x86]))

此后我每秒都会得到一个 107 字节长的数据集。第一个字节应为 107(字节数),第二个字节应为 105(代码)。

分隔以 107 和 105 开头的 107 字节长数据集的最佳方法是什么?如果我使用 print(ser.read(107)) 几次,我会得到:

b'\x00\x00\x00\x00\x00P\xbf\x99\x10\xe0}\x86\xaaV\xd4\xeeg\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x87}i\xdf\n\x00\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc1\xc3k\x00\x00\x00\xc0t\xb4\xbd\xf0\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Y\x00\x00\x00\x00\x00\x00\x80\x01\x00\x80\xc7\x10\xc0\xcd\xe6G\x0b\x99\xd4\xcb.'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc5\xeck\x00\x00\x00\xc0\xf4\xb3\xbd\xf0\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0V\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\xc8\x10@\xcd\xe67\x8b\x99\xd4\x0b/\x00\x00@\x00\xf6\xb7\xbf\xfd\xed\xaf:\x00\x00\x00\xe8\xf3J\xaf\x04\x00\x00\x00\x00\x00p\xbf\x99\x18\xe0}\x86\xaaV\xd4\xeeg\x12\x00\x00\x00\x00\x00\x00\x00'

k(ascii 表示 107)位于中间的某个位置。

最佳答案

在提出请求之前刷新您的输入可能会有所帮助。即,

ser.read(ser.inWaiting())

读出所有正在等待的字节。然后,希望不再发送更多字节,您可以发送命令:

ser.write(bytes([0x05, 0x69, 0x02, 0x0A, 0x86]))

这应该确保接下来出现的所有字节都是对此命令的响应。

然后读取数据,直到得到 107:

found = False
buffer = '' # what is left from the previous run...
while not found:
    rd = ser.read(50)
    buffer += rd
    sp = buffer.split(chr(107), 1)
    if len(sp) == 2:
        pkt = chr(107) + sp[1] # candidate for a valid packet
        if pkt[1] == chr(105): # 
            while len(pkt) < 107: # TODO add a timeout condition here...
                rd = ser.read(107 - len(pkt))
                pkt += rd
            found = True
        else:
            buffer = pkt[1:] # process this further...
    else: # no 107 found; empty the buffer.
        buffer = ''
# Now we have a pkt of 107 bytes and can do whatever we want with it.

关于python - 如何用python找到串行流的第一个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19317766/

相关文章:

python - 如何为特定行和列中的numpy数组赋值

python - 为什么带参数的 object.__new__ 在 Python 2.x 中工作正常而不是在 Python 3.3+ 中工作?

python - 为什么 tk.IntVar 不适用于第二个 tk 窗口?

python - 为什么这个脚本在 python3 中比在 python2 中花费更多的时间?

python - 当我中断代码时如何关闭串行连接

python - Arduino 串行命令独立工作,但组合时没有任何反应

python - 实现重试装饰器比异常高一种方法

python - 如何在 Python 中生成指数增长的范围

python - Ubuntu 13.10 : No Module Named appindicator

python - http.client.RemoteDisconnected : Remote end closed connection without response SELENIUM/PYTHON