From 2715aa029f7566bc9e1af128543871e2232c60bd Mon Sep 17 00:00:00 2001 From: Lorenz Stechauner Date: Mon, 23 Nov 2026 19:10:13 +0100 Subject: [PATCH] Simulator: Add support for /dev/ttyUSB and COM --- Simulator/plc.py | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/Simulator/plc.py b/Simulator/plc.py index e79389a..bd9ae32 100755 --- a/Simulator/plc.py +++ b/Simulator/plc.py @@ -1,6 +1,5 @@ #!/bin/env python3 -import socket import time import random import argparse @@ -43,9 +42,13 @@ def send_cmd(cmd: str, data: str) -> None: msg = f'(A01{cmd}{data}&' chk = sum(c for c in msg.encode('ascii')) & 0xFF msg += f'{chk:02X})\r' - time.sleep(len(msg) * 8 / 9600 * 2) + if not is_real: + time.sleep(len(msg) * 8 / 9600 * 1.5) print(f'-> {msg}') - client.send(msg.encode('ascii')) + if is_real: + client.write(msg.encode('ascii')) + else: + client.send(msg.encode('ascii')) if __name__ == '__main__': @@ -53,19 +56,30 @@ if __name__ == '__main__': parser.add_argument('socket') args = parser.parse_args() - client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - client.connect(args.socket) + is_real = args.socket.startswith('/dev/ttyUSB') or args.socket.startswith('COM') + + if is_real: + import serial + client = serial.Serial(args.socket, 9600, parity=serial.PARITY_ODD) + else: + import socket + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + client.connect(args.socket) while True: - line = b'' - while b'\r' not in line: - line += client.recv(256) + if is_real: + line = client.read_until(b'\r') + else: + line = b'' + while b'\r' not in line: + line += client.recv(256) cmds = line.split(b'\r') line = cmds[-1] cmds = [c.decode('ascii') for c in cmds[:-1]] for cmd in cmds: print(f'<- {cmd}') - time.sleep(len(cmd) * 8 / 9600 * 2) + if not is_real: + time.sleep(len(cmd) * 8 / 9600 * 1.5) if not cmd.startswith('(A01') or not cmd.endswith(')') or len(cmd) < 7: send_cmd('CE', '02') continue