Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fake serial communication under Linux

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.

Example Python code

device = Device()
modem  = Modem()
device.connect(modem)

device.write("Hello")
modem_reply = device.read()

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.

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.

I have also lpayed with the ptymodule, 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.

Update

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

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.

like image 242
Hannes Ovrén Avatar asked Mar 23 '10 13:03

Hannes Ovrén


1 Answers

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.

like image 74
Vinay Sajip Avatar answered Oct 05 '22 10:10

Vinay Sajip