python监听串口双方收发消息内容
使用说明
使用VSPD建立一组虚拟串口
查看MCU的端口号与波特率并修改python程序配置,运行即可看到双方收发的效果,相当于在MCU与上位机软件中间插入了一个监听双方通讯的打印程序
通过串口助手连接到虚拟串口并向其发送消息
即Python显示MCU端发给串口助手的消息,并显示串口助手发送至MCU的消息,中间使用VSPD与Python进行消息互转与打印。
应用场景:当需要分析设备与控制软件之间的收发命令时,通过VSPD与python在设备与控制软件中间架设一些列中间件来监听相互之间的消息
具体如下图示
Python监听串口收发双方程序
import serial
import threading
'''
通过监听MCU端与PC上位机软件的通讯,打印双方收发的消息
'''
# =============配置修改区==================
mcu_serial_config = {"MCU_serial": "COM19", "baud_rate": 115200}
vspd_serial_config = {"VSPD_A": "COM10", "VSPD_B": "COM11"}
# ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 配置修改区 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
class SerialLog:
def __init__(self, serial_config_dic, vspd_config=None):
if vspd_config == None:
vspd_config = {"VSPD_A": "COM10", "VSPD_B": "COM11"}
self.mcu_serial_num = serial_config_dic["MCU_serial"]
self.baud_rate = serial_config_dic["baud_rate"]
self.mcu_serial = serial.Serial(self.mcu_serial_num, self.baud_rate)
self.vspd_serial = serial.Serial(vspd_config["VSPD_A"], self.baud_rate)
self.is_running = True
# 创建两个线程
try:
thread1 = threading.Thread(target=self.listing_mcu)
thread2 = threading.Thread(target=self.listing_vspd)
thread1.start()
thread2.start()
except:
print(f"Error: 无法启动线程\n")
# 默认线程循环
try:
while 1:
pass
except KeyboardInterrupt as e:
# 捕获按键取消(ctrl+c)异常,结束2个子线程
self.is_running = False
print("\nthread end")
# 监听MCU端串口信息
def listing_mcu(self):
try:
while self.is_running:
if not self.mcu_serial.isOpen():
continue
data_size = self.mcu_serial.in_waiting
if data_size < 1:
continue
data = self.mcu_serial.read(data_size)
print(f'MCU:{data}')
self.vspd_serial.write(data)
finally:
print("\nmcu thread Done")
# 监听VSPD端串口信息
def listing_vspd(self):
try:
while self.is_running:
if not self.vspd_serial.isOpen():
continue
data_size = self.vspd_serial.in_waiting
if data_size < 1:
continue
data = self.vspd_serial.read(data_size)
print(f'VSPD:{data}')
self.mcu_serial.write(data)
finally:
print("\nvspd thread Done")
if __name__ == '__main__':
print('Begining')
app = SerialLog(mcu_serial_config, vspd_serial_config)