Skip to content

Instantly share code, notes, and snippets.

@krzyklo
Forked from tiagocoutinho/README.md
Last active October 22, 2023 15:48
Show Gist options
  • Select an option

  • Save krzyklo/e60793b27400be7a330042aa6bdf388a to your computer and use it in GitHub Desktop.

Select an option

Save krzyklo/e60793b27400be7a330042aa6bdf388a 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 -x shows data exchanged in HEX format

Run on terminal 1:

socat -x -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 -x -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