diff --git a/.github/workflows/acceptance.yaml b/.github/workflows/acceptance.yaml index c925821..1d171ba 100644 --- a/.github/workflows/acceptance.yaml +++ b/.github/workflows/acceptance.yaml @@ -67,16 +67,9 @@ jobs: cp examples/model-source.yaml "$RUNNER_TEMP/catalog-acceptance/examples/" cd "$RUNNER_TEMP/catalog-acceptance" "$RUNNER_TEMP/modsim/bin/python" tools/fetch-models.py --output "$RUNNER_TEMP/catalog-acceptance/inputs" - "$RUNNER_TEMP/modsim/bin/python" tools/catalog-interop.py --vectors "$RUNNER_TEMP/catalog-acceptance/inputs/products/advantech/adam-5017uh/models/adam-5017uh.vectors.json" --modpoll-python "$RUNNER_TEMP/modpoll/bin/python" --node-reader "$GITHUB_WORKSPACE/.interop/modpoll/tools/wot-interop/read-write.cjs" --output "$RUNNER_TEMP/catalog-interop.json" - - name: Verify the released runtime against the catalog model - run: | - uv venv "$RUNNER_TEMP/released-modsim" - uv pip install --python "$RUNNER_TEMP/released-modsim/bin/python" 'modsim==2.0.0a2' - cd "$RUNNER_TEMP/catalog-acceptance" - "$RUNNER_TEMP/released-modsim/bin/python" tools/catalog-interop.py --vectors "$RUNNER_TEMP/catalog-acceptance/inputs/products/advantech/adam-5017uh/models/adam-5017uh.vectors.json" --modpoll-python "$RUNNER_TEMP/modpoll/bin/python" --node-reader "$GITHUB_WORKSPACE/.interop/modpoll/tools/wot-interop/read-write.cjs" --output "$RUNNER_TEMP/catalog-interop-released.json" + "$RUNNER_TEMP/modsim/bin/python" tools/catalog-interop.py --modpoll-python "$RUNNER_TEMP/modpoll/bin/python" --node-reader "$GITHUB_WORKSPACE/.interop/modpoll/tools/wot-interop/read-write.cjs" --output "$RUNNER_TEMP/catalog-interop.json" - uses: actions/upload-artifact@v4 with: name: catalog-interop path: | ${{ runner.temp }}/catalog-interop.json - ${{ runner.temp }}/catalog-interop-released.json diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c352f45..687b50f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -50,6 +50,26 @@ jobs: - name: Test with tox run: uv run --locked --no-sync tox -e ${{ matrix.tox-env }} + snapshot-replay: + name: modpoll snapshot replay + runs-on: ubuntu-latest + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Set up uv and Python + uses: ./.github/actions/setup-uv + + - name: Install an independent released modpoll + run: | + uv venv "$RUNNER_TEMP/modpoll" + uv pip install --python "$RUNNER_TEMP/modpoll/bin/python" 'modpoll==2.0.0a5' + + - name: Export with modpoll and replay with modsim + env: + MODSIM_TEST_MODPOLL_PYTHON: ${{ runner.temp }}/modpoll/bin/python + run: uv run --locked pytest tests/test_snapshot_replay.py -v + docs: runs-on: ubuntu-latest steps: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de39ea8..293b626 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to modsim -Simulator code, runtime and scenario language changes target the affected tool +Simulator code, runtime and simulation data changes target the affected tool line (`v2` for model-driven development). Run relevant checks from the root: ```sh @@ -11,7 +11,7 @@ uv run python tools/generate-td.py --check uv run --group docs mkdocs build -s ``` -Device TMs, metadata, sources and product-specific scenarios belong in +Device TMs, metadata, sources and product-specific simulation data belong in [Open Modbus Catalog](https://github.com/top-maker/open-modbus-catalog), targeting its `main` through a PR and required catalog CI. Do not add editable device copies here. A new model submission needs an executable TM and source/permission/known diff --git a/README.md b/README.md index ad4e68b..b6a9f7d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ modsim is a standalone Modbus simulator for device integration and testing. The v2 development source reads WoT Thing Models (TM), instantiates device descriptions (TD), and runs independent simulated devices on one Modbus TCP -listener. Models, scenarios, the simulator and the client remain separate. +listener. Models, simulation data, the simulator and the client remain separate. This README describes the **v2 development branch**. The published `2.0.0a1` preview predates the managed deployment commands shown below; do not assume an @@ -35,7 +35,7 @@ uv run modsim ps The commands use `examples/deployment.yaml` by default. The example starts two virtual ADAM devices: Unit 1 exposes ADAM-5017UH raw inputs; Unit 2 exposes ADAM-6024 raw I/O with synthetic AO→AI and DO→DI loopback. These are simulation -values, not verified physical measurements. The ADAM-5017UH model and scenario +values, not verified physical measurements. The ADAM-5017UH model and simulation data come from [Open Modbus Catalog](https://github.com/top-maker/open-modbus-catalog); the ADAM-6024 model is a frozen regression fixture in `tests/fixtures/io-module/`. @@ -84,7 +84,7 @@ container unless stopped. Each restart resets simulation state. TDs advertise `127.0.0.1` by default; configure the advertised host and port mapping when clients connect from another machine. -The deployment and model/scenario files are mounted from the repository. +The deployment, model and simulation data files are mounted from the repository. `docker compose up -d` starts the configured deployment; do not run `modsim up` again just to start it. After editing the mounted deployment file, apply the updated configuration to the running simulator with: @@ -162,12 +162,14 @@ Stop modpoll with Ctrl+C, stop the broker if used (`docker stop modpoll-demo-mqtt`), then stop modsim with `uv run modsim down` or stop the Compose deployment with `docker compose down`. -## Models and scenarios +## Models and simulation data -A deployment has a stable ID per device, a TM path, instance parameters and an -optional scenario. TD IDs and Modbus Unit IDs must be unique. Scenarios define -initial values, seeded generators and bindings; local Python behavior requires -`--allow-scripts`. They do not duplicate the Thing Model's point mappings. See +A deployment has a stable ID per device, a TM path, instance parameters and +optional simulation data. TD IDs and Modbus Unit IDs must be unique. +[Simulation data](https://github.com/top-maker/modpoll-wot/blob/main/profile.md#simulation-data) +gives static initial values, seeded generators and bindings, and carries no +code; a local Python behavior is a separate `script` that requires +`--allow-scripts`. Neither duplicates the Thing Model's point mappings. See [model configuration](docs/site/model-validation.md) for the supported profile, codecs, constraints and behavior hooks. @@ -175,9 +177,18 @@ For a single device without a managed deployment: ```bash uv run python tools/fetch-models.py -uv run modsim --config examples/models/products/advantech/adam-5017uh/models/adam-5017uh.tm.json \ +uv run modsim --config examples/models/products/advantech/adam-5017uh/model.tm.json \ --unit-id 1 --port 5020 \ - --scenario examples/models/products/advantech/adam-5017uh/simulation/adam-5017uh.sim.json + --data examples/models/products/advantech/adam-5017uh/model.sim.json +``` + +A modpoll `--export` snapshot is simulation data too, so a device read once can +be replayed locally. Snapshots hold readings of a real device; keep them on +your computer: + +```bash +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 @@ -203,17 +214,17 @@ source change. ## Pinned public model inputs -Device data and optional scenarios are maintained in +Device models and optional simulation data are maintained in [Open Modbus Catalog](https://github.com/top-maker/open-modbus-catalog). `examples/model-source.yaml` pins a full catalog commit and individual SHA-256 hashes. Prepare examples with `uv run python tools/fetch-models.py`; this downloads verified local inputs to ignored `examples/models/`, never executes downloaded Python, and does not copy an interpreter. Re-run after updating the lock through a reviewed PR. -The application keeps its independent modpoll-wot 0.2.0a2 dependency. +The application keeps its independent modpoll-wot dependency. -Single-device mode can read a fixed HTTPS TM URL directly. Optional scenarios -remain local; scripts require explicit `--allow-scripts`. Managed deployments +Single-device mode can read a fixed HTTPS TM URL and simulation data directly; +scripts stay local and require explicit `--allow-scripts`. Managed deployments use Unix sockets and require POSIX; native Windows should use single-device foreground mode or WSL. Independent-wheel CI verifies single-device remote-TM startup, raw reads and process shutdown on Linux, macOS and native Windows. diff --git a/docs/preview-notes.md b/docs/preview-notes.md index 9ee4f66..0f78e74 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,4 +1,31 @@ -# Modsim 2.0.0a6 preview +# Modsim 2.0.0a7 preview + +Modsim 2.0.0a7 loads [simulation data](https://github.com/top-maker/modpoll-wot/blob/main/profile.md#simulation-data) +with `--data` and pins modpoll-wot 0.4.0a1. This preview breaks the previous +command line: + +- `--scenario` becomes `--data`; deployment devices use `data:` instead of + `scenario:`. +- `--initial-file` is removed: put the values in a data document's `initial`. +- Simulation data carries no code. Behavior scripts move out of the data file + to `--script` (with `--allow-scripts`) or a deployment device's `script:`, + and their values to the device's `scriptParameters:`. +- A modpoll `--export` snapshot is simulation data, so a device read once can + be replayed on this computer: + +```sh +uvx --prerelease allow modpoll==2.0.0a6 --config device.tm.json --tcp 192.168.1.10 --once --export snapshot.json +uvx --prerelease allow modsim==2.0.0a7 --config device.tm.json --data snapshot.json +``` + +Scaled values that modpoll exports, such as `230.10000000000002` for a raw +2301 with multiplier 0.1, are served again unchanged. Snapshot points modpoll +could not read keep their defaults and are listed at startup. Snapshots hold +readings of a real device: keep them on your computer. + +### Previous preview + +#### Modsim 2.0.0a6 Modsim 2.0.0a6 pins modpoll-wot 0.3.0a3, the same interpreter as modpoll 2.0.0a5. Thing Models no longer carry a `modpoll:audit` plan: a TM that still @@ -10,8 +37,6 @@ ports and remote loading are unchanged from 2.0.0a5: uvx --prerelease allow modsim==2.0.0a6 --config https://example.org/device.tm.json ``` -### Previous preview - #### Modsim 2.0.0a5 Without `--port`, modsim now listens on the standard Modbus port: 502 for TCP diff --git a/docs/release-process.md b/docs/release-process.md index 7e260c5..9e07c02 100644 --- a/docs/release-process.md +++ b/docs/release-process.md @@ -35,7 +35,7 @@ images. Record the separate validation run and tooling SHA. ### Known-value checks Use the approved TM as the configuration for a local TCP simulator. Seed known -values with `--initial PROPERTY=JSON` or `--initial-file`, then read them with +values with `--initial PROPERTY=JSON` or `--data` with an `initial` object, then read them with a full modpoll read. Thing Models no longer carry a `modpoll:audit` plan; a full read covers every property in `modpoll:acquisition`. diff --git a/docs/site/index.md b/docs/site/index.md index 52a803d..5954fe6 100644 --- a/docs/site/index.md +++ b/docs/site/index.md @@ -1,7 +1,7 @@ # modsim v2 development source modsim runs simulated Modbus devices for development and integration testing. -The current source supports profile 0.2 TM/TD input, scenarios and independent +The current source supports profile 0.2 TM/TD input, simulation data and independent devices on a single managed Modbus TCP listener. The published `2.0.0a1` preview does not include all current managed commands; see [preview notes](https://github.com/top-maker/modsim/blob/v2/docs/preview-notes.md). @@ -32,6 +32,6 @@ The CLI rejects non-default `--store` and the unsupported `--slaves` and ## More information -- [Model-driven simulation](model-validation.md): TM/TD, codecs and scenarios. +- [Model-driven simulation](model-validation.md): TM/TD, codecs and simulation data. - [Managed deployments](managed-deployments.md): YAML, lifecycle and export. - [Modules](modules.md): API reference. diff --git a/docs/site/managed-deployments.md b/docs/site/managed-deployments.md index 2eb8a3e..cab2b53 100644 --- a/docs/site/managed-deployments.md +++ b/docs/site/managed-deployments.md @@ -38,23 +38,23 @@ server: port: 5020 devices: - id: adam-5017uh - model: examples/models/advantech/adam-5017uh/adam-5017uh.tm.json + model: examples/models/products/advantech/adam-5017uh/model.tm.json parameters: THING_ID: urn:modsim:example:adam-5017uh UNIT_ID: 1 - scenario: examples/models/advantech/adam-5017uh/simulation/adam-5017uh.sim.json + data: examples/models/products/advantech/adam-5017uh/model.sim.json ``` `devices` may be empty. IDs and deployment names use lowercase letters, digits and hyphens, starting with a letter or digit (maximum 64 characters). Device IDs, instantiated TD IDs and Unit IDs must each be unique within the deployment. Paths in the repository example resolve from the project root; for standalone -deployments, model and scenario paths resolve relative to the deployment file. Scripts -resolve relative to their scenario file. Models may also use bounded HTTPS URLs. Pin remote model revisions +deployments, model, data and script paths resolve relative to the deployment file. +Models may also use bounded HTTPS URLs. Pin remote model revisions for repeatable runs. -Each device contains only `id`, `model`, optional `parameters` and optional -`scenario`. A model must be a profile 0.2 TM. Its instantiated TD must have a +Each device contains only `id`, `model`, and optional `parameters`, `data`, +`script` and `scriptParameters` (values a script reads as `device.parameters`). A model must be a profile 0.2 TM. Its instantiated TD must have a stable URI `id`. Supply `THING_ID` when the TM declares that placeholder or has no `id`. The deployment device ID selects management operations; the TD ID identifies the Thing; Unit ID selects the device in Modbus requests. A device's TD ID cannot @@ -78,11 +78,11 @@ The deployment format is a Modsim contract, not a standard TD object. TD generat uses `modpoll-wot==0.2.0a2` and its bundled TD/Modbus/profile validation. There is no private TD parser or arbitrary TD patch mechanism. -Scenarios keep their existing version `"1"` schema, including `initial`, generators, -bindings, seed, tick and optional local behavior scripts. Both JSON and YAML -scenario documents are accepted by managed deployments. There is no duplicate -initial-value field in deployment v2. Omitting a scenario produces valid static -initial values from the model. Scenario state is not exported as TD defaults. +`data` names [simulation data](model-validation.md#simulation-data) or a modpoll +snapshot. Both JSON and YAML documents are accepted by managed deployments. +There is no duplicate initial-value field in deployment v2. Omitting data +produces valid static initial values from the model. Simulation data is not +exported as TD defaults. Deployment files must use the `.yaml` or `.yml` extension. YAML uses safe loading with a 1 MiB document limit, bounded nesting and JSON compatible values; aliases, duplicate keys, implicit dates and non-finite numbers @@ -90,7 +90,7 @@ are rejected. Use quoted strings where YAML scalar inference is inappropriate. ## Update and reset behavior -Before changing a runtime, `up` validates every model and scenario and initializes +Before changing a runtime, `up` validates every model and data document and initializes all new or changed candidates. An invalid candidate leaves the live device set unchanged. This guarantee covers simulator state, not external side effects in explicitly enabled Python scripts. @@ -99,7 +99,7 @@ explicitly enabled Python scripts. and script state. Repeating `up` does not rerun their initialization hooks. * New IDs create independent devices. Removed IDs stop their tasks. Removing the last device leaves the listener available for a subsequent `up`. -* Changed model, parameters, scenario or behavior source replaces that device and +* Changed model, parameters, data or behavior source replaces that device and resets its state. Changes are detected by content, not just file paths. * Listener changes require `down` followed by `up`. @@ -129,7 +129,7 @@ during a real application of the update. In managed mode, a periodic behavior failure takes that device offline and marks it failed in `ps`; other devices continue. Repeated unchanged `up` preserves that -failure status. Use `reset` to retry or change the scenario and run `up`. The legacy +failure status. Use `reset` to retry or change the data or script and run `up`. The legacy flag-based startup retains its existing process-wide failure behavior. ## TD export @@ -144,7 +144,7 @@ By default, `modsim export` writes every TD to `output/` in the project root. The directory is ignored by Git. `--output-dir` changes the destination. Offline export reads the deployment, instantiates its TMs and validates the TDs; -it needs no running process or scenario files and never executes behavior scripts. `--running` +it needs no running process or data files and never executes behavior scripts. `--running` exports the last successfully applied TDs, so pending file edits cannot be mistaken for the active configuration. TD export describes interfaces and advertised endpoints, not current register values or a runtime snapshot. diff --git a/docs/site/model-validation.md b/docs/site/model-validation.md index c57d175..14b26c6 100644 --- a/docs/site/model-validation.md +++ b/docs/site/model-validation.md @@ -7,9 +7,9 @@ shared package; Modsim owns state and protocol execution. ## One device ```bash -uv run modsim --config examples/models/advantech/adam-5017uh/adam-5017uh.tm.json \ +uv run modsim --config examples/models/products/advantech/adam-5017uh/model.tm.json \ --unit-id 1 --port 5020 \ - --scenario examples/models/advantech/adam-5017uh/simulation/adam-5017uh.sim.json + --data examples/models/products/advantech/adam-5017uh/model.sim.json ``` Without `--port`, the listener uses 502, which needs administrator rights on @@ -56,24 +56,31 @@ The ADAM lab example starts two independent devices on one listener: uv run modsim up -f examples/deployment.yaml ``` -Paths in deployment files are relative to the deployment directory; scenario -script paths are relative to the scenario file. Unit IDs and TD identities must +Paths in deployment files, including data and script paths, are relative to the +deployment directory. Unit IDs and TD identities must be unique. Unknown addresses or Unit IDs never inherit another device's state. -## Scenarios +## Simulation data +`--data` takes a local path or HTTPS URL of simulation data, defined by +[modpoll-wot](https://github.com/top-maker/modpoll-wot/blob/main/profile.md#simulation-data). Version `"1"` fields: | Field | Meaning | | --- | --- | -| `initial` | Property-name/value overrides | +| `initial` | Property-name/value static values, the default | | `tick` | Update interval in seconds, default 1, minimum 0.001 | | `seed` | Per-instance random seed, default 0 | | `generators` | Property-name to generator specification | | `bindings` | Target property to source property for synthetic loopback | | `writePolicy` | `hold` (default) or `overwrite` for generated properties | -| `script` | Local Python file | -| `parameters` | Script values exposed as `device.parameters` | + +Simulation data carries no code. A modpoll `--export` snapshot is accepted as +well: the entry titled like the model, or the only entry, becomes `initial`; +points modpoll could not read (`null`) keep their defaults and are logged. +Scaled values are accepted when they are exact decimal multiples of the +multiplier or exactly the float modpoll exports, so a snapshot replays +unchanged. Generators: `constant` (`value`); `sine` (`center`, `amplitude`, positive `period`); `ramp` (`start`, `rate`, `minimum`, `maximum`, clamped to bounds); @@ -84,9 +91,8 @@ Boolean channels can use constant values, bindings or scripts. All updates must satisfy the model's schema and raw encoding bounds. Unknown properties are errors. Binding chains and cycles are rejected; use a script for ordered dependencies. -Initialization order: model defaults/type fallback → scenario initial → -CLI initial → script `initialize` → first dynamic update at elapsed 0. -`--initial` and `--initial-file` remain available for single-device runs. +Initialization order: model defaults/type fallback → data `initial` → +CLI `--initial` → script `initialize` → first dynamic update at elapsed 0. Single-device startup logs include the final initialized values; raw values are synthetic unless the contribution explicitly documents their source. @@ -107,8 +113,8 @@ response and may deliberately overwrite values. ## Local Python behaviors ```bash -uv run modsim --config examples/models/advantech/adam-5017uh/adam-5017uh.tm.json \ - --scenario examples/models/advantech/adam-5017uh/simulation/adam-5017uh-scripted-analog-input.sim.json --allow-scripts +uv run modsim --config examples/models/products/advantech/adam-5017uh/model.tm.json \ + --script behavior.py --allow-scripts ``` Optional synchronous hooks: diff --git a/examples/deployment.yaml b/examples/deployment.yaml index 8be89d8..8c48d53 100644 --- a/examples/deployment.yaml +++ b/examples/deployment.yaml @@ -5,16 +5,16 @@ server: port: 5020 devices: - id: adam-5017uh - model: examples/models/products/advantech/adam-5017uh/models/adam-5017uh.tm.json + model: examples/models/products/advantech/adam-5017uh/model.tm.json parameters: THING_ID: urn:modsim:device:advantech:adam-5017uh UNIT_ID: 1 HOST: 127.0.0.1 - scenario: examples/models/products/advantech/adam-5017uh/simulation/adam-5017uh.sim.json + data: examples/models/products/advantech/adam-5017uh/model.sim.json - id: adam-6024 model: tests/fixtures/io-module/adam-6024.tm.json parameters: THING_ID: urn:modsim:device:advantech:adam-6024 UNIT_ID: 2 HOST: 127.0.0.1 - scenario: tests/fixtures/io-module/simulation/adam-6024.sim.json + data: tests/fixtures/io-module/simulation/adam-6024.data.json diff --git a/examples/model-source.yaml b/examples/model-source.yaml index 8cff47e..f3ec603 100644 --- a/examples/model-source.yaml +++ b/examples/model-source.yaml @@ -1,6 +1,6 @@ repository: top-maker/open-modbus-catalog -revision: 3359d13e008cebfbb1c79646a4083cf5e39e0609 +revision: fd90607ef0235c5af01dfd1c62b32ca853834bdb files: - products/advantech/adam-5017uh/models/adam-5017uh.tm.json: 9e1d6e38dbb4e2db2f30f8dfd3d9df90a349b2e9aeb60a168ae4d60ee709ead7 - products/advantech/adam-5017uh/models/adam-5017uh.vectors.json: a76f365ae333b78e8113227940e15cc52e527962d676d62754d6211b184e22eb - products/advantech/adam-5017uh/simulation/adam-5017uh.sim.json: 246e0eaf9234aaec6c85c63497a27bbd89c132e436345636c9cdba8969fd3c9f + products/advantech/adam-5017uh/model.tm.json: 9e1d6e38dbb4e2db2f30f8dfd3d9df90a349b2e9aeb60a168ae4d60ee709ead7 + # Catalog schema 7 name for the simulation data; later catalog commits call it model.data.json. + products/advantech/adam-5017uh/model.sim.json: 246e0eaf9234aaec6c85c63497a27bbd89c132e436345636c9cdba8969fd3c9f diff --git a/modsim/__init__.py b/modsim/__init__.py index 24aa5d3..8fd977a 100644 --- a/modsim/__init__.py +++ b/modsim/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0a6" +__version__ = "2.0.0a7" diff --git a/modsim/codec.py b/modsim/codec.py index 6edef62..527110f 100644 --- a/modsim/codec.py +++ b/modsim/codec.py @@ -6,6 +6,7 @@ from typing import Any from jsonschema import Draft7Validator # type: ignore[import-untyped] +from modpoll_wot import DataError, scaled_raw # type: ignore[import-untyped] FORMATS = { "uint16": "H", @@ -154,22 +155,28 @@ def encode(self, value: Any) -> list[tuple[int, int]]: else: if type(value) not in (int, float): raise ValueError(f"{self.name}: expected a finite numeric value") - if not self.factor: - if value != 0: - raise ValueError( - f"{self.name}: zero multiplier only represents zero" - ) - raw = Fraction(0) - else: - raw = Fraction(str(value)) / self.factor if self.dtype.startswith("float"): - raw = float(raw) - elif raw.denominator != 1: - raise ValueError( - f"{self.name}: value is not an exact integer after inverse multiplier" - ) + if not self.factor: + if value != 0: + raise ValueError( + f"{self.name}: zero multiplier only represents zero" + ) + raw = 0.0 + else: + raw = float(Fraction(str(value)) / self.factor) else: - raw = raw.numerator + # Exact decimals and the floats modpoll exports both map back. + try: + raw = scaled_raw( + value, + ( + 1 + if self.member.multiplier is None + else self.member.multiplier + ), + ) + except DataError as exc: + raise ValueError(f"{self.name}: {exc}") from exc try: payload = self.ordered(struct.pack(">" + FORMATS[self.dtype], raw)) except (OverflowError, struct.error) as exc: diff --git a/modsim/commands.py b/modsim/commands.py index 387cf4e..6749bcd 100644 --- a/modsim/commands.py +++ b/modsim/commands.py @@ -139,7 +139,7 @@ def run(argv: list[str]) -> None: "inside the Docker Compose container" ) from exc else: - deployment = load_deployment(path, include_scenarios=False) + deployment = load_deployment(path, include_data=False) tds = {key: item.td for key, item in deployment.instances.items()} export_documents(tds, args) return diff --git a/modsim/deployment.py b/modsim/deployment.py index 21d464c..11dc89b 100644 --- a/modsim/deployment.py +++ b/modsim/deployment.py @@ -1,14 +1,17 @@ -"""Local deployment and scenario contracts for a single listener.""" +"""Simulation data and behavior for a single configured device.""" +import logging import math from pathlib import Path from typing import Any -from jsonschema import Draft7Validator # type: ignore[import-untyped] +from modpoll_wot import load_simulation_data # type: ignore[import-untyped] from modpoll_wot.loading import load_document # type: ignore[import-untyped] from .sources import is_remote, local_path, remote_document +logger = logging.getLogger(__name__) + def obj(properties: dict, required: tuple = ()) -> dict: return { @@ -20,83 +23,43 @@ def obj(properties: dict, required: tuple = ()) -> dict: STRING = {"type": "string", "minLength": 1} -NUMBER = {"type": "number"} -POSITIVE = {"type": "number", "exclusiveMinimum": 0} -INITIAL = {"type": "object"} -GENERATOR = { - "oneOf": [ - obj({"kind": {"const": "constant"}, "value": {}}, ("kind", "value")), - obj( - { - "kind": {"const": "sine"}, - "center": NUMBER, - "amplitude": {"type": "number", "minimum": 0}, - "period": POSITIVE, - }, - ("kind", "center", "amplitude", "period"), - ), - obj( - { - "kind": {"const": "ramp"}, - "start": NUMBER, - "rate": NUMBER, - "minimum": NUMBER, - "maximum": NUMBER, - }, - ("kind", "start", "rate", "minimum", "maximum"), - ), - obj( - {"kind": {"const": "noise"}, "minimum": NUMBER, "maximum": NUMBER}, - ("kind", "minimum", "maximum"), - ), - ] -} -SCENARIO = obj( - { - "version": {"const": "1"}, - "initial": INITIAL, - "seed": {"type": "integer"}, - "tick": POSITIVE, - "generators": {"type": "object", "additionalProperties": GENERATOR}, - "bindings": {"type": "object", "additionalProperties": STRING}, - "script": STRING, - "parameters": INITIAL, - "writePolicy": {"enum": ["hold", "overwrite"]}, - }, - ("version",), -) - - -def document(path: str, schema: dict) -> dict: - source: str | Path - if is_remote(path): - source = path - value = remote_document(path) - # Behavior scripts are local code; never resolve them from a download. - if isinstance(value, dict) and "script" in value: - raise ValueError(f"{path}: remote scenarios cannot reference scripts") - else: - source = Path(local_path(Path.cwd(), path)) - value = load_document(source) - errors = sorted( - Draft7Validator(schema).iter_errors(value), key=lambda error: str(error.path) + + +def data_document(source: str) -> dict: + """Load simulation data, or a modpoll --export snapshot, from a path or HTTPS URL.""" + if is_remote(source): + return remote_document(source) + return load_document(Path(local_path(Path.cwd(), source))) # type: ignore[no-any-return] + + +def resolve_data(document: dict, device: Any, title: str) -> dict: + """Check simulation data or a snapshot against the device's properties.""" + loaded = load_simulation_data( + document, title=title, properties=device.members.keys() ) - if errors: - error = errors[0] - raise ValueError(f"{source}: {'/'.join(map(str, error.path))}: {error.message}") - return value + if loaded.unread: + logger.warning( + "%s: snapshot points without a value keep their defaults: %s", + title, + ", ".join(loaded.unread), + ) + return loaded.data # type: ignore[no-any-return] -def apply_scenario(args: Any) -> None: +def apply_data(args: Any) -> None: + """Apply simulation data, CLI initial values and local behavior to a device.""" device = args.runtime - spec = getattr(args, "scenario_spec", None) + title = args.model_initialization["title"] + spec = getattr(args, "data_spec", None) if spec is None: - spec = document(args.scenario, SCENARIO) if args.scenario else {} + spec = ( + resolve_data(data_document(args.data), device, title) if args.data else {} + ) device.tick_interval = spec.get("tick", 1.0) if not math.isfinite(device.tick_interval) or device.tick_interval < 0.001: - raise ValueError("scenario tick must be finite and at least 0.001 seconds") + raise ValueError("data tick must be finite and at least 0.001 seconds") device.random.seed(spec.get("seed", 0)) - device.parameters = spec.get("parameters", {}) + device.parameters = getattr(args, "script_parameters", None) or {} device.generators = spec.get("generators", {}) device.bindings = spec.get("bindings", {}) device.write_policy = spec.get("writePolicy", "hold") @@ -105,7 +68,9 @@ def apply_scenario(args: Any) -> None: targets - device.members.keys() or set(device.bindings.values()) - device.members.keys() ): - raise ValueError(f"{device.name}: scenario references unknown properties") + raise ValueError( + f"{device.name}: simulation data references unknown properties" + ) if device.generators.keys() & device.bindings.keys(): raise ValueError("a property cannot have both a generator and a binding") if device.bindings.keys() & set(device.bindings.values()): @@ -143,18 +108,12 @@ def apply_scenario(args: Any) -> None: finally: device.cells = saved initial = dict(spec.get("initial", {})) - # CLI/deployment initial values take precedence over scenario defaults. - from modpoll_wot import parse_parameters # type: ignore[import-untyped] + # CLI initial values take precedence over simulation data. + from modpoll_wot import parse_parameters - if args.initial_file: - initial.update(load_document(args.initial_file)) initial.update(parse_parameters(args.initial)) device.set_many(initial) script = args.script - if script and spec.get("script"): - raise ValueError("choose a script in either the scenario or device/CLI") - if not script and spec.get("script"): - script = local_path(Path(args.scenario).resolve().parent, spec["script"]) if script: if not args.allow_scripts: raise ValueError("Python behavior scripts require --allow-scripts") @@ -165,21 +124,16 @@ def apply_scenario(args: Any) -> None: device.advance(0.0, 0.0) origins = args.model_initialization["origins"] for name in spec.get("initial", {}): - origins[name] = "scenario initial" - for name in initial: - if ( - name not in spec.get("initial", {}) - or name in parse_parameters(args.initial) - or args.initial_file - ): - origins[name] = "instance initial" + origins[name] = "data initial" + for name in parse_parameters(args.initial): + origins[name] = "instance initial" if script: for name in origins: origins[name] = "local script/initialization" for name in device.generators: - origins[name] = "scenario generator" + origins[name] = "data generator" for name in device.bindings: - origins[name] = "scenario binding" + origins[name] = "data binding" args.model_initialization["values"] = { name: device.get(name) for name in device.members } @@ -190,6 +144,6 @@ def configure_devices(args: Any) -> list: from .wot import configure sim = configure(args) - apply_scenario(args) + apply_data(args) args.runtimes = [args.runtime] return [sim] diff --git a/modsim/manifest.py b/modsim/manifest.py index 46afb17..63c1eea 100644 --- a/modsim/manifest.py +++ b/modsim/manifest.py @@ -10,10 +10,14 @@ import yaml # type: ignore[import-untyped] from jsonschema import Draft7Validator # type: ignore[import-untyped] -from modpoll_wot import export_td, parse_model # type: ignore[import-untyped] +from modpoll_wot import ( # type: ignore[import-untyped] + export_td, + load_simulation_data, + parse_model, +) from modpoll_wot.loading import MAX_BYTES, load_document # type: ignore[import-untyped] -from .deployment import SCENARIO, STRING, obj +from .deployment import STRING, obj from .sources import local_path, model_document @@ -63,7 +67,9 @@ def construct_mapping(self, node: Any, deep: bool = False) -> dict: "id": IDENTIFIER, "model": STRING, "parameters": {"type": "object"}, - "scenario": STRING, + "data": STRING, + "script": STRING, + "scriptParameters": {"type": "object"}, }, ("id", "model"), ), @@ -120,13 +126,14 @@ class Instance: td: dict model: Any fingerprint: str - scenario: dict + data: dict script_path: str | None script_source: bytes | None + script_parameters: dict def build(self, allow_scripts: bool = False, *, preview: bool = False) -> Any: """Construct isolated state from this snapshot, without reopening inputs.""" - from .deployment import apply_scenario + from .deployment import apply_data from .wot import configure if self.script_source is not None: @@ -136,17 +143,17 @@ def build(self, allow_scripts: bool = False, *, preview: bool = False) -> Any: compile(self.script_source, self.script_path or "", "exec") args = Namespace( prepared_model=self.model, - initial_file=None, initial=[], - scenario=None, - scenario_spec=copy.deepcopy(self.scenario), + data=None, + data_spec=copy.deepcopy(self.data), script=None if preview else self.script_path, script_source=self.script_source, + script_parameters=copy.deepcopy(self.script_parameters), allow_scripts=allow_scripts, ) configure(args) args.runtime.name = self.id - apply_scenario(args) + apply_data(args) return args.runtime @@ -171,7 +178,7 @@ def deployment_root(path: Path) -> Path: return path.parent -def load_deployment(path: Path, *, include_scenarios: bool = True) -> Deployment: +def load_deployment(path: Path, *, include_data: bool = True) -> Deployment: """Resolve and validate every instance before the runtime can be changed.""" path = path.resolve() if path.suffix.lower() not in (".yaml", ".yml"): @@ -233,25 +240,32 @@ def load_deployment(path: Path, *, include_scenarios: bool = True) -> Deployment raise ValueError(f"{key}: duplicate TD id or Unit ID") units.add(model.unit_id) identities.add(identity) - scenario = {} + data: dict = {} script_path, script_source = None, None - if include_scenarios and item.get("scenario"): - scene_path = Path(local_path(root, item["scenario"])) - scenario = read_yaml(scene_path) - validate(scenario, SCENARIO) - if scenario.get("script"): - script_path = local_path(scene_path.parent, scenario["script"]) - with Path(script_path).open("rb") as stream: - script_source = stream.read(MAX_BYTES + 1) - if len(script_source) > MAX_BYTES: - raise ValueError("script exceeds 1 MiB") - # Resolved script is supplied separately to apply_scenario. - scenario = {k: v for k, v in scenario.items() if k != "script"} + if include_data and item.get("data"): + data = load_simulation_data( + read_yaml(Path(local_path(root, item["data"]))), + title=model.title, + properties=json.loads(model.properties_json).keys(), + ).data + if include_data and item.get("script"): + script_path = local_path(root, item["script"]) + with Path(script_path).open("rb") as stream: + script_source = stream.read(MAX_BYTES + 1) + if len(script_source) > MAX_BYTES: + raise ValueError("script exceeds 1 MiB") + script_parameters = dict(item.get("scriptParameters", {})) fingerprint = hashlib.sha256( - canonical([item, document, td, scenario, script_path]) - + (script_source or b"") + canonical([item, document, td, data, script_path]) + (script_source or b"") ).hexdigest() instances[key] = Instance( - key, td, model, fingerprint, scenario, script_path, script_source + key, + td, + model, + fingerprint, + data, + script_path, + script_source, + script_parameters, ) return Deployment(path, name, bind, port, instances) diff --git a/modsim/sources.py b/modsim/sources.py index 8a4ef92..aa88d3b 100644 --- a/modsim/sources.py +++ b/modsim/sources.py @@ -1,4 +1,4 @@ -"""Bounded local JSON and HTTPS model and scenario loading.""" +"""Bounded local JSON and HTTPS model and simulation data loading.""" import tempfile from pathlib import Path @@ -33,7 +33,7 @@ def remote_document(source: str) -> dict: """Load bounded JSON from an HTTPS URL with the shared loader's rules.""" url = urlparse(source) if url.scheme != "https": - raise ValueError("model and scenario URLs must use HTTPS") + raise ValueError("model and data URLs must use HTTPS") if url.hostname == "github.com": parts = url.path.strip("/").split("/") if len(parts) >= 5 and parts[2] == "blob": diff --git a/modsim/utils.py b/modsim/utils.py index bed8f9c..7737a5d 100644 --- a/modsim/utils.py +++ b/modsim/utils.py @@ -24,7 +24,11 @@ def get_parser() -> argparse.ArgumentParser: sources = parser.add_mutually_exclusive_group() sources.add_argument("--config", help="Profile 0.2 TM/TD local path or HTTPS URL") parser.add_argument( - "--scenario", help="Scenario JSON local path or HTTPS URL for --config" + "--data", + help=( + "Simulation data for --config: a local path or HTTPS URL of a data " + "document or a modpoll --export snapshot" + ), ) parser.add_argument("--script", help="Local Python behavior for --config") parser.add_argument( @@ -40,9 +44,6 @@ def get_parser() -> argparse.ArgumentParser: parser.add_argument( "--initial", action="append", default=[], metavar="PROPERTY=JSON" ) - parser.add_argument( - "--initial-file", help="Property-name/value JSON initialization file" - ) parser.add_argument( "--comm", choices=["tcp", "udp", "serial", "tls"], @@ -97,14 +98,13 @@ def get_commandline() -> argparse.Namespace: args.comm = args.comm or "tcp" if not args.config and ( args.initial - or args.initial_file or args.param or args.unit_id is not None - or args.scenario + or args.data or args.script ): parser.error( - "--initial, --initial-file, --param and --unit-id require --config" + "--data, --initial, --param, --script and --unit-id require --config" ) if args.bind and args.comm != "tcp": parser.error("--bind currently supports --comm tcp only") diff --git a/modsim/wot.py b/modsim/wot.py index 8e1b41f..eae2ac0 100644 --- a/modsim/wot.py +++ b/modsim/wot.py @@ -4,7 +4,6 @@ from typing import Any from modpoll_wot import parse_model, parse_parameters # type: ignore[import-untyped] -from modpoll_wot.loading import load_document # type: ignore[import-untyped] from pymodbus.constants import ExcCodes from pymodbus.simulator import DataType, SimData, SimDevice @@ -37,15 +36,7 @@ def configure(args: Any) -> SimDevice: if model.profile_version != "0.2" or model.properties_json is None: raise ValueError("configured simulation requires profile 0.2") schemas = json.loads(model.properties_json) - overrides: dict[str, Any] = {} - if args.initial_file: - overrides = load_document(args.initial_file) - if not isinstance(overrides, dict): - raise ValueError("--initial-file must contain a property-name/value object") - cli_values = parse_parameters(args.initial) - if overrides.keys() & cli_values.keys(): - raise ValueError("duplicate initial values in --initial and --initial-file") - overrides.update(cli_values) + overrides: dict[str, Any] = parse_parameters(args.initial) if overrides.keys() - schemas.keys(): raise ValueError( f"unknown initial properties: {sorted(overrides.keys() - schemas.keys())}" diff --git a/pyproject.toml b/pyproject.toml index 24fd54f..57540e6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,13 @@ [project] name = "modsim" -version = "2.0.0a6" +version = "2.0.0a7" 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", - "modpoll-wot==0.3.0a3", + "modpoll-wot==0.4.0a1", "jsonschema>=4.21,<5", "PyYAML>=6,<7", ] diff --git a/tests/fixtures/io-module/README.md b/tests/fixtures/io-module/README.md index 7a39778..d4124eb 100644 --- a/tests/fixtures/io-module/README.md +++ b/tests/fixtures/io-module/README.md @@ -1,6 +1,6 @@ # Runtime regression fixture -Frozen MIT model/scenario/TD used only for protocol and codec regression. +Frozen MIT model/simulation data/TD used only for protocol and codec regression. Not a device contribution or independently maintained product mapping. It also serves as the ADAM-6024 device in examples/deployment.yaml. Generated TDs are checked by tools/generate-td.py. Do not use this fixture as a model contribution target. diff --git a/tests/fixtures/io-module/generated.json b/tests/fixtures/io-module/generated.json index dee870f..3a6c337 100644 --- a/tests/fixtures/io-module/generated.json +++ b/tests/fixtures/io-module/generated.json @@ -3,7 +3,7 @@ "source_sha256": "4c2aee3334faf6622f4ee34a23108fa0ec100a6b3110a78200eee79da8935596", "generator": { "package": "modpoll-wot", - "version": "0.3.0a3" + "version": "0.4.0a1" }, "instance": { "host": "127.0.0.1", diff --git a/tests/fixtures/io-module/simulation/adam-6024.sim.json b/tests/fixtures/io-module/simulation/adam-6024.data.json similarity index 100% rename from tests/fixtures/io-module/simulation/adam-6024.sim.json rename to tests/fixtures/io-module/simulation/adam-6024.data.json diff --git a/tests/test_acceptance_fixtures.py b/tests/test_acceptance_fixtures.py index 6904bc8..be1f00f 100644 --- a/tests/test_acceptance_fixtures.py +++ b/tests/test_acceptance_fixtures.py @@ -14,7 +14,7 @@ spec.loader.exec_module(prepare_acceptance) -def test_relocated_manifest_preserves_model_and_scenario_base(tmp_path, monkeypatch): +def test_relocated_manifest_preserves_model_and_data_base(tmp_path, monkeypatch): directory = tmp_path / "examples" directory.mkdir() (directory / "model-source.yaml").write_text("revision: pinned\n") @@ -25,7 +25,7 @@ def test_relocated_manifest_preserves_model_and_scenario_base(tmp_path, monkeypa "devices": [ { "model": "examples/models/vendor/model.tm.json", - "scenario": "examples/models/vendor/initial.sim.json", + "data": "examples/models/vendor/model.data.json", } ] } @@ -39,7 +39,7 @@ def test_relocated_manifest_preserves_model_and_scenario_base(tmp_path, monkeypa assert str(directory / "models") in args device = yaml.safe_load(manifest.read_text())["devices"][0] assert device["model"] == str(directory / "models/vendor/model.tm.json") - assert device["scenario"] == str(directory / "models/vendor/initial.sim.json") + assert device["data"] == str(directory / "models/vendor/model.data.json") def test_historical_release_is_left_unchanged(tmp_path, monkeypatch): diff --git a/tests/test_catalog_platform.py b/tests/test_catalog_platform.py index 384e4ed..47cf806 100644 --- a/tests/test_catalog_platform.py +++ b/tests/test_catalog_platform.py @@ -22,10 +22,10 @@ def test_remote_model_single_device_read_and_stop(tmp_path): lock = yaml.safe_load( (Path(__file__).resolve().parents[1] / "examples/model-source.yaml").read_text() ) - url = f"https://raw.githubusercontent.com/{lock['repository']}/{lock['revision']}/products/advantech/adam-5017uh/models/adam-5017uh.tm.json" - scenario = tmp_path / "initial.sim.json" + url = f"https://raw.githubusercontent.com/{lock['repository']}/{lock['revision']}/products/advantech/adam-5017uh/model.tm.json" + data = tmp_path / "initial.data.json" values = [0x1234, 0x8001, 0xABCD, 0, 65535, 42, 0x0102, 0xFE01] - scenario.write_text( + data.write_text( json.dumps( {"version": "1", "initial": {f"AI{i}_RAW": v for i, v in enumerate(values)}} ) @@ -49,8 +49,8 @@ def test_remote_model_single_device_read_and_stop(tmp_path): str(port), "--unit-id", "1", - "--scenario", - str(scenario), + "--data", + str(data), ], cwd=tmp_path, env=env, diff --git a/tests/test_codec.py b/tests/test_codec.py index 6906c1a..4d1484a 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -194,7 +194,7 @@ def test_exact_inverse_multiplier_negative_and_zero(tmp_path): instance = configure_properties(tmp_path, {"value": mapping}, {"value": 12.3}) assert instance.cells["holding_register"][0] == 0xFF85 assert instance.get("value") == 12.3 - with pytest.raises(ValueError, match="exact integer"): + with pytest.raises(ValueError, match="integer multiple"): instance.set("value", 12.35) assert instance.get("value") == 12.3 mapping["forms"][0]["modpoll:multiplier"] = 0 @@ -315,8 +315,8 @@ def test_tcp_wide_values_partial_writes_and_writeonly(tmp_path): "flags": [True, False] * 4, } configure_properties(tmp_path, properties, initial) - initial_path = tmp_path / "initial.json" - initial_path.write_text(json.dumps(initial)) + data_path = tmp_path / "initial.data.json" + data_path.write_text(json.dumps({"version": "1", "initial": initial})) with socket.socket() as reservation: reservation.bind(("127.0.0.1", 0)) port = reservation.getsockname()[1] @@ -330,8 +330,8 @@ def test_tcp_wide_values_partial_writes_and_writeonly(tmp_path): "modsim", "--config", str(tmp_path / "codec.tm.json"), - "--initial-file", - str(initial_path), + "--data", + str(data_path), "--port", str(port), "--unit-id", diff --git a/tests/test_deployment.py b/tests/test_deployment.py index 6531a76..43b5ad3 100644 --- a/tests/test_deployment.py +++ b/tests/test_deployment.py @@ -34,23 +34,17 @@ def device(unit=1, **options): def build(tmp_path, devices, **server): - # The fixture creates version 2 declarations; initial values and scripts - # belong to scenario documents, not deployment device fields. + # The fixture creates version 2 declarations; initial values belong to + # simulation data documents, not deployment device fields. import copy devices = copy.deepcopy(devices) for index, spec in enumerate(devices): initial = spec.pop("initial", None) - script = spec.pop("script", None) - if initial is not None or script: - scene = {"version": "1"} - if initial is not None: - scene["initial"] = initial - if script: - scene["script"] = script - scene_path = tmp_path / f"fixture-scene-{index}.json" - scene_path.write_text(json.dumps(scene)) - spec["scenario"] = str(scene_path) + if initial is not None: + data_path = tmp_path / f"fixture-data-{index}.json" + data_path.write_text(json.dumps({"version": "1", "initial": initial})) + spec["data"] = str(data_path) path = tmp_path / "deployment.yaml" path.write_text( yaml.safe_dump( @@ -93,7 +87,7 @@ def test_duplicate_instances_fail_before_listening(tmp_path, devices): build(tmp_path, devices) -def test_relative_scenario_script_and_instance_state(tmp_path, monkeypatch): +def test_relative_script_and_instance_state(tmp_path, monkeypatch): (tmp_path / "models").mkdir() (tmp_path / "models/io.tm.json").write_bytes(MODEL.read_bytes()) (tmp_path / "scenes").mkdir() @@ -113,11 +107,8 @@ def on_write(device, changes): device.set("AI0_RAW", changes["AO0_RAW"]) """ ) - (tmp_path / "scenes/io.json").write_text( - json.dumps({"version": "1", "script": "behavior.py"}) - ) specs = [ - device(unit, model="models/io.tm.json", scenario="scenes/io.json") + device(unit, model="models/io.tm.json", script="scenes/behavior.py") for unit in (1, 2) ] monkeypatch.chdir("/") @@ -135,12 +126,9 @@ def on_write(device, changes): def test_script_requires_opt_in_and_unknown_fields_rejected(tmp_path): (tmp_path / "script.py").write_text('raise AssertionError("must not execute")') path = tmp_path / "denied.yaml" - (tmp_path / "scene.json").write_text( - json.dumps({"version": "1", "script": "script.py"}) - ) path.write_text( yaml.safe_dump( - {"version": 2, "name": "denied", "devices": [device(scenario="scene.json")]} + {"version": 2, "name": "denied", "devices": [device(script="script.py")]} ) ) with pytest.raises(ValueError, match="allow-scripts"): @@ -150,15 +138,13 @@ def test_script_requires_opt_in_and_unknown_fields_rejected(tmp_path): def test_seeded_noise_and_client_write_policy(tmp_path): - scenario = { + data = { "version": "1", "seed": 73, "generators": {"AO0_RAW": {"kind": "noise", "minimum": 1, "maximum": 100}}, } - (tmp_path / "scene.json").write_text(json.dumps(scenario)) - args = build( - tmp_path, [device(1, scenario="scene.json"), device(2, scenario="scene.json")] - ) + (tmp_path / "data.json").write_text(json.dumps(data)) + args = build(tmp_path, [device(1, data="data.json"), device(2, data="data.json")]) first, second = args.runtimes assert first.get("AO0_RAW") == second.get("AO0_RAW") first.advance(1, 1) @@ -220,8 +206,8 @@ def test_multi_device_listener_loopback_and_shutdown(tmp_path): device(1, initial={"AO0_RAW": 10}), device( 2, - scenario=str( - ROOT / "tests/fixtures/io-module/simulation/adam-6024.sim.json" + data=str( + ROOT / "tests/fixtures/io-module/simulation/adam-6024.data.json" ), ), ], @@ -280,14 +266,14 @@ def test_invalid_generator_envelope_and_binding_cycles_fail_at_startup(tmp_path) ) ) with pytest.raises(ValueError): - build(tmp_path, [device(scenario=scene.name)]) + build(tmp_path, [device(data=scene.name)]) scene.write_text( json.dumps( {"version": "1", "bindings": {"AO0_RAW": "AO1_RAW", "AO1_RAW": "AO0_RAW"}} ) ) with pytest.raises(ValueError, match="chains/cycles"): - build(tmp_path, [device(scenario=scene.name)]) + build(tmp_path, [device(data=scene.name)]) def test_failed_write_hook_rolls_back_entire_device(tmp_path): diff --git a/tests/test_management.py b/tests/test_management.py index 0f9c620..9634d7a 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -26,7 +26,7 @@ def fixture(tmp_path): model["id"] = "{{THING_ID}}" model["title"] = "{{TITLE}}" (tmp_path / "io.tm.json").write_text(json.dumps(model)) - (tmp_path / "scene.json").write_text( + (tmp_path / "data.json").write_text( json.dumps({"version": "1", "initial": {"AO0_RAW": 12}}) ) with socket.socket() as reservation: @@ -52,7 +52,7 @@ def device(unit): "TITLE": f"I/O {unit}", "UNIT_ID": unit, }, - "scenario": "scene.json", + "data": "data.json", } @@ -165,7 +165,7 @@ async def exercise(): await manager.apply(load_deployment(path)) assert retired.done() assert 2 not in manager.context.devices - (tmp_path / "scene.json").write_text("invalid on disk") + (tmp_path / "data.json").write_text("invalid on disk") await manager.reset("io-1") assert manager.devices["io-1"].get("AO0_RAW") == 12 finally: @@ -188,9 +188,8 @@ async def exercise(): try: await manager.apply(load_deployment(path)) original = manager.devices["io-1"] - (tmp_path / "scene.json").write_text( - json.dumps({"version": "1", "script": "behavior.py"}) - ) + spec["devices"][0]["script"] = "behavior.py" + write(path, spec) desired = load_deployment(path) plan = await manager.apply(desired, dry_run=True) assert plan["replaced"] == ["io-1"] @@ -279,9 +278,8 @@ def test_cli_live_add_remove_replace_export_reset_and_rollback(tmp_path): def test_offline_export_requires_no_process_and_does_not_run_behavior(tmp_path): path, spec, _ = fixture(tmp_path) (tmp_path / "fail.py").write_text("raise RuntimeError('must not execute')") - (tmp_path / "scene.json").write_text( - json.dumps({"version": "1", "script": "fail.py"}) - ) + spec["devices"][0]["script"] = "fail.py" + write(path, spec) output = tmp_path / "tds" cli(path, "export", "--output-dir", str(output)) td = json.loads((output / "io-1.td.json").read_text()) @@ -296,11 +294,9 @@ def test_reset_uses_pristine_script_parameters(tmp_path): " device.parameters['counter'] += 1\n" " device.set('AO0_RAW', device.parameters['counter'])\n" ) - (tmp_path / "scene.json").write_text( - json.dumps( - {"version": "1", "parameters": {"counter": 0}, "script": "behavior.py"} - ) - ) + spec["devices"][0]["script"] = "behavior.py" + spec["devices"][0]["scriptParameters"] = {"counter": 0} + write(path, spec) async def exercise(): manager = RuntimeManager(allow_scripts=True) @@ -322,10 +318,9 @@ def test_managed_behavior_failure_isolated_and_not_revived_by_unchanged_up(tmp_p " if elapsed > 0:\n" " raise RuntimeError('failed device')\n" ) - (tmp_path / "fail.json").write_text( - json.dumps({"version": "1", "tick": 0.001, "script": "fail.py"}) - ) - spec["devices"][0]["scenario"] = "fail.json" + (tmp_path / "fail.json").write_text(json.dumps({"version": "1", "tick": 0.001})) + spec["devices"][0]["data"] = "fail.json" + spec["devices"][0]["script"] = "fail.py" spec["devices"].append(device(2)) write(path, spec) @@ -349,9 +344,9 @@ async def exercise(): asyncio.run(exercise()) -def test_export_does_not_require_scenario_files(tmp_path): +def test_export_does_not_require_data_files(tmp_path): path, spec, _ = fixture(tmp_path) - (tmp_path / "scene.json").unlink() + (tmp_path / "data.json").unlink() output = tmp_path / "instance.td.json" cli(path, "export", "--device", "io-1", "-o", str(output)) assert parse_model(json.loads(output.read_text())).unit_id == 1 diff --git a/tests/test_remote_sources.py b/tests/test_remote_sources.py index b4744aa..1014dcd 100644 --- a/tests/test_remote_sources.py +++ b/tests/test_remote_sources.py @@ -1,4 +1,4 @@ -"""HTTPS model and scenario sources.""" +"""HTTPS model and simulation data sources.""" from io import BytesIO import json @@ -6,6 +6,8 @@ import pytest +from modpoll_wot import load_simulation_data + from modsim import __version__, deployment, sources @@ -21,22 +23,21 @@ def geturl(self): def test_remote_documents_identify_modsim(): payload = json.dumps({"version": "1", "tick": 0.5}).encode() with patch.object(sources, "urlopen", return_value=Response(payload)) as remote: - scenario = deployment.document( - "https://example.invalid/device.sim.json", deployment.SCENARIO - ) - assert scenario == {"version": "1", "tick": 0.5} + data = deployment.data_document("https://example.invalid/device.data.json") + assert data == {"version": "1", "tick": 0.5} request = remote.call_args.args[0] - assert request.full_url == "https://example.invalid/device.sim.json" + assert request.full_url == "https://example.invalid/device.data.json" assert request.get_header("User-agent") == f"modsim/{__version__}" -def test_remote_scenarios_reject_scripts_and_plain_http(): +def test_simulation_data_rejects_scripts_and_plain_http(): payload = json.dumps({"version": "1", "script": "behavior.py"}).encode() with patch.object(sources, "urlopen", return_value=Response(payload)): - with pytest.raises(ValueError, match="cannot reference scripts"): - deployment.document("https://example.invalid/s.json", deployment.SCENARIO) + document = deployment.data_document("https://example.invalid/s.json") + with pytest.raises(ValueError, match="script"): + load_simulation_data(document) with pytest.raises(ValueError, match="must use HTTPS"): - deployment.document("http://example.invalid/s.json", deployment.SCENARIO) + deployment.data_document("http://example.invalid/s.json") redirected = Response(b"{}", url="http://example.invalid/s.json") with patch.object(sources, "urlopen", return_value=redirected): with pytest.raises(ValueError, match="redirect must use HTTPS"): diff --git a/tests/test_snapshot_replay.py b/tests/test_snapshot_replay.py new file mode 100644 index 0000000..c0938c0 --- /dev/null +++ b/tests/test_snapshot_replay.py @@ -0,0 +1,152 @@ +"""modpoll reads a simulated device, exports a snapshot, and modsim replays it. + +Runs when MODSIM_TEST_MODPOLL_PYTHON names a Python environment with modpoll +installed; modsim and modpoll stay independent installations. +""" + +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import time + +import pytest + +MODPOLL = os.environ.get("MODSIM_TEST_MODPOLL_PYTHON") +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif(not MODPOLL, reason="MODSIM_TEST_MODPOLL_PYTHON is not set"), +] +ROOT = Path(__file__).resolve().parents[1] + + +def register(raw, address, quantity=1, multiplier=None, kind="number"): + form = { + "op": "readproperty", + "modv:entity": "HoldingRegister", + "modv:address": address, + "modv:quantity": quantity, + "modv:type": "xsd:" + raw, + } + if multiplier is not None: + form["modpoll:multiplier"] = multiplier + return {"type": kind, "readOnly": True, "forms": [form]} + + +MODEL = { + "@context": [ + "https://www.w3.org/2022/wot/td/v1.1", + { + "modpoll": "https://top-maker.github.io/modpoll/vocab/wot-modbus#", + "modv": "https://www.w3.org/2019/wot/modbus", + "xsd": "http://www.w3.org/2001/XMLSchema#", + }, + ], + "@type": "tm:ThingModel", + "title": "replay-meter", + "modpoll:version": "0.2", + "properties": { + "VOLTAGE": register("unsignedShort", 0, multiplier="0.1"), + "CURRENT": register("short", 1, multiplier="0.001"), + "ENERGY": register("unsignedInt", 2, 2, multiplier="0.01"), + "FREQUENCY": register("float", 4, 2), + "STATUS": register("unsignedShort", 6, kind="integer"), + }, + "modpoll:acquisition": [ + { + "modv:entity": "HoldingRegister", + "modv:address": 0, + "modv:quantity": 7, + "modpoll:members": ["VOLTAGE", "CURRENT", "ENERGY", "FREQUENCY", "STATUS"], + } + ], +} +# 230.1 and 4.987 read back as 230.10000000000002 and 4.987 with float scaling; +# the replay must serve whatever modpoll exported. +INITIAL = { + "VOLTAGE": 230.1, + "CURRENT": -4.987, + "ENERGY": 123456.78, + "FREQUENCY": 50.0, + "STATUS": 4660, +} + + +def serve_and_read(tmp_path, model, data, name): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + env = {**os.environ, "PYTHONPATH": str(ROOT)} + with (tmp_path / f"{name}.log").open("w+") as log: + server = subprocess.Popen( + [ + sys.executable, + "-m", + "modsim", + "--config", + str(model), + "--data", + str(data), + "--bind", + "127.0.0.1", + "--port", + str(port), + ], + cwd=tmp_path, + env=env, + stdout=log, + stderr=log, + ) + try: + deadline = time.monotonic() + 30 + while True: + if server.poll() is not None: + log.seek(0) + raise AssertionError(log.read()) + try: + socket.create_connection(("127.0.0.1", port), timeout=0.2).close() + break + except OSError: + assert time.monotonic() < deadline, "modsim did not start" + time.sleep(0.1) + snapshot = tmp_path / f"{name}.snapshot.json" + subprocess.run( + [ + MODPOLL, + "-m", + "modpoll", + "--config", + str(model), + "--tcp", + "127.0.0.1", + "--tcp-port", + str(port), + "--once", + "--export", + str(snapshot), + ], + check=True, + capture_output=True, + timeout=60, + ) + return snapshot + finally: + server.terminate() + server.wait(timeout=10) + + +def test_exported_snapshot_replays_unchanged(tmp_path): + model = tmp_path / "replay.tm.json" + model.write_text(json.dumps(MODEL)) + data = tmp_path / "initial.data.json" + data.write_text(json.dumps({"version": "1", "initial": INITIAL})) + + first = serve_and_read(tmp_path, model, data, "first") + exported = json.loads(first.read_text())["replay-meter"] + assert exported["VOLTAGE"] == float(2301) * 0.1 != 230.1 + assert exported["STATUS"] == 4660 + + replayed = serve_and_read(tmp_path, model, first, "replay") + assert json.loads(replayed.read_text()) == json.loads(first.read_text()) diff --git a/tools/catalog-interop.py b/tools/catalog-interop.py index 4232555..4172297 100644 --- a/tools/catalog-interop.py +++ b/tools/catalog-interop.py @@ -20,7 +20,7 @@ import yaml ROOT = Path(__file__).resolve().parents[1] -TM_PATH = "products/advantech/adam-5017uh/models/adam-5017uh.tm.json" +TM_PATH = "products/advantech/adam-5017uh/model.tm.json" VALUES = [0x1234, 0x8001, 0xABCD, 0, 65535, 42, 0x0102, 0xFE01] EXPECTED = {f"AI{i}_RAW": value for i, value in enumerate(VALUES)} @@ -76,17 +76,8 @@ def run(args): port = reserve.getsockname()[1] with TemporaryDirectory(prefix="modsim-catalog-interop-") as temporary: work = Path(temporary) - if args.vectors and json.loads(args.vectors.read_bytes()) != EXPECTED: - raise ValueError( - "Catalog vectors differ from the independent expected vector" - ) - scenario = work / "initial.sim.json" - scenario.write_text(json.dumps({"version": "1", "initial": EXPECTED})) - vectors_digest = ( - hashlib.sha256(args.vectors.read_bytes()).hexdigest() - if args.vectors - else None - ) + data = work / "initial.data.json" + data.write_text(json.dumps({"version": "1", "initial": EXPECTED})) env = dict(os.environ) env.pop("PYTHONPATH", None) with (work / "simulator.log").open("w+") as log: @@ -103,8 +94,8 @@ def run(args): str(port), "--unit-id", "1", - "--scenario", - str(scenario), + "--data", + str(data), ], cwd=work, env=env, @@ -206,7 +197,6 @@ def run(args): report = { "executed-at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "data-revision": revision, - "vectors-sha256": vectors_digest, "td-sha256": td_digest, "td-endpoint": { "host": "127.0.0.1", @@ -250,11 +240,6 @@ def run(args): parser.add_argument( "--lock", type=Path, default=ROOT / "examples/model-source.yaml" ) - parser.add_argument( - "--vectors", - type=Path, - help="Catalog vectors file that must equal the independent known vector", - ) parser.add_argument("--modpoll-python", type=Path, required=True) parser.add_argument("--node-reader", type=Path, required=True) parser.add_argument( diff --git a/tools/prepare-acceptance.py b/tools/prepare-acceptance.py index bd75520..4a0728a 100644 --- a/tools/prepare-acceptance.py +++ b/tools/prepare-acceptance.py @@ -30,7 +30,7 @@ def prepare(root): # The source example uses repository-root paths. A detached acceptance tree # has no Git root, so make that original base explicit in the staged copy. for device in document["devices"]: - for key in ("model", "scenario"): + for key in ("model", "data", "script"): if key in device and not device[key].startswith("https://"): device[key] = str((root / device[key]).resolve()) manifest.write_text(yaml.safe_dump(document, sort_keys=False)) diff --git a/uv.lock b/uv.lock index d4bd088..36affca 100644 --- a/uv.lock +++ b/uv.lock @@ -829,20 +829,20 @@ wheels = [ [[package]] name = "modpoll-wot" -version = "0.3.0a3" +version = "0.4.0a1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" }, { name = "referencing", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ec/c3/aec90bc5a9b1eac294e49e6f0d5ad85846da505f9ee12639ac57d2ba74c7/modpoll_wot-0.3.0a3.tar.gz", hash = "sha256:e2f61c65540d8487eb1f91adbff812d29580c3195632a4a2377374134ee84305", size = 50388, upload-time = "2026-11-10T13:56:03.147Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/19/f27b28a5e50b5ff8c7cb25e3593df58f31c65d4da5f29d051d29ee0f4d2a/modpoll_wot-0.4.0a1.tar.gz", hash = "sha256:81d25997407a64799a034ad4df9c53dbb4f8a7842f4416dacb81a7e26d95b6b6", size = 54976, upload-time = "2026-11-12T03:52:27.323Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/09/80/cf5e0a63ff469cda8818116e5f8e3bdc8a293aa83a8ba788566f7903198f/modpoll_wot-0.3.0a3-py3-none-any.whl", hash = "sha256:1fb4a27a5a4503512303155881ec8b13c0543d086d39767d613434782d46161e", size = 42463, upload-time = "2026-11-10T13:56:02.184Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d3/4400813559fd11ca7d758d5ab343505366a7dd94c65be0c293b8048d915c/modpoll_wot-0.4.0a1-py3-none-any.whl", hash = "sha256:9708d2cadf65ce93626eb5755905f25e7aedcc1b9746e66277d5d94f08aa4c76", size = 46936, upload-time = "2026-11-12T03:52:26.239Z" }, ] [[package]] name = "modsim" -version = "2.0.0a6" +version = "2.0.0a7" source = { editable = "." } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" }, @@ -872,7 +872,7 @@ docs = [ [package.metadata] requires-dist = [ { name = "jsonschema", specifier = ">=4.21,<5" }, - { name = "modpoll-wot", specifier = "==0.3.0a3" }, + { name = "modpoll-wot", specifier = "==0.4.0a1" }, { name = "pymodbus", specifier = "~=3.16.1" }, { name = "pyyaml", specifier = ">=6,<7" }, ]