sme-modbus-sim 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. sme_modbus_sim/__init__.py +3 -0
  2. sme_modbus_sim/__main__.py +298 -0
  3. sme_modbus_sim/behaviors.py +21 -0
  4. sme_modbus_sim/config.py +425 -0
  5. sme_modbus_sim/data/sunspec/LICENSE +201 -0
  6. sme_modbus_sim/data/sunspec/README.md +13 -0
  7. sme_modbus_sim/data/sunspec/model_1.json +110 -0
  8. sme_modbus_sim/data/sunspec/model_103.json +477 -0
  9. sme_modbus_sim/data/sunspec/model_113.json +388 -0
  10. sme_modbus_sim/data/sunspec/model_120.json +275 -0
  11. sme_modbus_sim/data/sunspec/model_121.json +339 -0
  12. sme_modbus_sim/data/sunspec/model_122.json +356 -0
  13. sme_modbus_sim/data/sunspec/model_123.json +307 -0
  14. sme_modbus_sim/data/sunspec/model_160.json +380 -0
  15. sme_modbus_sim/data/sunspec/model_203.json +748 -0
  16. sme_modbus_sim/data/sunspec/model_213.json +624 -0
  17. sme_modbus_sim/data/sunspec/model_701.json +1021 -0
  18. sme_modbus_sim/data/sunspec/model_702.json +742 -0
  19. sme_modbus_sim/data/sunspec/model_703.json +175 -0
  20. sme_modbus_sim/data/sunspec/model_704.json +899 -0
  21. sme_modbus_sim/data/sunspec/model_705.json +425 -0
  22. sme_modbus_sim/data/sunspec/model_802.json +799 -0
  23. sme_modbus_sim/data/sunspec/model_803.json +801 -0
  24. sme_modbus_sim/engine.py +642 -0
  25. sme_modbus_sim/faults.py +373 -0
  26. sme_modbus_sim/protocol/__init__.py +34 -0
  27. sme_modbus_sim/protocol/client.py +413 -0
  28. sme_modbus_sim/protocol/constants.py +73 -0
  29. sme_modbus_sim/protocol/datatypes.py +180 -0
  30. sme_modbus_sim/protocol/diagnostics.py +241 -0
  31. sme_modbus_sim/protocol/errors.py +17 -0
  32. sme_modbus_sim/protocol/framer.py +275 -0
  33. sme_modbus_sim/protocol/pdu.py +265 -0
  34. sme_modbus_sim/protocol/pty_port.py +95 -0
  35. sme_modbus_sim/protocol/serial_server.py +391 -0
  36. sme_modbus_sim/protocol/server.py +460 -0
  37. sme_modbus_sim/protocol/store.py +141 -0
  38. sme_modbus_sim/protocol/tls.py +177 -0
  39. sme_modbus_sim/scan.py +843 -0
  40. sme_modbus_sim/static/app.js +1500 -0
  41. sme_modbus_sim/static/favicon.svg +6 -0
  42. sme_modbus_sim/static/i18n/en.js +300 -0
  43. sme_modbus_sim/static/i18n/ja.js +298 -0
  44. sme_modbus_sim/static/i18n/zh.js +298 -0
  45. sme_modbus_sim/static/index.html +319 -0
  46. sme_modbus_sim/static/style.css +250 -0
  47. sme_modbus_sim/sunspec.py +206 -0
  48. sme_modbus_sim/templates.py +635 -0
  49. sme_modbus_sim/web.py +429 -0
  50. sme_modbus_sim/xlsx.py +288 -0
  51. sme_modbus_sim-0.3.1.dist-info/METADATA +205 -0
  52. sme_modbus_sim-0.3.1.dist-info/RECORD +56 -0
  53. sme_modbus_sim-0.3.1.dist-info/WHEEL +5 -0
  54. sme_modbus_sim-0.3.1.dist-info/entry_points.txt +2 -0
  55. sme_modbus_sim-0.3.1.dist-info/licenses/LICENSE +21 -0
  56. sme_modbus_sim-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3 @@
