Skip to content

Instantly share code, notes, and snippets.

@tiagocoutinho
Last active December 19, 2023 07:57
Show Gist options
  • Save tiagocoutinho/de3f8da1bc11943b5ae41fd84aa83ee8 to your computer and use it in GitHub Desktop.
Save tiagocoutinho/de3f8da1bc11943b5ae41fd84aa83ee8 to your computer and use it in GitHub Desktop.
Virtual serial line (RS232) on linux with socat and pyserial

Virtual serial line

Virtual serial line on linux with socat, python server & client

Run on terminal 1:

socat -d -d pty,raw,echo=0,link=/tmp/cryocon_simulator pty,raw,echo=0,link=/tmp/cryocon

Run on terminal 2:

python simulator.py

Run on terminal 3:

python client.py "*IDN?"

References

stack overflow reference

Alternatives:

import sys
import serial
DEFAULT_ADDR = '/tmp/cryocon'
DEFAULT_CMD = '*IDN?'
args = len(sys.argv) - 1
if args == 0:
addr, cmd = DEFAULT_ADDR, DEFAULT_CMD
elif args == 1:
addr, cmd = DEFAULT_ADDR, sys.argv[1]
else:
addr, cmd = sys.argv[1:3]
cmd += '\n'
s = serial.serial_for_url(addr)
s.write(cmd.encode())
print(s.readline())
import sys
import logging
import serial
DEFAULT_ADDR = '/tmp/cryocon_simulator'
logging.basicConfig(level=logging.INFO)
addr = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_ADDR
conn = serial.serial_for_url(addr)
logging.info(f'Ready to receive requests on {addr}')
while True:
request = conn.readline()
logging.info('REQ: %r', request)
request = request.strip().decode().lower()
reply = 'Cryo-con,24C,305682,1.05A\n' if request == '*idn?' else 'NACK\n'
reply = reply.encode()
logging.info('REP: %r', reply)
conn.write(reply)
# creates the PTYs
socat -d -d pty,raw,echo=0,link=/tmp/cryocon_simulator pty,raw,echo=0,link=/tmp/cryocon
Copy link

ghost commented Nov 12, 2022

Thanks! This example helped a lot in my bachelor's thesis!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment