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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,11 @@ again just to start it. After editing the mounted deployment file, apply the
updated configuration to the running simulator with:

```bash
docker compose exec modsim python -m modsim up -f /app/examples/deployment.yaml -d
docker compose exec modsim python -m modsim up -f /app/deployment.yaml -d
```

An unchanged device keeps its state; a changed device is replaced. Listener
Use the mounted path Compose started (`/app/deployment.yaml`); the control
socket rejects any other path. An unchanged device keeps its state; a changed device is replaced. Listener
changes require a container restart. If you replace the deployment file itself,
run `docker compose up -d --force-recreate` to refresh its bind mount. Export
all running TDs directly into the host's `examples/td/` directory. The Compose
Expand Down
2 changes: 1 addition & 1 deletion examples/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ services:
modsim:
build: ..
restart: unless-stopped
command: ["python", "-m", "modsim", "up", "-f", "/app/deployment.yaml", "--allow-scripts"]
command: ["python", "-m", "modsim", "up", "-f", "/app/deployment.yaml"]
ports:
- "127.0.0.1:5020:5020"
volumes:
Expand Down
16 changes: 11 additions & 5 deletions modsim/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,16 @@ async def run_async_server(args: Any) -> Any:
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(
certfile="certificates/pymodbus.crt",
keyfile="certificates/pymodbus.key",
)
try:
sslctx.load_cert_chain(
certfile="certificates/pymodbus.crt",
keyfile="certificates/pymodbus.key",
)
except OSError as exc:
raise OSError(
"TLS needs certificates/pymodbus.crt and certificates/pymodbus.key "
f"in the working directory: {exc}"
) from exc

server = ModbusTlsServer(
context=args.context,
Expand Down Expand Up @@ -244,7 +250,7 @@ def app() -> None:
_logger.error("Invalid model configuration: %s", exc)
raise SystemExit(2) from exc
try:
asyncio.run(_run_server_with_signals(run_args), debug=True)
asyncio.run(_run_server_with_signals(run_args), debug=args.log == "debug")
except OSError as exc:
_logger.error("%s", exc)
raise SystemExit(2) from exc
Expand Down
17 changes: 11 additions & 6 deletions modsim/management.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,12 @@ def plan(self, desired: Deployment) -> dict:
async def apply(self, desired: Deployment, dry_run: bool = False) -> dict:
plan = self.plan(desired)
# Only changed candidates initialize; repeated up cannot rerun live hooks.
# Building validates schemas and executes behavior scripts; keep it off the
# event loop so Modbus clients of the running devices are still served.
candidates = {
key: desired.instances[key].build(self.allow_scripts, preview=dry_run)
key: await asyncio.to_thread(
desired.instances[key].build, self.allow_scripts, preview=dry_run
)
for key in plan["added"] + plan["replaced"]
}
if dry_run:
Expand Down Expand Up @@ -227,12 +231,13 @@ async def handle(
if task is not None:
handlers.add(task)
try:
# Read before locking so an idle connection cannot stall other commands.
payload = await asyncio.wait_for(reader.readline(), 5)
message = json.loads(payload)
if message.get("source") != str(desired.path):
raise ValueError("deployment name belongs to a different file")
action = message.get("action")
async with manager.lock:
payload = await asyncio.wait_for(reader.readline(), 5)
message = json.loads(payload)
if message.get("source") != str(desired.path):
raise ValueError("deployment name belongs to a different file")
action = message.get("action")
if action == "up":
if message.get("allow_scripts") and not manager.allow_scripts:
raise ValueError(
Expand Down
5 changes: 4 additions & 1 deletion modsim/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,10 @@ async def async_setValues(
device.cells[table][current_address] = value
touched = {(table, item) for item in range(address, address + len(values))}
changes = device.validate_cells(touched)
device.held.update(changes)
# Read-only aliases are re-decoded but not written, so their generators keep running.
device.held.update(
name for name in changes if device.codecs[name].member.writable
)
device.hook("on_write", changes)
device.set_many(
{
Expand Down
15 changes: 15 additions & 0 deletions tests/test_codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,21 @@ def test_readonly_bits_and_writeonly_property(tmp_path):
assert instance.get("value") == 0x12345678


def test_client_write_holds_only_writable_properties(tmp_path):
a = prop("unsignedShort", 1, "boolean", readOnly=True)
a["forms"][0]["modpoll:bit"] = 0
b = prop("unsignedShort", 1, "boolean")
b["forms"][0]["modpoll:bit"] = 1
instance = configure_properties(tmp_path, {"a": a, "b": b})
instance.generators = {"a": {"kind": "constant", "value": True}}
context = RuntimeContext([instance])
assert asyncio.run(context.async_setValues(1, 6, 0, [2])) is None
assert instance.held == {"b"}
instance.advance(0, 1)
assert instance.get("a") is True
assert instance.get("b") is True


def test_partial_float_write_validates_full_span_and_rolls_back(tmp_path):
instance = configure_properties(
tmp_path, {"value": prop("float", 2, "number", maximum=1.5)}, {"value": 1.5}
Expand Down
55 changes: 55 additions & 0 deletions tests/test_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,3 +422,58 @@ def test_attached_up_and_follow_logs_detach_without_stopping(tmp_path):
assert json.loads(cli(path, "ps").stdout)["running"] is True
finally:
cli(path, "down")


def test_apply_builds_devices_off_the_event_loop(tmp_path, monkeypatch):
import threading

path, _, _ = fixture(tmp_path)
desired = load_deployment(path)
instance_type = type(desired.instances["io-1"])
original = instance_type.build
threads = []

def build(self, *args, **kwargs):
threads.append(threading.current_thread())
return original(self, *args, **kwargs)

monkeypatch.setattr(instance_type, "build", build)

async def exercise():
manager = RuntimeManager()
try:
await manager.apply(desired)
finally:
await manager.close()

asyncio.run(exercise())
assert threads and all(t is not threading.main_thread() for t in threads)


def test_idle_management_connection_does_not_block_other_commands(tmp_path):
import time

from modsim.management import paths

path, spec, _ = fixture(tmp_path)
process = subprocess.Popen(
[sys.executable, "-m", "modsim", "up"],
cwd=tmp_path,
env={**os.environ, "PYTHONPATH": str(ROOT)},
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
deadline = time.monotonic() + 10
while not json.loads(cli(path, "ps").stdout)["running"]:
assert time.monotonic() < deadline and process.poll() is None
time.sleep(0.05)
with socket.socket(socket.AF_UNIX) as idle:
idle.connect(str(paths(spec["name"])[0]))
started = time.monotonic()
assert json.loads(cli(path, "ps").stdout)["running"]
# The server drops an idle client after 5 seconds.
assert time.monotonic() - started < 3
finally:
process.terminate()
process.wait(timeout=10)
17 changes: 17 additions & 0 deletions tests/test_modsim.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,3 +461,20 @@ def test_default_port_without_rights_fails_with_hint():
)
assert result.returncode == 2
assert "Port 502 needs administrator rights" in result.stderr


def test_tls_without_certificates_explains_what_is_missing(tmp_path):
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
port = reservation.getsockname()[1]
source = os.path.dirname(os.path.dirname(modsim.__file__))
result = subprocess.run(
[sys.executable, "-m", "modsim", "--comm", "tls", "--port", str(port)],
cwd=tmp_path,
env={**os.environ, "PYTHONPATH": source},
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 2
assert "certificates/pymodbus.crt" in result.stderr + result.stdout
Loading