1
+ """SME ModbusSim: a Modbus device simulator with a web UI."""
2
+
3
+ __version__ = "0.3.1"
@@ -0,0 +1,298 @@
1
+ """Command line entry point.
2
+
3
+ sme-modbus-sim [run] [-c CONFIG] [--host 127.0.0.1] [--http-port 8081] [--no-browser]
4
+ sme-modbus-sim validate [-c] CONFIG (exit 0 = valid, 2 = config error)
5
+ sme-modbus-sim templates [--templates-dir DIR]
6
+ sme-modbus-sim scan (--host H [--port 502] [--transport tcp|rtu_over_tcp|udp|tls] | --serial COM5 [--baudrate ...])
7
+ --unit 1 --range holding:0-99 [--range ...] [-o template.yaml] [-y]
8
+ sme-modbus-sim record (target as for scan) --unit 1 (--template FILE_OR_NAME | -c CONFIG --device NAME)
9
+ [--period 1] [--duration 60] [-o out.csv] [-y]
10
+ scan / record are read-only (FC 01/02/03/04 and 2B/0E) and ask for confirmation unless -y is given.
11
+
12
+ User-local templates are read from --templates-dir, $SME_MODBUS_SIM_TEMPLATES or ~/.sme-modbus-sim/templates.
13
+ sme-modbus-sim --version
14
+
15
+ The common options (-c, --host, --http-port, --no-browser, --templates-dir, -v, --version), the web server start
16
+ and ``validate`` come from ``sme_sim_common.cli``; default-config resolution follows sme-bac-sim
17
+ ``sme_bacnet_sim/__main__.py`` @ ebd27ec.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import logging
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ from sme_sim_common.cli import add_common_args, run_validate, run_web
28
+
29
+ from . import __version__
30
+
31
+ APP_NAME = "sme-modbus-sim"
32
+ DEFAULT_HTTP_PORT = 8081 # series port table (sme-sim-common README)
33
+ DEFAULT_CONFIG = Path(__file__).resolve().parent.parent / "configs" / "demo-site.yaml"
34
+
35
+
36
+ def _progress(text: str) -> None:
37
+ """One progress line on stderr: rewritten in place on a terminal, one line each when redirected."""
38
+ if sys.stderr.isatty():
39
+ print("\r" + text, end="", file=sys.stderr, flush=True)
40
+ else:
41
+ print(text, file=sys.stderr, flush=True)
42
+
43
+
44
+ def _load_templates(directory) -> None:
45
+ from .templates import load_user_templates
46
+
47
+ for e in load_user_templates(directory):
48
+ print(f"user template {e['path']}: skipped: {e['error']}", file=sys.stderr)
49
+
50
+
51
+ def _validate(argv) -> int:
52
+ from .config import load_file
53
+ from .engine import Engine
54
+
55
+ return run_validate(argv, prog=APP_NAME, load=load_file,
56
+ before=lambda args: _load_templates(args.templates_dir),
57
+ build=lambda cfg, path: Engine(cfg, path.resolve().parent), # behaviors / initial values
58
+ summary=lambda cfg: f"{len(cfg.listeners)} listeners, {len(cfg.devices)} devices")
59
+
60
+
61
+ def _templates(argv) -> int:
62
+ from .templates import ENV_TEMPLATES_DIR, template_catalog
63
+
64
+ ap = argparse.ArgumentParser(prog=f"{APP_NAME} templates", description="list device templates")
65
+ ap.add_argument("--templates-dir", help=f"user template directory "
66
+ f"(default: ${ENV_TEMPLATES_DIR} or ~/.{APP_NAME}/templates)")
67
+ _load_templates(ap.parse_args(argv).templates_dir)
68
+ for t in template_catalog():
69
+ params = ", ".join(f"{k}={v!r}" for k, v in t["params"].items())
70
+ src = f" [user: {t['path']}]" if t["source"] == "user" else ""
71
+ print(f"{t['name']:<14} {t['title']}{src}" + (f"\n{'':<14} params: {params}" if params else ""))
72
+ return 0
73
+
74
+
75
+ def _target_args(ap: argparse.ArgumentParser) -> None:
76
+ g = ap.add_argument_group("target (read-only: FC 01/02/03/04 and 2B/0E only)")
77
+ g.add_argument("--host", help="TCP host of the device or gateway")
78
+ g.add_argument("--port", type=int, help="TCP / UDP port (default 502, tls 802)")
79
+ g.add_argument("--transport", choices=("tcp", "rtu_over_tcp", "udp", "tls"), default="tcp", help="network framing")
80
+ g.add_argument("--ca", help="tls: CA certificate (PEM) to verify the server; without it the server is not verified")
81
+ g.add_argument("--cert", help="tls: client certificate (PEM)")
82
+ g.add_argument("--key", help="tls: client private key (PEM)")
83
+ g.add_argument("--serial", metavar="DEVICE", help="serial device or pyserial URL (RTU), e.g. COM5")
84
+ g.add_argument("--baudrate", type=int, default=19200)
85
+ g.add_argument("--parity", choices=("E", "N", "O"), default="E")
86
+ g.add_argument("--stopbits", type=int, choices=(1, 2))
87
+ g.add_argument("--unit", type=int, default=1, help="unit id (default 1)")
88
+ g.add_argument("--rate", type=float, default=10.0, help="max requests per second (default 10)")
89
+ g.add_argument("--timeout", type=float, default=1.0, help="per-request timeout in seconds (default 1)")
90
+ g.add_argument("-y", "--yes", action="store_true", help="do not ask for confirmation")
91
+
92
+
93
+ def _target(args) -> dict:
94
+ if bool(args.host) == bool(args.serial):
95
+ raise ValueError("give either --host (TCP) or --serial (RTU)")
96
+ if args.serial:
97
+ return {"type": "rtu", "port": args.serial, "baudrate": args.baudrate, "parity": args.parity,
98
+ "stopbits": args.stopbits}
99
+ t = {"type": args.transport, "host": args.host, "port": args.port}
100
+ for k, v in (("ca", args.ca), ("certificate", args.cert), ("private_key", args.key)):
101
+ if v:
102
+ t[k] = v
103
+ return t
104
+
105
+
106
+ def _confirm(plan: dict, yes: bool, extra: list) -> int:
107
+ """Print the plan; returns 0 to go on, otherwise the exit code."""
108
+ lines = [f"{plan['kind']}: {plan['target']} unit {plan['unit']}", *extra,
109
+ f"estimated requests: {plan['requests']}, duration: ~{plan['duration_s']} s "
110
+ f"at <= {plan['rate']:g} requests/s", plan["read_only"]]
111
+ print("\n".join(lines), file=sys.stderr)
112
+ if yes:
113
+ return 0
114
+ if sys.stdin is None or not sys.stdin.isatty():
115
+ print("aborted: confirmation needed but stdin is not interactive (use -y / --yes)", file=sys.stderr)
116
+ return 2
117
+ try:
118
+ answer = input("Proceed? [y/N] ")
119
+ except EOFError:
120
+ answer = ""
121
+ if answer.strip().lower() not in ("y", "yes"):
122
+ print("aborted", file=sys.stderr)
123
+ return 1
124
+ return 0
125
+
126
+
127
+ def _scan(argv) -> int:
128
+ import asyncio
129
+
130
+ from . import scan as sc
131
+
132
+ ap = argparse.ArgumentParser(prog=f"{APP_NAME} scan",
133
+ description="read-only scan of a real device into a user template (YAML)")
134
+ _target_args(ap)
135
+ ap.add_argument("--range", action="append", required=True, metavar="TABLE:START-END",
136
+ help="address range to scan (repeatable), e.g. holding:0-99, coil:0-15")
137
+ ap.add_argument("--samples", type=int, default=3, help="reads per address for type guessing (default 3)")
138
+ ap.add_argument("--sample-interval", type=float, default=1.0, help="seconds between samples (default 1)")
139
+ ap.add_argument("--name", default="scanned", help="template name (default scanned)")
140
+ ap.add_argument("-o", "--output", help="output YAML (default: <name>.yaml)")
141
+ args = ap.parse_args(argv)
142
+ try:
143
+ ranges = sc.parse_ranges(args.range)
144
+ client = sc.make_client(_target(args), timeout=args.timeout, rate=args.rate)
145
+ plan = sc.scan_plan(client.endpoint, sc.check_unit(args.unit), ranges, args.rate, args.samples,
146
+ args.sample_interval, timeout=args.timeout)
147
+ except ValueError as e:
148
+ print(f"error: {e}", file=sys.stderr)
149
+ return 2
150
+ rc = _confirm(plan, args.yes, ["ranges: " + ", ".join(f"{r.table}:{r.start}-{r.start + r.count - 1}"
151
+ for r in ranges)])
152
+ if rc:
153
+ return rc
154
+
155
+ def progress(p):
156
+ _progress(f"{p['phase']}: {p['requests']}/{p['estimate']} requests, {p['found']} readable")
157
+
158
+ async def run():
159
+ async with client:
160
+ return await sc.scan(client, args.unit, ranges, samples=args.samples,
161
+ sample_interval=args.sample_interval, progress=progress)
162
+
163
+ try:
164
+ result = asyncio.run(run())
165
+ doc = sc.to_template(result, name=args.name)
166
+ except Exception as e: # noqa: BLE001
167
+ print(f"\nscan failed: {e}", file=sys.stderr)
168
+ return 1
169
+ out = Path(args.output or f"{args.name}.yaml")
170
+ out.write_text(sc.template_yaml(doc, result), encoding="utf-8")
171
+ print(f"\n{len(result['readable'])} readable addresses, {len(doc['points'])} points -> {out}", file=sys.stderr)
172
+ return 0
173
+
174
+
175
+ def _record_points(args):
176
+ from .config import DeviceConfig, load_file
177
+ from .templates import expand_device, load_user_templates
178
+
179
+ if bool(args.template) == bool(args.device):
180
+ raise ValueError("give either --template FILE_OR_NAME or -c CONFIG --device NAME")
181
+ if args.device:
182
+ if not args.config:
183
+ raise ValueError("--device needs -c CONFIG")
184
+ _load_templates(args.templates_dir)
185
+ dev = next((d for d in load_file(args.config).devices if d.name == args.device), None)
186
+ if dev is None:
187
+ raise ValueError(f"device {args.device!r} not found in {args.config}")
188
+ else:
189
+ path = Path(args.template)
190
+ if path.suffix.lower() in (".yaml", ".yml") and path.is_file():
191
+ import yaml
192
+
193
+ errs = load_user_templates(path.parent)
194
+ mine = [e for e in errs if Path(e["path"]).resolve() == path.resolve()]
195
+ if mine:
196
+ raise ValueError(f"{path}: {mine[0]['error']}")
197
+ name = (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).get("name") or path.stem
198
+ else:
199
+ _load_templates(args.templates_dir)
200
+ name = args.template
201
+ dev = DeviceConfig(name="record", unit_id=1, template=str(name))
202
+ return expand_device(dev), dev.byte_order, dev.word_order
203
+
204
+
205
+ def _record(argv) -> int:
206
+ import asyncio
207
+
208
+ from . import scan as sc
209
+
210
+ ap = argparse.ArgumentParser(prog=f"{APP_NAME} record",
211
+ description="read-only polling of a real device into a replay CSV")
212
+ _target_args(ap)
213
+ ap.add_argument("--template", help="template YAML file (e.g. from scan) or template name")
214
+ ap.add_argument("-c", "--config", help="config file holding --device")
215
+ ap.add_argument("--device", help="device of --config whose points are recorded")
216
+ ap.add_argument("--templates-dir", help="user template directory")
217
+ ap.add_argument("--period", type=float, default=1.0, help="seconds between polls (default 1)")
218
+ ap.add_argument("--duration", type=float, default=60.0, help="seconds to record (default 60)")
219
+ ap.add_argument("-o", "--output", default="record.csv", help="output CSV (default record.csv)")
220
+ args = ap.parse_args(argv)
221
+ try:
222
+ points, bo, wo = _record_points(args)
223
+ points = sc.record_points(points)
224
+ client = sc.make_client(_target(args), timeout=args.timeout, rate=args.rate)
225
+ plan = sc.record_plan(client.endpoint, sc.check_unit(args.unit), points, args.period, args.duration,
226
+ args.rate)
227
+ except ValueError as e:
228
+ print(f"error: {e}", file=sys.stderr)
229
+ return 2
230
+ rc = _confirm(plan, args.yes, [f"points: {len(points)}, every {args.period:g} s for {args.duration:g} s "
231
+ f"-> {args.output}"])
232
+ if rc:
233
+ return rc
234
+
235
+ def progress(p):
236
+ _progress(f"row {p['rows']}/{p['cycles']}, failed reads {p['failed']}")
237
+
238
+ async def run():
239
+ async with client:
240
+ return await sc.record(client, args.unit, points, args.period, args.duration, Path(args.output),
241
+ byte_order=bo, word_order=wo, progress=progress)
242
+
243
+ try:
244
+ res = asyncio.run(run())
245
+ except Exception as e: # noqa: BLE001
246
+ print(f"\nrecord failed: {e}", file=sys.stderr)
247
+ return 1
248
+ print(f"\n{res['rows']} rows -> {res['path']}", file=sys.stderr)
249
+ for w in res["warnings"]:
250
+ print(f"warning: {w}", file=sys.stderr)
251
+ return 0
252
+
253
+
254
+ def main(argv=None) -> int:
255
+ rest = sys.argv[1:] if argv is None else list(argv)
256
+ if rest[:1] == ["scan"]:
257
+ return _scan(rest[1:])
258
+ if rest[:1] == ["record"]:
259
+ return _record(rest[1:])
260
+ if rest[:1] == ["validate"]:
261
+ return _validate(rest[1:])
262
+ if rest[:1] == ["templates"]:
263
+ return _templates(rest[1:])
264
+ if rest[:1] == ["run"]:
265
+ rest = rest[1:]
266
+ ap = argparse.ArgumentParser(prog=APP_NAME,
267
+ description="Modbus TCP / RTU over TCP device simulator with a web UI "
268
+ "(subcommands: run, validate [-c] CONFIG, templates, scan, record); "
269
+ "default config: the bundled configs/demo-site.yaml")
270
+ add_common_args(ap, default_http_port=DEFAULT_HTTP_PORT, app_name=APP_NAME, version=__version__)
271
+ args = ap.parse_args(rest)
272
+
273
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG if args.verbose else logging.INFO,
274
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
275
+
276
+ from .config import SimConfig, load_file
277
+ from .engine import Engine
278
+
279
+ _load_templates(args.templates_dir) # before the config: devices may use user templates
280
+ path = args.config
281
+ if path is None and DEFAULT_CONFIG.exists():
282
+ path = str(DEFAULT_CONFIG)
283
+ try:
284
+ cfg = load_file(path) if path else SimConfig()
285
+ text = Path(path).read_text(encoding="utf-8") if path else None
286
+ engine = Engine(cfg, Path(path).resolve().parent if path else None, config_text=text, config_path=path)
287
+ except Exception as e:
288
+ print(f"config error: {e}", file=sys.stderr)
289
+ return 2
290
+
291
+ from .web import create_app
292
+
293
+ run_web(create_app(engine, path), args, name=f"SME ModbusSim v{__version__}")
294
+ return 0
295
+
296
+
297
+ if __name__ == "__main__":
298
+ sys.exit(main())
@@ -0,0 +1,21 @@
1
+ """Value simulation behaviors and the restricted expression evaluator.
2
+
3
+ Re-exported from ``sme_sim_common.behaviors`` (taken from this module @ 085fe59: ``discrete`` / ``coerce``
4
+ replay hooks, ``ramp`` kind, ``reserved_names`` / ``check_point_names``). Kept so that existing imports
5
+ ``sme_modbus_sim.behaviors`` keep working; new code should import from ``sme_sim_common.behaviors``.
6
+ """
7
+
8
+ from sme_sim_common.behaviors import * # noqa: F401,F403
9
+ from sme_sim_common.behaviors import ( # noqa: F401 (explicit names used across the product)
10
+ BEHAVIORS,
11
+ ENGINE_NAMES,
12
+ FUNCTIONS,
13
+ Behavior,
14
+ ExpressionError,
15
+ check_point_names,
16
+ compile_expr,
17
+ ident,
18
+ load_table,
19
+ make_behavior,
20
+ reserved_names,
21
+ )