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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ uv run modsim --config examples/models/products/advantech/adam-5017uh/models/ada
--scenario examples/models/products/advantech/adam-5017uh/simulation/adam-5017uh.sim.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
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
Expand Down
21 changes: 19 additions & 2 deletions docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
# Modsim 2.0.0a4 preview
# Modsim 2.0.0a5 preview

Without `--port`, modsim now listens on the standard Modbus port: 502 for TCP
and UDP, 802 for Modbus/TLS. A simulator started from a ModioHub Thing Model is
then read with `modpoll --tcp 127.0.0.1`, without `--tcp-port`:

```sh
uvx --prerelease allow modsim==2.0.0a5 --config https://example.org/device.tm.json
```

Linux, and macOS when binding to `127.0.0.1`, reserve ports below 1024 for
administrators. modsim then exits before starting and explains how to rerun it
with sudo (`sudo "$(command -v uvx)" modsim ...`) or choose a port above 1023,
for example `--port 5020`. Managed deployments keep their explicit server port.
This preview still pins modpoll-wot 0.2.0a4.

### Previous preview

#### Modsim 2.0.0a4

Remote models and scenarios load directly from a site such as ModioHub:

Expand All @@ -11,7 +29,6 @@ HTTPS requests identify themselves as `modsim/<version>`, because some CDNs reje
the default Python agent. `--scenario` accepts an HTTPS URL; a remote scenario
cannot name a behavior script. This preview still pins modpoll-wot 0.2.0a4.

### Previous preview

#### Modsim 2.0.0a3

Expand Down
4 changes: 4 additions & 0 deletions docs/site/model-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ uv run modsim --config examples/models/advantech/adam-5017uh/adam-5017uh.tm.json
--scenario examples/models/advantech/adam-5017uh/simulation/adam-5017uh.sim.json
```

Without `--port`, the listener uses 502, which 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.

`--config` also accepts HTTPS model URLs. GitHub `blob` links are converted to
raw file URLs. Prefer a tag or commit SHA for repeatable runs; branch URLs change.
Downloads have a 15-second timeout and a 1 MiB limit, and use the shared bounded
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.0a4"
__version__ = "2.0.0a5"
32 changes: 31 additions & 1 deletion modsim/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import ssl
import asyncio
import socket
import signal
import logging
from contextlib import suppress
Expand Down Expand Up @@ -108,6 +109,28 @@ def setup_server(args: Any) -> Any:
return args


def privileged_port_hint(port: Any) -> str:
"""Explain how to listen on a port the operating system reserves."""
return (
f"Port {port} needs administrator rights on this system. Run the same "
'command with sudo; with uvx that is sudo "$(command -v uvx)" followed by '
"the rest of the command. Or listen on a port above 1023, for example "
"--port 5020, and point the client at it (modpoll --tcp-port 5020)."
)


def require_bindable(host: str, port: Any, kind: int = socket.SOCK_STREAM) -> None:
"""Fail early with a clear message when binding needs elevated rights."""
with socket.socket(socket.AF_INET, kind) as probe:
try:
probe.bind((host, int(port)))
except PermissionError as exc:
raise OSError(privileged_port_hint(port)) from exc
except OSError:
# Occupied ports and other failures are reported by the server itself.
return


async def run_async_server(args: Any) -> Any:
"""Run server."""
txt = f"Start ASYNC server, listening on {args.port} - {args.comm}"
Expand All @@ -119,6 +142,7 @@ async def run_async_server(args: Any) -> Any:
or ("127.0.0.1" if getattr(args, "runtimes", None) else ""),
args.port,
)
require_bindable(address[0], args.port)
server = ModbusTcpServer(
context=args.context,
identity=args.identity,
Expand Down Expand Up @@ -148,6 +172,7 @@ async def run_async_server(args: Any) -> Any:
return server
elif args.comm == "udp":
address = ("127.0.0.1", args.port)
require_bindable(address[0], args.port, socket.SOCK_DGRAM)
server = ModbusUdpServer(
context=args.context,
identity=args.identity,
Expand All @@ -173,6 +198,7 @@ async def run_async_server(args: Any) -> Any:
return None
elif args.comm == "tls":
address = ("", args.port)
require_bindable(address[0], args.port)
# Create SSL context from cert and key files
sslctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
sslctx.load_cert_chain(
Expand Down Expand Up @@ -217,7 +243,11 @@ def app() -> None:
except (ValueError, OSError) as exc:
_logger.error("Invalid model configuration: %s", exc)
raise SystemExit(2) from exc
asyncio.run(_run_server_with_signals(run_args), debug=True)
try:
asyncio.run(_run_server_with_signals(run_args), debug=True)
except OSError as exc:
_logger.error("%s", exc)
raise SystemExit(2) from exc

_logger.info("exiting.")

Expand Down
8 changes: 4 additions & 4 deletions modsim/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def get_parser() -> argparse.ArgumentParser:
)
parser.add_argument(
"--port",
help="set port",
help="set port; defaults to 502 for TCP and UDP and 802 for TLS",
type=str,
)
parser.add_argument(
Expand Down Expand Up @@ -129,10 +129,10 @@ def get_commandline() -> argparse.Namespace:

# set defaults
comm_defaults: Dict[str, list] = {
"tcp": ["socket", 5020],
"udp": ["socket", 5020],
"tcp": ["socket", 502],
"udp": ["socket", 502],
"serial": ["rtu", "/dev/ptyp0"],
"tls": ["tls", 5020],
"tls": ["tls", 802],
}
framers: Dict[str, Any] = {
"ascii": FramerType.ASCII,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "modsim"
version = "2.0.0a4"
version = "2.0.0a5"
description = "A Simple Modbus TCP Device Simulator used for modpoll tool"
authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }]
readme = "README.md"
Expand Down
49 changes: 49 additions & 0 deletions tests/test_modsim.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import socket
import signal
import subprocess
Expand Down Expand Up @@ -412,3 +413,51 @@ def test_local_tls_server_with_ephemeral_certificate(tmp_path):
if process.poll() is None:
process.kill()
process.wait(timeout=5)


def test_privileged_port_reports_how_to_run(monkeypatch):
from modsim import main

def refuse(self, address):
raise PermissionError(13, "Permission denied")

monkeypatch.setattr(socket.socket, "bind", refuse)
with pytest.raises(OSError) as error:
main.require_bindable("127.0.0.1", 502)
message = str(error.value)
assert "Port 502 needs administrator rights" in message
assert 'sudo "$(command -v uvx)"' in message
assert "--port 5020" in message


def test_default_tcp_port_is_502(monkeypatch):
from modsim.utils import get_commandline

monkeypatch.setattr(sys, "argv", ["modsim"])
assert get_commandline().port == 502


def _unprivileged_low_ports():
try:
with open("/proc/sys/net/ipv4/ip_unprivileged_port_start") as handle:
return int(handle.read()) <= 502
except OSError:
return True


@pytest.mark.integration
@pytest.mark.skipif(
not sys.platform.startswith("linux")
or os.geteuid() == 0
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():
result = subprocess.run(
[sys.executable, "-m", "modsim", "--log", "error"],
capture_output=True,
text=True,
timeout=5,
)
assert result.returncode == 2
assert "Port 502 needs administrator rights" in result.stderr
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading