Skip to content
This repository was archived by the owner on Nov 15, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
19 changes: 18 additions & 1 deletion docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/site/model-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion modsim/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "2.0.0a11"
__version__ = "2.0.0a12"
69 changes: 60 additions & 9 deletions modsim/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from pymodbus.pdu.device import ModbusDeviceIdentification
from pymodbus.server import (
StartAsyncSerialServer,
ModbusSerialServer,
ModbusTcpServer,
ModbusTlsServer,
ModbusUdpServer,
Expand All @@ -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__)

Expand Down Expand Up @@ -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}"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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())
Expand Down
60 changes: 53 additions & 7 deletions modsim/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {}

Expand Down Expand Up @@ -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"],
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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,
Expand Down
97 changes: 97 additions & 0 deletions modsim/virtual_serial.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading