Let’s see how to forward data from a virtual serial to a network address.
Step 1 – Choose the serial to use
It is possible to view the list of virtual serial numbers available in the system with the following command:
dmesg | grep tty
Step 2 – Socat
Socat is a very useful tool that is already present in many Linux distros, enabling you to manipulate and forward network packets.
Open a terminal and acquire ROOT privileges (important).
Execute this command to initialise the forwarding of incoming packets to the serial port.
ttyS0, towards IP loopback, on port 60001:
socat pty,link=/dev/ttyS0,raw tcp:127.0.0.1:60001&
Obviously it will be sufficient to modify the command with the desired serial and IP:port address.
Another possible use is the binding (union) of two different serials:
socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11
Step 3 – Send/Receive with Python
3.1
In order to receive the data, we must prepare a listener on the destination IP address (this is not covered in detail in this article). In our case we simply use netcat, always monitoring the 60001 port (make sure the chosen port is not already in use).
We then give the command (in a new terminal with ROOT privileges):
nc -l 60001
or
nc -v localhost 60001
3.2
Let’s prepare a simple script to write on serial (using Python) and save it with the name sender.py:
#START (serial forwarder) import sys import time import os, pty, serial #configure the serial connections print "\nSTARTING SERIAL PRINT\n" # open serial port ser = serial.Serial('/dev/ttyS0', 9600, rtscts=True, dsrdtr=True) print "SERIAL FORWARDER > (remind to use this as a root!)\n" # write test string ser.write("\n > serial test for an ALARM! \n go go ALARM! go :) ") # close serial port ser.close(); #END
run it from a new terminal (with ROOT privileges) with the following command:
python sender.py
NOTE: We install pyserial if necessary (if you go to the previous step we will receive an error):
sudo apt-get install python-serial
You can now see the socat connection towards the destination IP.
More information about socat is available on the official website.