Skip to content

Instantly share code, notes, and snippets.

@sutyum
Forked from tiagocoutinho/README.md
Created May 30, 2022 20:21
Show Gist options
  • Save sutyum/03e78373dadbcbd0c961c43561606aab to your computer and use it in GitHub Desktop.
Save sutyum/03e78373dadbcbd0c961c43561606aab 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment