我试图将命令写入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}
任何想法!