为什么通过从输入缓冲区读取而捕获对python串行端口输出缓冲区的写入

时间:2018-12-01 12:34:52

标签: python multithreading serial-port

我试图将命令写入python串行端口,并且 在输入上捕获来自连接设备的响应 端口缓冲区的通道。

我需要捕获这些读取以及它们发生的时间,因此我创建了一个 读取输入缓冲区是否为空的线程。

运行程序时,我看到输出到输出的数据 串口输入缓冲区上的缓冲区。

我创建的代码如下所示:

import threading
import serial
import json
import time


def handle_data(data):
    print(data)


def read_from_port(serPort):
        while True:
            if serPort.in_waiting > 0:
                # print("in:", serPort.in_waiting)
                reading = serPort.read(serPort.in_waiting).decode('ascii')
                handle_data(reading)
            time.sleep(0.1)


ser = serial.Serial(
  port='COM15',
  baudrate=115200,
  timeout=0
)

thread = threading.Thread(target=read_from_port, args=(ser,))
thread.start()

print(ser.name)

jsonDict = {
    'c': 120,
    'i': 0,
    'p': '',
}

i = 1
while i < 1000:
    jsonDict["i"] = i
    if i%2 == 0:
        cmd = (2 << 8) | 0
        payload = "local"
    else:
        cmd = (1 << 8) | 100
        payload = "remote"

    jsonDict["c"] = cmd
    jsonDict["p"] = payload
    output = json.dumps(jsonDict) + '\r'
    ser.write(output)
    i = i + 1
    time.sleep(1)

ser.close()

要测试python功能,我目前正在路由 数据通过有效负载“本地”发送到连接的设备,并返回到计算机。

但是,读取线程同时捕获了发送的数据和返回的数据,请参见下文:

COM15


{"i": 1, "p": "remote", "c": 356}

{"i": 2, "p": "local", "c": 512}

{"i": 2, "p": "local", "c": 512}
{"i": 3, "p": "remote", "c": 356}

{"i": 4, "p": "local", "c": 512}

{"i": 4, "p": "local", "c": 512}
{"i": 5, "p": "remote", "c": 356}

{"i": 6, "p": "local", "c": 512}

{"i": 6, "p": "local", "c": 512}
{"i": 7, "p": "remote", "c": 356}

{"i": 8, "p": "local", "c": 512}

{"i": 8, "p": "local", "c": 512}
{"i": 9, "p": "remote", "c": 356}

任何想法!

1 个答案:

答案 0 :(得分:0)

问题不在您的代码中。您可能可以打开PuttyTera-Term终端并看到完全相同的行为-一些设备可以选择回显已发送的命令(这在从终端工作时很有用)。 您没有说出正在使用的设备,但是可能可以对其进行配置-在设备上搜索“ echo”配置。 更奇特的问题可能是Tx线在连接线上某处短接到Rx线,但只有在消除回声配置后,我才会进行检查。

如果无法配置回显,则只需用代码处理即可。

相关问题