问题描述
我有一个应用程序,我想在其中模拟设备和调制解调器"之间的连接.该设备将连接到串行端口,并通过该端口与软件调制解调器通信.
I have an application where I want to simulate the connection between a device and a "modem". The device will be connected to a serial port and will talk to the software modem through that.
出于测试目的,我希望能够使用模拟软件设备来测试发送和接收数据.
For testing purposes I want to be able to use a mock software device to test send and receive data.
Python示例代码
Example Python code
device = Device()
modem = Modem()
device.connect(modem)
device.write("Hello")
modem_reply = device.read()
现在,在我最终的应用程序中,我将只传递/dev/ttyS1或COM1或任何供应用程序使用的内容.但是,我该如何在软件中执行此操作?我正在运行 Linux ,并且应用程序是用 Python 编写的.
Now, in my final app I will just pass /dev/ttyS1 or COM1 or whatever for the application to use.But how can I do this in software? I am running Linux and application is written in Python.
我尝试制作一个FIFO(mkfifo ~/my_fifo
),它确实起作用,但是随后我将需要一个FIFO来进行写入,而需要一个FIFO来进行读取.我想要的是打开~/my_fake_serial_port
并对其进行读写.
I have tried making a FIFO (mkfifo ~/my_fifo
) and that does work, but then I'll need one FIFO for writing and one for reading. What I want is to open ~/my_fake_serial_port
and read and write to that.
我也已经用pty
模块付款了,但是也不能使它正常工作.我可以从pty.openpty()
获取主文件和从文件描述符,但是尝试读取或写入它们只会导致IOError Bad File Descriptor
错误消息.
I have also lpayed with the pty
module, but can't get that to work either. I can get a master and slave file descriptor from pty.openpty()
but trying to read or write to them only causes IOError Bad File Descriptor
error message.
评论使我想到了这样的问题是否有像COM0COM这样的程序在Linux中?,它使用socat
设置虚拟串行连接.我这样使用它:
Comments pointed me to the SO question Are there some program like COM0COM in linux? which uses socat
to setup a virtual serial connection.I used it like this:
socat PTY,link=$HOME/COM1 PTY,link=$HOME/COM2
对于其他人,非常感谢您向我提供了宝贵的信息.我选择接受 Vinay Sajips 的回答,因为那是我在socat建议出现之前所寻求的解决方案.看来效果很好.
To the rest of you, thank you for giving me valuable information.I chose to accept Vinay Sajips's answer since that is the solution which I went for before the socat suggestion showed up. It seems to work well enough.
推荐答案
最好使用 pyserial 与串行端口通信,您只需创建serial.Serial
类的模拟版本即可实现read
,readline
,write
以及您需要的任何其他方法.
It's probably best to use pyserial to communicate with the serial port, and you can just create a mock version of the serial.Serial
class which implements read
, readline
, write
and any other methods you need.
这篇关于Linux下的伪串行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!