# uartmock **Repository Path**: lukbob/uartmock ## Basic Information - **Project Name**: uartmock - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-05-26 - **Last Updated**: 2025-05-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 模拟串口设备(比如一个简单的虚拟串口服务器,收到指令后返回固定或逻辑生成的报文) Demo程序(打开串口,发送指令,接收并打印返回) 在Ubuntu上,我们可以用**socat**工具配合Python来实现虚拟串口对连。 而Python端,我们用pyserial库来收发数据。 1. 安装环境准备 先确保安装好必要工具和库: bash 复制 编辑 sudo apt update sudo apt install socat pip install pyserial 2. 创建虚拟串口对 用 socat 命令创建两个互联的虚拟串口,比如 /tmp/ttyV0 和 /tmp/ttyV1: bash 复制 编辑 socat -d -d PTY,link=/tmp/ttyV0,raw,echo=0 PTY,link=/tmp/ttyV1,raw,echo=0 保持这个终端窗口开着,不要关掉! /tmp/ttyV0 和 /tmp/ttyV1 相当于一根串口线的两头。 3. Python 模拟设备端程序(Server) 比如,设备收到 "HELLO" ,回复 "WORLD"。 python 复制 编辑 # serial_server.py import serial def main(): ser = serial.Serial('/tmp/ttyV1', baudrate=9600, timeout=1) print("串口设备模拟器已启动,等待指令...") while True: data = ser.readline().decode('utf-8').strip() if data: print(f"收到指令: {data}") if data == "HELLO": response = "WORLD\n" else: response = "UNKNOWN\n" ser.write(response.encode('utf-8')) print(f"发送回复: {response.strip()}") if __name__ == '__main__': main() 4. Python Demo 程序(Client) 发送指令到串口,读取并打印返回的报文: python 复制 编辑 # serial_client.py import serial import time def main(): ser = serial.Serial('/tmp/ttyV0', baudrate=9600, timeout=1) time.sleep(2) # 给串口一点初始化时间 command = "HELLO\n" print(f"发送指令: {command.strip()}") ser.write(command.encode('utf-8')) response = ser.readline().decode('utf-8').strip() print(f"收到回复: {response}") if __name__ == '__main__': main() 5. 运行步骤总结 开一个终端运行 socat 创建虚拟串口连接。 开一个终端运行 python serial_server.py(模拟设备端)。 开一个终端运行 python serial_client.py(demo发送指令)。 看输出,应该是 WORLD 被成功返回!