socat
首先安装socat
$ sudo apt-get install socat
有点资料显示,直接:
$ socat -d -d PTY PTY:
即可建立两个虚拟串口,但是我遇到这样的报错:
$ sudo socat -d -d PTY PTY:
2021/11/04 10:30:42 socat[12462] N PTY is /dev/pts/0
2021/11/04 10:30:42 socat[12462] E PTY: wrong number of parameters (1 instead of 0)
2021/11/04 10:30:42 socat[12462] N exit(1)
查找资料后,输入以下命令,即可建立两个虚拟串口成功。
$ socat -d -d pty,raw,echo=0 pty,raw,echo=0
正常输出:
$ socat -d -d pty,raw,echo=0 pty,raw,echo=0
2021/11/04 10:36:47 socat[13961] N PTY is /dev/pts/0
2021/11/04 10:36:47 socat[13961] N PTY is /dev/pts/5
2021/11/04 10:36:47 socat[13961] N starting data transfer loop with FDs [5,5] and [7,7]
下面那种方法可以抛弃
#coding = utf-8
import pty
import os
import select
def mkpty():
master1, slave = pty.openpty()
slaveName1 = os.ttyname(slave)
master2, slave = pty.openpty()
slaveName2 = os.ttyname(slave)
print '\nslave device names: ', slaveName1, slaveName2
return master1, master2
if __name__ == "__main__":
master1, master2 = mkpty()
while True:
rl, wl, el = select.select([master1, master2], [], [], 1)
for master in rl:
data = os.read(master, 128)
print "read %d data." %len(data)
if master == master1:
os.write(master2, data)
else:
os.write(master1, data)
使用方法:
启动:在终端里运行
$ python mkptych.py
输出:
slave device names: /dev/pts/1 /dev/pts/2
这样就可以生成一个基于pty(伪终端)的虚拟端口对,两个设备名会显示在终端里。然后就可以利用这两个设备名在本机上进行虚拟串口之类的调试。
$ ls /dev/pts/
0 1 2 3 ptmx
关闭:使用完后用ps查看这个python进程的pid号,然后kill掉即可。
打开一个新的终端并且输入如下指令,表示等待捕获/dev/pts/1
端口上的数据
# sudo cat /dev/pts/1
打开一个新的终端并且输入如下指令,表示向/dev/pts/2
端口发送一个字符串"Hello World"
# sudo echo "Hello World" > /dev/pts/2
然后可以在/dev/pts/1
对应的终端窗口看到如下打印:
$ sudo cat /dev/pts/1
Hello World
创建一个python脚本virtual_com.py
#coding = utf-8
import serial
from time import sleep
def recv(serial):
while True:
data = serial.read_all()
if data == '':
continue
else:
break
sleep(0.02)
return data
if __name__ == '__main__':
serial = serial.Serial('/dev/pts/1', 9600, timeout=0.5) #/dev/ttyUSB0
if serial.isOpen() :
print("open success")
else :
print("open failed")
while True:
data =recv(serial)
if data != b'' :
print("receive : ",data)
serial.write(data)
启动脚本:
$ sudo python virtual_com.py
open success
打开一个新的终端并且输入如下指令,表示向/dev/pts/2
端口发送一个字符串"How are you?"
# sudo echo "How are you?" > /dev/pts/2
在第一个窗口有如下打印信息:
('receive : ', 'How are you?\r\n')