diff --git a/README.md b/README.md index 6901be8..b06775f 100644 --- a/README.md +++ b/README.md @@ -192,14 +192,33 @@ modpoll --config device.tm.json --tcp 192.168.1.10 --once --export snapshot.json uv run modsim --config device.tm.json --port 5020 --data snapshot.json ``` -Without `--port`, modsim listens on 502, the standard Modbus TCP port, so -`modpoll --tcp 127.0.0.1` reaches it without `--tcp-port`. Linux, and macOS -when binding to `127.0.0.1`, reserve ports below 1024 for administrators: run -the command with sudo (with uvx, `sudo "$(command -v uvx)" modsim ...`) or pass -`--port 5020` and read it with `modpoll --tcp-port 5020`. modsim prints the same -hint when the port is refused. Windows does not reserve these ports. - -The single-device model runtime currently supports TCP. The unconfigured demo +Without `--port`, modsim listens on 5020 so the first command needs no +administrator rights; read it with `modpoll --tcp 127.0.0.1 --tcp-port 5020`. +Linux, and macOS when binding to `127.0.0.1`, reserve ports below 1024 for +administrators: to listen on the standard port 502, run the command with sudo +(with uvx, `sudo "$(command -v uvx)" modsim --port 502 ...`). modsim prints the +same hint when a port is refused. Windows does not reserve these ports. + +### Modbus RTU + +`--serial pty` simulates a Modbus RTU device without hardware (Linux and macOS). +modsim creates a virtual serial cable, prints the port for the client and the +matching modpoll command, and removes it on exit: + +```bash +modsim --config device.tm.json --serial pty +# Virtual serial port for the client: /dev/pts/7 +# Read it with: modpoll --config device.tm.json --serial /dev/pts/7 --serial-baud 9600 +``` + +Virtual ports ignore baud rate and parity, so `--serial-baud` and `--serial-parity` +only shape the printed command. `--serial-link PATH` adds a fixed symbolic link to +the client port. Pass a port name instead of `pty` to listen on an existing serial +port with those settings. Windows has no pseudo-terminals: create a virtual serial +pair with a driver such as com0com, listen on one port with `--serial COM5` and +connect the client to the other. `--serial` and `--port` are mutually exclusive. + +The single-device model runtime currently supports TCP and Modbus RTU. The unconfigured demo also supports TCP, UDP, TLS, RTU and ASCII; its datastore is shared by all Unit IDs. TLS loads `certificates/pymodbus.crt` and `certificates/pymodbus.key` from the working directory. See [transport details](docs/site/index.md#unconfigured-demo). diff --git a/docs/preview-notes.md b/docs/preview-notes.md index ce0dd0e..0e8284a 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,4 +1,21 @@ -# Modsim 2.0.0a10 preview +# Modsim 2.0.0a12 preview + +Modsim 2.0.0a12 keeps modpoll-wot 0.6.0a2 and changes how a simulator is reached: + +- **Port 5020 by default.** Without `--port`, modsim now listens on 5020 for TCP, UDP and TLS, so the first + command needs no administrator rights on Linux and macOS. Read it with + `modpoll --tcp 127.0.0.1 --tcp-port 5020` (modpoll 2.0.0a10). `--port 502` still selects the standard port. +- **Modbus RTU without hardware.** `modsim --config device.tm.json --serial pty` creates a virtual serial + port on Linux and macOS, prints it together with the matching `modpoll --serial ...` command, and removes + it on exit. `--serial-link PATH` adds a fixed symbolic link; `--serial PORT` listens on an existing port + (on Windows, one port of a virtual pair made with a driver such as com0com). Virtual ports ignore baud + rate and parity. pyserial is now installed with modsim. + +## Modsim 2.0.0a11 preview + +Modsim 2.0.0a11 pins modpoll-wot 0.6.0a2 and resolves the ModioHub server from the only stored login. + +## Modsim 2.0.0a10 preview Modsim 2.0.0a10 keeps modpoll-wot 0.5.0a1. `modsim login` prints the sign-in link and opens a browser only where one can be opened; the opener's output no longer fills the terminal, and Ctrl-C cancels with one line. diff --git a/docs/site/model-validation.md b/docs/site/model-validation.md index 807cbfa..e8ed496 100644 --- a/docs/site/model-validation.md +++ b/docs/site/model-validation.md @@ -12,7 +12,7 @@ uv run modsim --config examples/models/products/advantech/adam-5017uh/model.tm.j --data examples/models/products/advantech/adam-5017uh/model.sim.json ``` -Without `--port`, the listener uses 502, which needs administrator rights on +Without `--port`, the listener uses 5020; port 502 needs administrator rights on Linux and on macOS for `127.0.0.1`; modsim then explains how to rerun with sudo or choose a port above 1023. diff --git a/modsim/__init__.py b/modsim/__init__.py index 45f4e01..3a87841 100644 --- a/modsim/__init__.py +++ b/modsim/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0a11" +__version__ = "2.0.0a12" diff --git a/modsim/main.py b/modsim/main.py index fb81755..a972e99 100644 --- a/modsim/main.py +++ b/modsim/main.py @@ -13,7 +13,7 @@ from pymodbus.pdu.device import ModbusDeviceIdentification from pymodbus.server import ( - StartAsyncSerialServer, + ModbusSerialServer, ModbusTcpServer, ModbusTlsServer, ModbusUdpServer, @@ -24,6 +24,9 @@ from . import __version__ from .compat import BinaryPayloadBuilder, Endian from .utils import get_commandline, get_utc_time, get_logger +from .virtual_serial import VirtualSerialPair + +SERIAL_PARITY = {"none": "N", "even": "E", "odd": "O"} _logger = logging.getLogger(__name__) @@ -131,6 +134,60 @@ def require_bindable(host: str, port: Any, kind: int = socket.SOCK_STREAM) -> No return +def read_command(args: Any, port: str) -> str: + """The modpoll command that reads this simulator over its virtual serial port.""" + parts = ["modpoll"] + if getattr(args, "config", None): + parts += ["--config", args.config] + parts += ["--serial", port, "--serial-baud", str(args.serial_baud)] + if args.serial_parity != "none": + parts += ["--serial-parity", args.serial_parity] + if getattr(args, "unit_id", None) is not None: + parts += ["--unit-id", str(args.unit_id)] + return " ".join(parts) + + +async def serve_serial(args: Any) -> None: + pair = None + port = args.port + if port == "pty": + pair = VirtualSerialPair(getattr(args, "serial_link", None)) + pair.open(asyncio.get_running_loop()) + port = pair.server_port + _logger.info("Virtual serial port for the client: %s", pair.client_port) + if getattr(args, "serial_link", None): + _logger.info("Also linked as %s", args.serial_link) + _logger.info("Read it with: %s", read_command(args, pair.client_port)) + server: Any = ModbusSerialServer( + context=args.context, + identity=args.identity, + port=port, + framer=args.framer, + baudrate=args.serial_baud, + parity=SERIAL_PARITY[args.serial_parity], + ) + if hasattr(args, "runtimes"): + from .runtime import RuntimeContext + + server.context = RuntimeContext(args.runtimes) + tasks: list = [] + try: + if not await server.listen(): + raise OSError("Could not open serial port %s" % port) + tasks = [ + asyncio.create_task(device.run()) + for device in getattr(args, "runtimes", []) + ] + await asyncio.gather(server.serving, *tasks) + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await server.shutdown() + if pair is not None: + pair.close() + + async def run_async_server(args: Any) -> Any: """Run server.""" txt = f"Start ASYNC server, listening on {args.port} - {args.comm}" @@ -189,13 +246,7 @@ async def run_async_server(args: Any) -> Any: await server.shutdown() return server elif args.comm == "serial": - await StartAsyncSerialServer( - context=args.context, - identity=args.identity, - port=args.port, - framer=args.framer, - ) - return None + return await serve_serial(args) elif args.comm == "tls": address = ("", args.port) require_bindable(address[0], args.port) @@ -281,7 +332,7 @@ def request_stop() -> None: nonlocal stop_requested if not stop_requested: stop_requested = True - if args.comm in ("tcp", "udp", "tls"): + if args.comm in ("tcp", "udp", "tls", "serial"): server_task.cancel() else: loop.create_task(stop_server()) diff --git a/modsim/utils.py b/modsim/utils.py index d15a993..5b95133 100644 --- a/modsim/utils.py +++ b/modsim/utils.py @@ -8,7 +8,10 @@ FramerType, ) -from . import __version__ +from . import __version__, virtual_serial + +# Above 1023, so the first command needs no administrator rights. +DEFAULT_PORT = 5020 config: Dict[str, Any] = {} @@ -54,6 +57,27 @@ def get_parser() -> argparse.ArgumentParser: default=None, type=str, ) + parser.add_argument( + "--serial", + metavar="PORT", + help=( + "listen for Modbus RTU on a serial port; 'pty' creates a virtual serial " + "port (Linux, macOS) and prints the port for the client" + ), + ) + parser.add_argument( + "--serial-baud", type=int, help="serial baud rate, default is 9600" + ) + parser.add_argument( + "--serial-parity", + choices=["none", "even", "odd"], + help="serial parity, default is none", + ) + parser.add_argument( + "--serial-link", + metavar="PATH", + help="with --serial pty, also create this symbolic link to the client port", + ) parser.add_argument( "--framer", choices=["ascii", "rtu", "socket", "tls"], @@ -69,7 +93,7 @@ def get_parser() -> argparse.ArgumentParser: ) parser.add_argument( "--port", - help="set port; defaults to 502 for TCP and UDP and 802 for TLS", + help="set port; defaults to 5020, which needs no administrator rights", type=str, ) parser.add_argument( @@ -98,7 +122,29 @@ def get_commandline() -> argparse.Namespace: parser = get_parser() args = parser.parse_args() + if args.serial: + if args.comm not in (None, "serial"): + parser.error("--serial cannot be combined with --comm %s" % args.comm) + if args.port: + parser.error("--serial and --port are mutually exclusive") + args.comm = "serial" + args.port = args.serial args.comm = args.comm or "tcp" + if args.comm != "serial" and ( + args.serial_baud or args.serial_parity or args.serial_link + ): + parser.error( + "--serial-baud, --serial-parity and --serial-link require --serial" + ) + if args.serial_link and args.serial != "pty": + parser.error("--serial-link requires --serial pty") + if args.serial == "pty" and not virtual_serial.available(): + parser.error( + "--serial pty is not available on Windows: create a virtual serial port " + "pair with a driver such as com0com and pass one of its ports to --serial" + ) + args.serial_baud = args.serial_baud or 9600 + args.serial_parity = args.serial_parity or "none" if not args.config and ( args.initial or args.param @@ -111,8 +157,8 @@ def get_commandline() -> argparse.Namespace: ) if args.bind and args.comm != "tcp": parser.error("--bind currently supports --comm tcp only") - if args.config and args.comm != "tcp": - parser.error("model-driven simulation currently supports --comm tcp") + if args.config and args.comm not in ("tcp", "serial"): + parser.error("model-driven simulation supports TCP and --serial") if args.store != "sequential": parser.error("only --store sequential is supported") if args.slaves != 0: @@ -132,10 +178,10 @@ def get_commandline() -> argparse.Namespace: # set defaults comm_defaults: Dict[str, list] = { - "tcp": ["socket", 502], - "udp": ["socket", 502], + "tcp": ["socket", DEFAULT_PORT], + "udp": ["socket", DEFAULT_PORT], "serial": ["rtu", "/dev/ptyp0"], - "tls": ["tls", 802], + "tls": ["tls", DEFAULT_PORT], } framers: Dict[str, Any] = { "ascii": FramerType.ASCII, diff --git a/modsim/virtual_serial.py b/modsim/virtual_serial.py new file mode 100644 index 0000000..2ea6f23 --- /dev/null +++ b/modsim/virtual_serial.py @@ -0,0 +1,97 @@ +"""A virtual serial cable on pseudo-terminals (Linux and macOS). + +Two pseudo-terminal pairs are joined by a byte-forwarding bridge between their master +ends: the Modbus RTU server opens the slave of one pair and the client opens the slave +of the other. Pseudo-terminals ignore baud rate and parity, so nothing is simulated +beyond the bytes. Windows has no pseudo-terminals; use a virtual serial pair driver +and pass one of its ports to --serial instead. +""" + +import asyncio +import contextlib +import logging +import os +import sys +from pathlib import Path +from typing import Optional + +_logger = logging.getLogger(__name__) + + +def available() -> bool: + return sys.platform != "win32" + + +class VirtualSerialPair: + """Two joined ports: `server_port` for modsim and `client_port` for the Modbus client.""" + + def __init__(self, link: Optional[str] = None) -> None: + self.server_port = "" + self.client_port = "" + self._link = Path(link) if link else None + self._masters: list[int] = [] + self._slaves: list[int] = [] + self._loop: Optional[asyncio.AbstractEventLoop] = None + + def open(self, loop: asyncio.AbstractEventLoop) -> None: + if not available(): + raise OSError("virtual serial ports are not available on Windows") + import pty + import tty + + if self._link is not None and (self._link.exists() or self._link.is_symlink()): + if not self._link.is_symlink(): + raise ValueError(f"--serial-link {self._link} exists and is not a link") + self._link.unlink() + self._loop = loop + try: + names = [] + for _ in range(2): + master, slave = pty.openpty() + self._masters.append(master) + # Keep the slaves open for the life of the pair: a pseudo-terminal master + # reports a hangup once no slave is open, e.g. between two client runs. + self._slaves.append(slave) + tty.setraw(slave) + os.set_blocking(master, False) + names.append(os.ttyname(slave)) + self.server_port, self.client_port = names + if self._link is not None: + self._link.symlink_to(self.client_port) + first, second = self._masters + loop.add_reader(first, self._forward, first, second) + loop.add_reader(second, self._forward, second, first) + except BaseException: + self.close() + raise + + def _forward(self, source: int, target: int) -> None: + try: + data = os.read(source, 4096) + except (BlockingIOError, InterruptedError): + return + except OSError: + assert self._loop is not None + self._loop.remove_reader(source) + return + try: + written = os.write(target, data) + except BlockingIOError: + written = 0 + if written < len(data): + _logger.warning( + "Virtual serial bridge dropped %d bytes", len(data) - written + ) + + def close(self) -> None: + for master in self._masters: + if self._loop is not None: + with contextlib.suppress(Exception): + self._loop.remove_reader(master) + for descriptor in (*self._masters, *self._slaves): + with contextlib.suppress(OSError): + os.close(descriptor) + self._masters, self._slaves = [], [] + if self._link is not None and self._link.is_symlink(): + with contextlib.suppress(OSError): + self._link.unlink() diff --git a/pyproject.toml b/pyproject.toml index 9165312..f386b51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,13 @@ [project] name = "modsim" -version = "2.0.0a11" +version = "2.0.0a12" description = "A Simple Modbus TCP Device Simulator used for modpoll tool" authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }] readme = "README.md" requires-python = ">=3.10,<4.0" dependencies = [ "pymodbus~=3.16.1", + "pyserial>=3.5,<4.0", "modpoll-wot==0.6.0a2", "jsonschema>=4.21,<5", "PyYAML>=6,<7", @@ -62,3 +63,7 @@ markers = ["integration: local protocol integration test"] [project.scripts] modsim = "modsim.main:app" + +[tool.deptry.per_rule_ignores] +# pymodbus imports pyserial for its serial transport; modsim never imports it itself. +DEP002 = ["pyserial"] diff --git a/tests/test_modsim.py b/tests/test_modsim.py index 09d7249..d9d9e76 100644 --- a/tests/test_modsim.py +++ b/tests/test_modsim.py @@ -430,11 +430,12 @@ def refuse(self, address): assert "--port 5020" in message -def test_default_tcp_port_is_502(monkeypatch): +@pytest.mark.parametrize("comm", ["tcp", "udp", "tls"]) +def test_default_port_is_5020(monkeypatch, comm): from modsim.utils import get_commandline - monkeypatch.setattr(sys, "argv", ["modsim"]) - assert get_commandline().port == 502 + monkeypatch.setattr(sys, "argv", ["modsim", "--comm", comm]) + assert get_commandline().port == 5020 def _unprivileged_low_ports(): @@ -452,9 +453,9 @@ def _unprivileged_low_ports(): or _unprivileged_low_ports(), reason="needs a non-root Linux user without access to port 502", ) -def test_default_port_without_rights_fails_with_hint(): +def test_privileged_port_without_rights_fails_with_hint(): result = subprocess.run( - [sys.executable, "-m", "modsim", "--log", "error"], + [sys.executable, "-m", "modsim", "--log", "error", "--port", "502"], capture_output=True, text=True, timeout=5, @@ -484,19 +485,41 @@ def test_serial_transport_passes_port_framer_and_datastore(monkeypatch): import asyncio from modsim import main - from modsim.utils import get_parser + from modsim.utils import get_commandline calls = {} - async def fake_serial_server(**kwargs): - calls.update(kwargs) + class FakeSerialServer: + def __init__(self, **kwargs): + calls.update(kwargs) + self.serving = asyncio.get_event_loop().create_future() + self.serving.set_result(None) + + async def listen(self): + return True + + async def shutdown(self): + calls["shutdown"] = True - monkeypatch.setattr(main, "StartAsyncSerialServer", fake_serial_server) - args = get_parser().parse_args( - ["--comm", "serial", "--port", "/dev/modsim-test", "--framer", "rtu"] + monkeypatch.setattr(main, "ModbusSerialServer", FakeSerialServer) + monkeypatch.setattr( + sys, + "argv", + [ + "modsim", + "--serial", + "/dev/modsim-test", + "--serial-baud", + "19200", + "--serial-parity", + "even", + ], ) + args = get_commandline() main.setup_server(args) assert asyncio.run(main.run_async_server(args)) is None assert calls["port"] == "/dev/modsim-test" assert calls["framer"] == args.framer assert calls["context"] is args.context + assert (calls["baudrate"], calls["parity"]) == (19200, "E") + assert calls["shutdown"] diff --git a/tests/test_virtual_serial.py b/tests/test_virtual_serial.py new file mode 100644 index 0000000..721ed50 --- /dev/null +++ b/tests/test_virtual_serial.py @@ -0,0 +1,112 @@ +"""RTU simulation over a virtual serial port (SIM-04).""" + +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time + +import pytest + +from modsim.main import read_command +from modsim.utils import get_parser + +MODEL = Path(__file__).parent / "fixtures/io-module/adam-6024.tm.json" +VALUES = [0x1234, 0x8001, 0xABCD, 0, 65535, 42] +posix_only = pytest.mark.skipif(os.name == "nt", reason="needs pseudo-terminals") + + +def _start(tmp_path, *extra): + data = tmp_path / "initial.data.json" + data.write_text( + json.dumps( + {"version": "1", "initial": {f"AI{i}_RAW": v for i, v in enumerate(VALUES)}} + ) + ) + log = (tmp_path / "server.log").open("w+") + process = subprocess.Popen( + [ + sys.executable, + "-m", + "modsim", + "--config", + str(MODEL), + "--unit-id", + "1", + "--data", + str(data), + "--serial", + "pty", + *extra, + ], + cwd=tmp_path, + stdout=log, + stderr=log, + ) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + log.seek(0) + text = log.read() + found = re.search(r"Virtual serial port for the client: (\S+)", text) + if found: + return process, found.group(1) + if process.poll() is not None: + pytest.fail(text) + time.sleep(0.1) + process.kill() + pytest.fail("virtual serial startup timed out") + + +@posix_only +def test_model_is_read_over_the_virtual_port_and_cleaned_up(tmp_path): + from pymodbus.client import ModbusSerialClient + + link = tmp_path / "ttyV0" + process, port = _start(tmp_path, "--serial-link", str(link)) + try: + assert link.is_symlink() and os.readlink(link) == port + # The same server survives a client opening and closing the port twice. + for _ in range(2): + client = ModbusSerialClient(port, baudrate=9600, timeout=2) + assert client.connect() + try: + reply = client.read_input_registers(0, count=6, device_id=1) + assert not reply.isError() + assert reply.registers == VALUES + finally: + client.close() + finally: + process.terminate() + process.wait(timeout=10) + assert not link.is_symlink() + + +def test_read_command_names_the_virtual_port(): + args = get_parser().parse_args( + ["--config", "m.tm.json", "--serial", "pty", "--unit-id", "7"] + ) + args.serial_baud, args.serial_parity = 9600, "even" + assert read_command(args, "/dev/pts/9") == ( + "modpoll --config m.tm.json --serial /dev/pts/9 --serial-baud 9600" + " --serial-parity even --unit-id 7" + ) + + +@pytest.mark.parametrize( + "arguments", + [ + ["--serial", "pty", "--port", "5020"], + ["--serial", "pty", "--comm", "tcp"], + ["--serial-baud", "9600"], + ["--serial", "/dev/ttyUSB0", "--serial-link", "x"], + ], +) +def test_conflicting_serial_options_are_refused(monkeypatch, arguments): + from modsim.utils import get_commandline + + monkeypatch.setattr(sys, "argv", ["modsim", *arguments]) + with pytest.raises(SystemExit) as error: + get_commandline() + assert error.value.code == 2 diff --git a/uv.lock b/uv.lock index c4111f6..371b079 100644 --- a/uv.lock +++ b/uv.lock @@ -842,12 +842,13 @@ wheels = [ [[package]] name = "modsim" -version = "2.0.0a11" +version = "2.0.0a12" source = { editable = "." } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" }, { name = "modpoll-wot", marker = "python_full_version < '3.15'" }, { name = "pymodbus", marker = "python_full_version < '3.15'" }, + { name = "pyserial", marker = "python_full_version < '3.15'" }, { name = "pyyaml", marker = "python_full_version < '3.15'" }, ] @@ -874,6 +875,7 @@ requires-dist = [ { name = "jsonschema", specifier = ">=4.21,<5" }, { name = "modpoll-wot", specifier = "==0.6.0a2" }, { name = "pymodbus", specifier = "~=3.16.1" }, + { name = "pyserial", specifier = ">=3.5,<4.0" }, { name = "pyyaml", specifier = ">=6,<7" }, ] @@ -1076,6 +1078,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d3/2f/ff5b8a99a33094a83e0e5c5b4cdf7b1fcc19dd009ff4acc1a749dcc18332/pyproject_api-1.11.4-py3-none-any.whl", hash = "sha256:30921dec1f85946dd47664536a003b2aea3a8be18e334c93ed12f6a8b1e60c76", size = 13563, upload-time = "2026-10-07T23:23:59.699Z" }, ] +[[package]] +name = "pyserial" +version = "3.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1e/7d/ae3f0a63f41e4d2f6cb66a5b57197850f919f59e558159a4dd3a818f5082/pyserial-3.5.tar.gz", hash = "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb", size = 159125, upload-time = "2020-11-23T03:59:15.045Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/bc/587a445451b253b285629263eb51c2d8e9bcea4fc97826266d186f96f558/pyserial-3.5-py2.py3-none-any.whl", hash = "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0", size = 90585, upload-time = "2020-11-23T03:59:13.41Z" }, +] + [[package]] name = "pytest" version = "8.4.2"