s7-sim 0.1.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.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: s7-sim
3
+ Version: 0.1.1
4
+ Summary: A simulated Siemens S7 line you can run in a container
5
+ Author: George Vasiliades
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Poseidonas/s7-sim
8
+ Project-URL: Repository, https://github.com/Poseidonas/s7-sim
9
+ Project-URL: Issues, https://github.com/Poseidonas/s7-sim/issues
10
+ Keywords: siemens,s7,plc,snap7,simulator,industrial,testing
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Manufacturing
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Classifier: Topic :: System :: Emulators
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: python-snap7>=3.1
21
+ Requires-Dist: PyYAML>=6.0
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=8.0; extra == "test"
24
+ Requires-Dist: ruff>=0.4; extra == "test"
25
+ Dynamic: license-file
26
+
27
+ # s7-sim
28
+
29
+ A Siemens S7 line you can run in a container.
30
+
31
+ It answers the S7 protocol like a controller does, and the values it serves
32
+ move the way a line moves: counters advance while it runs and freeze when it
33
+ stops, a temperature climbs and falls back, and the whole thing stops at random
34
+ intervals and starts again.
35
+
36
+ ```console
37
+ $ docker run -p 10102:1102 ghcr.io/poseidonas/s7-sim
38
+ ```
39
+
40
+ Point anything that speaks S7 at it — `python-snap7`, a gateway, your own code —
41
+ and develop against a plant that behaves like one, without hardware, a licence
42
+ or a Siemens account.
43
+
44
+ ## The whole stack, in one command
45
+
46
+ ```console
47
+ git clone https://github.com/Poseidonas/s7-sim && cd s7-sim
48
+ docker compose up
49
+ ```
50
+
51
+ That brings up four things wired together: the simulated line, an
52
+ [s7-gateway](https://github.com/Poseidonas/s7-gateway) reading it over S7,
53
+ Prometheus scraping the gateway, and Grafana with a dashboard already loaded.
54
+
55
+ | | |
56
+ | --- | --- |
57
+ | http://localhost:3000 | Grafana, no login. Line state, filler temperature, bottles per minute, current stop |
58
+ | http://localhost:8088/docs | the gateway's API |
59
+ | http://localhost:9090 | Prometheus |
60
+ | `localhost:10102` | the line itself, over S7 |
61
+
62
+ Everything is provisioned, so the dashboard has data in it the moment it opens.
63
+
64
+ ## What it is not
65
+
66
+ **It is not a PLC.** It speaks the protocol and serves plausible values; it runs
67
+ no user program, has no cycle, no I/O, no diagnostics buffer and no safety.
68
+
69
+ Where it is known to differ from a controller, and this matters if you are using
70
+ it to test error handling:
71
+
72
+ - **A read from a data block that does not exist returns fabricated bytes**
73
+ instead of an error. This is `snap7.server` underneath, reported upstream at
74
+ [python-snap7#578](https://github.com/gijzelaerr/python-snap7/discussions/578).
75
+ A real CPU answers with an address error. If you are testing what your code
76
+ does with a wrong address, this is the one thing you cannot test here.
77
+ - **A read past the end of a block is padded with zeros** rather than refused.
78
+ - **A normal client disconnect is logged as an error** by the server.
79
+ - There is no PUT/GET permission and no optimized block access, so neither of
80
+ the two settings that gate a real S7-1200 or S7-1500 applies. Code that works
81
+ here can still be refused by a real CPU for that reason alone.
82
+
83
+ Use it to build and to demonstrate. Confirm against hardware before you trust it.
84
+
85
+ ## Describing a plant
86
+
87
+ Everything is one YAML file. Each tag names its own address, exactly as a
88
+ standard-access data block lays them out, and says what it does.
89
+
90
+ ```yaml
91
+ line:
92
+ mean_run_minutes: 12 # average time between stops
93
+ mean_stop_minutes: 3 # average length of a stop
94
+ seed: 1 # the same seed gives the same day, every time
95
+
96
+ blocks:
97
+ 10:
98
+ tags:
99
+ running:
100
+ offset: 0
101
+ bit: 0
102
+ type: bool
103
+ behaviour: running
104
+
105
+ filler_temp:
106
+ offset: 6
107
+ type: real
108
+ behaviour: temperature
109
+ running: 74.0 # settles here while producing
110
+ idle: 21.5 # and falls back to here when stopped
111
+ tau: 180 # seconds to cover 63% of the gap
112
+ noise: 0.3
113
+
114
+ bottles_filled:
115
+ offset: 10
116
+ type: dint
117
+ behaviour: counter
118
+ per_minute: 420
119
+
120
+ line_speed:
121
+ offset: 18
122
+ type: int
123
+ behaviour: setpoint # written once, then left to the client
124
+ value: 420
125
+ ```
126
+
127
+ Check it before starting anything. This reads the file only:
128
+
129
+ ```console
130
+ $ s7-sim --config examples/line.yml --check
131
+ line: runs 12 min on average, stops for 3 min, seed 1
132
+ DB10 24 bytes
133
+ running bool DB10.DBX0.0 r- running
134
+ stopped_for real DB10.DBX2 r- stoppedfor
135
+ filler_temp real DB10.DBX6 r- temperature
136
+ bottles_filled dint DB10.DBX10 r- counter
137
+ bottles_rejected dint DB10.DBX14 r- counter
138
+ line_speed int DB10.DBX18 rw setpoint
139
+ target_temp real DB10.DBX20 rw setpoint
140
+ ```
141
+
142
+ ### Behaviours
143
+
144
+ | | |
145
+ | --- | --- |
146
+ | `running` | true while the line produces |
147
+ | `counter` | advances at `per_minute` **only while running**, so a stop shows as a flat line. `fraction` counts a share of the same production, which is how a reject counter is written |
148
+ | `temperature` | approaches `running` while producing and `idle` while stopped, as a first-order lag with time constant `tau`, plus optional `noise` |
149
+ | `stopped_for` | seconds the current stop has lasted, zero while running |
150
+ | `setpoint` | written once at startup and never again, so a client can write it and have it stay written |
151
+
152
+ Types: `bool` `byte` `sint` `usint` `int` `uint` `word` `dint` `udint` `dword`
153
+ `real` `lreal`.
154
+
155
+ Two tags may share a byte only as different bits. Anything else that overlaps is
156
+ refused when the file is read, because both would write the same bytes every
157
+ tick and the last one would win.
158
+
159
+ ## Reproducibility
160
+
161
+ The line is a function of elapsed time rather than a loop that mutates state.
162
+ The same seed produces the same stops, at the same seconds, on every run and on
163
+ every machine. That is what makes it useful for a test rather than only a demo:
164
+ a stop you cannot reproduce cannot be asserted on.
165
+
166
+ ```python
167
+ from s7sim import Simulator, loads
168
+
169
+ sim = Simulator(loads(open("line.yml").read()))
170
+ sim._register()
171
+ sim.refresh(1800.0) # the plant half an hour in
172
+ print(sim.buffer(10).hex()) # always the same bytes
173
+ ```
174
+
175
+ ## Running it without Docker
176
+
177
+ ```console
178
+ pip install s7-sim
179
+ s7-sim --config examples/line.yml --port 1102
180
+ ```
181
+
182
+ Python 3.11+. `python-snap7` 3.1+ speaks S7 in Python over a plain socket, so
183
+ there is nothing to compile.
184
+
185
+ ### About port 102
186
+
187
+ S7 clients expect port 102, which is privileged. The container runs as a
188
+ non-root user and listens on 1102, so publish it where you need it:
189
+
190
+ ```console
191
+ docker run -p 102:1102 ghcr.io/poseidonas/s7-sim # the real port, needs a privileged bind
192
+ docker run -p 10102:1102 ghcr.io/poseidonas/s7-sim # anywhere else
193
+ ```
194
+
195
+ ## Development
196
+
197
+ ```console
198
+ pip install -e ".[test]"
199
+ pytest
200
+ ```
201
+
202
+ The tests drive a real `snap7` client against the simulator over the actual
203
+ protocol. Nothing about snap7 is mocked.
204
+
205
+ ## Licence
206
+
207
+ MIT
@@ -0,0 +1,12 @@
1
+ s7_sim-0.1.1.dist-info/licenses/LICENSE,sha256=l71-j7ZXnaK1BnAog3cV4gsfdqU2RT12fUp9ed98fu4,1074
2
+ s7sim/__init__.py,sha256=XBn9Nri50cenp5I5K6vf_9I3UUfj0Khrg92PrRWNE1k,268
3
+ s7sim/cli.py,sha256=jNBXYK0uY3FyBh4vU1sjgV9KmLqpyav7Kvm5gak1LjY,4067
4
+ s7sim/config.py,sha256=Kxgvdx5lKVB9S7mYQm2oVCc5B6OXhD0FwM1BOSFPNEA,6628
5
+ s7sim/line.py,sha256=BBjqEJbWlYj1X0Pe2x7YoHLWLIRkb8U7aO-ocqG0UjE,2925
6
+ s7sim/server.py,sha256=_kAP4x-S-Vaa4e7VJQLgDCNTdx5Je1v1OBooSlun3lI,3371
7
+ s7sim/tags.py,sha256=6cUqqQQuF-z6X-Vwl4-wUXA9w-AX_oAiIfNy1Fp9rQo,3625
8
+ s7_sim-0.1.1.dist-info/METADATA,sha256=g4tJFEW4QVILxd4IeNM5HKMFSMA8SKqnDvenxCWsmb0,7238
9
+ s7_sim-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ s7_sim-0.1.1.dist-info/entry_points.txt,sha256=LJQjVRmR_56sXLDyEyFw4AQqOdSofS_Ahf-x61iMbbc,42
11
+ s7_sim-0.1.1.dist-info/top_level.txt,sha256=hVmgeUiZsG2dXhMCwMFu0DiYGpalaqXAmpb-d9A94XQ,6
12
+ s7_sim-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ s7-sim = s7sim.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 George Vasiliades
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ s7sim
s7sim/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """A Siemens S7 line you can run in a container."""
2
+
3
+ from .config import Block, Plant, Tag, load, loads
4
+ from .line import Line, Stop
5
+ from .server import Simulator
6
+
7
+ __all__ = ["Block", "Line", "Plant", "Simulator", "Stop", "Tag", "load", "loads"]
8
+ __version__ = "0.1.1"
s7sim/cli.py ADDED
@@ -0,0 +1,113 @@
1
+ """Starting the simulator from a terminal or a container."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import logging
6
+ import signal
7
+ import sys
8
+ import threading
9
+
10
+ from . import __version__
11
+ from . import config as config_module
12
+ from .server import Simulator
13
+
14
+
15
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
16
+ parser = argparse.ArgumentParser(
17
+ prog="s7-sim",
18
+ description="Serve a simulated Siemens S7 line over the S7 protocol.")
19
+ parser.add_argument("-c", "--config", required=True,
20
+ help="path to the plant description")
21
+ parser.add_argument("--host", default="0.0.0.0",
22
+ help="address to listen on (default: %(default)s)")
23
+ parser.add_argument("--port", type=int,
24
+ help="port to listen on (default: the one in the file, or 102)")
25
+ parser.add_argument("--log-level", default="info",
26
+ choices=["debug", "info", "warning", "error"])
27
+ parser.add_argument("--check", action="store_true",
28
+ help="read the plant, print its layout and exit")
29
+ parser.add_argument("--health", action="store_true",
30
+ help="connect as an S7 client and exit 0 if the CPU answers")
31
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
32
+ return parser.parse_args(argv)
33
+
34
+
35
+ def _print_layout(plant) -> None:
36
+ line = plant.line
37
+ print(f"line: runs {line.mean_run_seconds / 60:g} min on average, "
38
+ f"stops for {line.mean_stop_seconds / 60:g} min, seed {line.seed}")
39
+ for block in sorted(plant.blocks.values(), key=lambda b: b.number):
40
+ print(f"DB{block.number} {block.size} bytes")
41
+ for tag in sorted(block.tags.values(), key=lambda t: (t.offset, t.bit)):
42
+ where = f"DB{block.number}.DBX{tag.offset}"
43
+ if tag.type == "bool":
44
+ where += f".{tag.bit}"
45
+ access = "rw" if tag.behaviour.writable else "r-"
46
+ print(f" {tag.name:20} {tag.type:6} {where:18} {access} "
47
+ f"{type(tag.behaviour).__name__.lower()}")
48
+
49
+
50
+ def _health(plant, port: int | None) -> int:
51
+ """Speak the protocol rather than opening a bare socket.
52
+
53
+ A TCP connection with no S7 handshake is logged by the server as a failed
54
+ ISO connection, so a bare socket check makes a healthy container look like
55
+ it is being probed by something broken.
56
+ """
57
+ import snap7
58
+
59
+ block = min(plant.blocks)
60
+ client = snap7.client.Client()
61
+ try:
62
+ client.connect("127.0.0.1", plant.rack, plant.slot, port or plant.port)
63
+ # Read a real block rather than asking for the CPU state: the state
64
+ # request makes the server parse an address it was not given, which it
65
+ # resolves to a block that does not exist and logs as a failure.
66
+ client.db_read(block, 0, 1)
67
+ except Exception as error: # noqa: BLE001 - any failure means unhealthy
68
+ print(f"s7-sim: {error}", file=sys.stderr)
69
+ return 1
70
+ finally:
71
+ try:
72
+ client.disconnect()
73
+ except Exception: # noqa: BLE001
74
+ pass
75
+ return 0
76
+
77
+
78
+ def main(argv: list[str] | None = None) -> int:
79
+ args = parse_args(argv)
80
+ logging.basicConfig(level=args.log_level.upper(),
81
+ format="%(asctime)s %(levelname)-8s %(name)s: %(message)s")
82
+ try:
83
+ plant = config_module.load(args.config)
84
+ except (OSError, ValueError) as error:
85
+ print(f"s7-sim: {error}", file=sys.stderr)
86
+ return 2
87
+
88
+ if args.check:
89
+ _print_layout(plant)
90
+ return 0
91
+
92
+ if args.health:
93
+ return _health(plant, args.port)
94
+
95
+ simulator = Simulator(plant, host=args.host, port=args.port)
96
+ stop = threading.Event()
97
+
98
+ def shutdown(*_: object) -> None:
99
+ stop.set()
100
+
101
+ signal.signal(signal.SIGINT, shutdown)
102
+ signal.signal(signal.SIGTERM, shutdown)
103
+
104
+ simulator.start()
105
+ try:
106
+ stop.wait()
107
+ finally:
108
+ simulator.stop()
109
+ return 0
110
+
111
+
112
+ if __name__ == "__main__":
113
+ raise SystemExit(main())
s7sim/config.py ADDED
@@ -0,0 +1,194 @@
1
+ """Reading the simulated plant from a YAML file.
2
+
3
+ The tag shape is deliberately the one s7-gateway uses, so a layout written here
4
+ can be pointed at by a gateway configuration without translating anything.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import yaml
13
+ from snap7 import util
14
+
15
+ from .line import Line
16
+ from .tags import BEHAVIOURS, Behaviour
17
+
18
+ #: name -> (width in bytes, writer)
19
+ TYPES: dict[str, tuple[int, Any]] = {
20
+ "bool": (1, None), # written through set_bool, which needs the bit
21
+ "byte": (1, util.set_byte),
22
+ "sint": (1, util.set_sint),
23
+ "usint": (1, util.set_usint),
24
+ "int": (2, util.set_int),
25
+ "uint": (2, util.set_uint),
26
+ "word": (2, util.set_word),
27
+ "dint": (4, util.set_dint),
28
+ "udint": (4, util.set_udint),
29
+ "dword": (4, util.set_dword),
30
+ "real": (4, util.set_real),
31
+ "lreal": (8, util.set_lreal),
32
+ }
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Tag:
37
+ name: str
38
+ offset: int
39
+ type: str
40
+ behaviour: Behaviour
41
+ bit: int = 0
42
+
43
+ @property
44
+ def size(self) -> int:
45
+ return TYPES[self.type][0]
46
+
47
+ @property
48
+ def end(self) -> int:
49
+ return self.offset + self.size
50
+
51
+ def write(self, buffer: bytearray, line: Line, t: float) -> None:
52
+ value = self.behaviour.value(line, t)
53
+ if self.type == "bool":
54
+ util.set_bool(buffer, self.offset, self.bit, bool(value))
55
+ else:
56
+ TYPES[self.type][1](buffer, self.offset, value)
57
+
58
+ def address(self) -> str:
59
+ where = f"DB?.DBX{self.offset}"
60
+ return f"{where}.{self.bit}" if self.type == "bool" else where
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Block:
65
+ number: int
66
+ size: int
67
+ tags: dict[str, Tag]
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Plant:
72
+ line: Line
73
+ blocks: dict[int, Block]
74
+ rack: int = 0
75
+ slot: int = 1
76
+ port: int = 102
77
+ tick: float = 0.5
78
+
79
+ def writable_tags(self) -> list[Tag]:
80
+ return [t for b in self.blocks.values() for t in b.tags.values()
81
+ if t.behaviour.writable]
82
+
83
+
84
+ def _behaviour(tag_name: str, body: dict[str, Any]) -> Behaviour:
85
+ kind = body.get("behaviour")
86
+ if kind is None:
87
+ raise ValueError(f"tag '{tag_name}' does not say what it does: add a 'behaviour'")
88
+ if kind not in BEHAVIOURS:
89
+ known = ", ".join(sorted(BEHAVIOURS))
90
+ raise ValueError(f"tag '{tag_name}' has unknown behaviour '{kind}'; known are: {known}")
91
+
92
+ cls = BEHAVIOURS[kind]
93
+ args = {k: v for k, v in body.items() if k not in ("offset", "type", "bit", "behaviour")}
94
+ if kind == "setpoint":
95
+ args = {"value_": args.get("value", 0)}
96
+ if kind == "temperature" and "running" in args:
97
+ args["running"] = float(args["running"])
98
+ try:
99
+ return cls(**args)
100
+ except TypeError as error:
101
+ raise ValueError(f"tag '{tag_name}' ({kind}): {error}") from error
102
+
103
+
104
+ def _tag(name: str, body: dict[str, Any]) -> Tag:
105
+ if not isinstance(body, dict):
106
+ raise ValueError(f"tag '{name}' must be a mapping")
107
+ for required in ("offset", "type"):
108
+ if required not in body:
109
+ raise ValueError(f"tag '{name}' is missing: {required}")
110
+ kind = str(body["type"]).lower()
111
+ if kind not in TYPES:
112
+ known = ", ".join(sorted(TYPES))
113
+ raise ValueError(f"tag '{name}' has unknown type '{body['type']}'; known are: {known}")
114
+ bit = int(body.get("bit", 0))
115
+ if kind != "bool" and "bit" in body:
116
+ raise ValueError(f"tag '{name}': a bit may only be given for a bool")
117
+ if not 0 <= bit <= 7:
118
+ raise ValueError(f"tag '{name}': bit must be between 0 and 7")
119
+ if int(body["offset"]) < 0:
120
+ raise ValueError(f"tag '{name}': offset must not be negative")
121
+ return Tag(name=name, offset=int(body["offset"]), type=kind,
122
+ bit=bit, behaviour=_behaviour(name, body))
123
+
124
+
125
+ def _block(number: Any, body: dict[str, Any]) -> Block:
126
+ try:
127
+ number = int(number)
128
+ except (TypeError, ValueError):
129
+ raise ValueError(f"block '{number}' is not a number") from None
130
+ tags_raw = (body or {}).get("tags")
131
+ if not tags_raw:
132
+ raise ValueError(f"block {number} declares no tags")
133
+ tags = {name: _tag(name, tag_body) for name, tag_body in tags_raw.items()}
134
+
135
+ _reject_overlaps(number, tags)
136
+ needed = max(t.end for t in tags.values())
137
+ size = int(body.get("size", needed))
138
+ if size < needed:
139
+ raise ValueError(
140
+ f"block {number} is declared as {size} bytes but its tags reach {needed}")
141
+ return Block(number=number, size=size, tags=tags)
142
+
143
+
144
+ def _reject_overlaps(number: int, tags: dict[str, Tag]) -> None:
145
+ """Two tags sharing bytes would each overwrite the other every tick."""
146
+ claimed: dict[int, tuple[str, int | None]] = {}
147
+ for tag in sorted(tags.values(), key=lambda t: (t.offset, t.bit)):
148
+ for byte in range(tag.offset, tag.end):
149
+ bit = tag.bit if tag.type == "bool" else None
150
+ owner = claimed.get(byte)
151
+ if owner is None:
152
+ claimed[byte] = (tag.name, bit)
153
+ continue
154
+ other_name, other_bit = owner
155
+ if bit is not None and other_bit is not None and bit != other_bit:
156
+ continue # different bits of the same byte are fine
157
+ raise ValueError(
158
+ f"block {number}: tags '{other_name}' and '{tag.name}' both use byte {byte}")
159
+
160
+
161
+ def loads(text: str) -> Plant:
162
+ try:
163
+ raw = yaml.safe_load(text) or {}
164
+ except yaml.YAMLError as error:
165
+ raise ValueError(f"the plant description is not valid YAML: {error}") from error
166
+ if not isinstance(raw, dict):
167
+ raise ValueError("the configuration must be a mapping at the top level")
168
+
169
+ blocks_raw = raw.get("blocks")
170
+ if not blocks_raw:
171
+ raise ValueError("the configuration declares no blocks")
172
+
173
+ line_raw = raw.get("line") or {}
174
+ line = Line(
175
+ mean_run_seconds=float(line_raw.get("mean_run_minutes", 12)) * 60,
176
+ mean_stop_seconds=float(line_raw.get("mean_stop_minutes", 3)) * 60,
177
+ seed=int(line_raw.get("seed", 1)),
178
+ )
179
+ plc = raw.get("plc") or {}
180
+ return Plant(
181
+ line=line,
182
+ blocks={b.number: b for b in (_block(n, body) for n, body in blocks_raw.items())},
183
+ rack=int(plc.get("rack", 0)),
184
+ slot=int(plc.get("slot", 1)),
185
+ port=int(plc.get("port", 102)),
186
+ tick=float(plc.get("tick_seconds", 0.5)),
187
+ )
188
+
189
+
190
+ def load(path: str | Path) -> Plant:
191
+ try:
192
+ return loads(Path(path).read_text(encoding="utf-8"))
193
+ except ValueError as error:
194
+ raise ValueError(f"{path}: {error}") from error
s7sim/line.py ADDED
@@ -0,0 +1,89 @@
1
+ """The behaviour of a production line, as a function of elapsed time.
2
+
3
+ The line is a pure function rather than a loop that mutates state: given the
4
+ seed and a number of seconds, it always reports the same thing. That makes a
5
+ stop reproducible, which is the whole point of simulating one.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import bisect
10
+ import random
11
+ from dataclasses import dataclass, field
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Stop:
16
+ """One stoppage, in seconds from the start of the run."""
17
+
18
+ start: float
19
+ end: float
20
+
21
+ @property
22
+ def duration(self) -> float:
23
+ return self.end - self.start
24
+
25
+
26
+ @dataclass
27
+ class Line:
28
+ """A line that runs, stops and runs again.
29
+
30
+ Run and stop lengths are drawn from an exponential distribution, which is
31
+ what a plant sees when failures are independent of how long the machine has
32
+ been up. The draws come from a seeded generator, so the same seed gives the
33
+ same day.
34
+ """
35
+
36
+ mean_run_seconds: float = 720.0
37
+ mean_stop_seconds: float = 180.0
38
+ seed: int = 1
39
+ #: How far ahead the schedule is generated, in seconds.
40
+ horizon: float = 24 * 3600.0
41
+
42
+ _stops: list[Stop] = field(default_factory=list, repr=False)
43
+ _starts: list[float] = field(default_factory=list, repr=False)
44
+
45
+ def __post_init__(self) -> None:
46
+ if self.mean_run_seconds <= 0:
47
+ raise ValueError("mean_run_seconds must be positive")
48
+ if self.mean_stop_seconds <= 0:
49
+ raise ValueError("mean_stop_seconds must be positive")
50
+ self._build()
51
+
52
+ def _build(self) -> None:
53
+ rng = random.Random(self.seed)
54
+ t = 0.0
55
+ while t < self.horizon:
56
+ t += rng.expovariate(1.0 / self.mean_run_seconds)
57
+ stop_end = t + rng.expovariate(1.0 / self.mean_stop_seconds)
58
+ self._stops.append(Stop(t, stop_end))
59
+ t = stop_end
60
+ self._starts = [s.start for s in self._stops]
61
+
62
+ def running(self, t: float) -> bool:
63
+ """True when the line is producing at elapsed time ``t``."""
64
+ stop = self._stop_at(t)
65
+ return stop is None
66
+
67
+ def _stop_at(self, t: float) -> Stop | None:
68
+ i = bisect.bisect_right(self._starts, t) - 1
69
+ if i < 0:
70
+ return None
71
+ stop = self._stops[i]
72
+ return stop if t < stop.end else None
73
+
74
+ def stopped_for(self, t: float) -> float:
75
+ """Seconds the current stop has lasted, or 0 while running."""
76
+ stop = self._stop_at(t)
77
+ return t - stop.start if stop else 0.0
78
+
79
+ def running_seconds(self, t: float) -> float:
80
+ """Total producing time up to ``t``. This is what a counter follows."""
81
+ total = t
82
+ for stop in self._stops:
83
+ if stop.start >= t:
84
+ break
85
+ total -= min(stop.end, t) - stop.start
86
+ return total
87
+
88
+ def stops_before(self, t: float) -> list[Stop]:
89
+ return [s for s in self._stops if s.start < t]
s7sim/server.py ADDED
@@ -0,0 +1,96 @@
1
+ """Serving the simulated plant over the S7 protocol.
2
+
3
+ Each block is a bytearray registered with the snap7 server. The server keeps a
4
+ reference to it rather than a copy, so refreshing the plant is a matter of
5
+ writing into the same buffer the clients are reading from.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import threading
11
+ import time
12
+
13
+ import snap7
14
+ from snap7.server import Server
15
+
16
+ from .config import Plant
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class Simulator:
22
+ """A running S7 server whose data blocks follow the line."""
23
+
24
+ def __init__(self, plant: Plant, host: str = "0.0.0.0", port: int | None = None) -> None:
25
+ self._plant = plant
26
+ self._host = host
27
+ self._port = port if port is not None else plant.port
28
+ self._server = Server()
29
+ self._buffers: dict[int, bytearray] = {}
30
+ self._thread: threading.Thread | None = None
31
+ self._stop = threading.Event()
32
+ self._started_at = 0.0
33
+
34
+ @property
35
+ def port(self) -> int:
36
+ return self._port
37
+
38
+ def elapsed(self) -> float:
39
+ return time.monotonic() - self._started_at
40
+
41
+ def _register(self) -> None:
42
+ for block in self._plant.blocks.values():
43
+ buffer = bytearray(block.size)
44
+ # Writable tags are placed once. The refresh leaves them alone so a
45
+ # client can write one and have it stay written.
46
+ for tag in block.tags.values():
47
+ if tag.behaviour.writable:
48
+ tag.write(buffer, self._plant.line, 0.0)
49
+ self._buffers[block.number] = buffer
50
+ self._server.register_area(snap7.type.SrvArea.DB, block.number, buffer)
51
+ logger.info("DB%d registered, %d bytes, %d tags",
52
+ block.number, block.size, len(block.tags))
53
+
54
+ def refresh(self, t: float) -> None:
55
+ """Bring every simulated tag up to elapsed time ``t``."""
56
+ for block in self._plant.blocks.values():
57
+ buffer = self._buffers[block.number]
58
+ for tag in block.tags.values():
59
+ if not tag.behaviour.writable:
60
+ tag.write(buffer, self._plant.line, t)
61
+
62
+ def _run(self) -> None:
63
+ while not self._stop.is_set():
64
+ self.refresh(self.elapsed())
65
+ self._stop.wait(self._plant.tick)
66
+
67
+ def start(self) -> None:
68
+ self._register()
69
+ self._started_at = time.monotonic()
70
+ self.refresh(0.0)
71
+ self._server.start_to(self._host, self._port)
72
+ logger.info("listening on %s:%d, rack %d slot %d",
73
+ self._host, self._port, self._plant.rack, self._plant.slot)
74
+ self._thread = threading.Thread(target=self._run, name="s7sim", daemon=True)
75
+ self._thread.start()
76
+
77
+ def stop(self) -> None:
78
+ self._stop.set()
79
+ if self._thread is not None:
80
+ self._thread.join(timeout=5)
81
+ try:
82
+ self._server.stop()
83
+ self._server.destroy()
84
+ except Exception: # noqa: BLE001 - shutdown must not raise
85
+ logger.debug("server already down", exc_info=True)
86
+
87
+ def __enter__(self) -> Simulator:
88
+ self.start()
89
+ return self
90
+
91
+ def __exit__(self, *exc: object) -> None:
92
+ self.stop()
93
+
94
+ def buffer(self, block: int) -> bytearray:
95
+ """The live bytes of one block. Used by the tests."""
96
+ return self._buffers[block]
s7sim/tags.py ADDED
@@ -0,0 +1,127 @@
1
+ """Turning the state of a line into the value a tag holds.
2
+
3
+ Each behaviour is a function of elapsed time, for the same reason the line is:
4
+ a value that cannot be reproduced cannot be used to test anything.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ import random
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ from .line import Line
14
+
15
+
16
+ @dataclass
17
+ class Behaviour:
18
+ """What a tag does. Subclasses answer for one elapsed time."""
19
+
20
+ def value(self, line: Line, t: float) -> Any:
21
+ raise NotImplementedError
22
+
23
+ @property
24
+ def writable(self) -> bool:
25
+ """True when the simulator leaves the tag alone after starting it.
26
+
27
+ A tag the simulator keeps writing cannot be used to test writes: the
28
+ next tick would undo whatever the client sent.
29
+ """
30
+ return False
31
+
32
+
33
+ @dataclass
34
+ class Running(Behaviour):
35
+ """True while the line is producing."""
36
+
37
+ def value(self, line: Line, t: float) -> bool:
38
+ return line.running(t)
39
+
40
+
41
+ @dataclass
42
+ class Counter(Behaviour):
43
+ """A production counter, advancing only while the line runs."""
44
+
45
+ per_minute: float = 60.0
46
+ fraction: float = 1.0
47
+ start: int = 0
48
+
49
+ def value(self, line: Line, t: float) -> int:
50
+ produced = line.running_seconds(t) * self.per_minute / 60.0
51
+ return self.start + int(produced * self.fraction)
52
+
53
+
54
+ @dataclass
55
+ class StoppedFor(Behaviour):
56
+ """Seconds the current stop has lasted. Zero while running."""
57
+
58
+ def value(self, line: Line, t: float) -> float:
59
+ return round(line.stopped_for(t), 1)
60
+
61
+
62
+ @dataclass
63
+ class Temperature(Behaviour):
64
+ """Approaches one value while running and another while stopped.
65
+
66
+ A first-order lag rather than a step, because a motor that jumps from 22 to
67
+ 74 degrees between two reads is the kind of signal that makes a monitoring
68
+ system look like it works when it does not.
69
+ """
70
+
71
+ running: float = 70.0
72
+ idle: float = 20.0
73
+ tau: float = 120.0
74
+ noise: float = 0.4
75
+ seed: int = 0
76
+
77
+ def value(self, line: Line, t: float) -> float:
78
+ return round(self._settled(line, t) + self._noise(t), 2)
79
+
80
+ def _settled(self, line: Line, t: float) -> float:
81
+ """Integrate the lag across every state change up to t."""
82
+ temp = self.idle
83
+ clock = 0.0
84
+ for stop in line.stops_before(t):
85
+ temp = self._approach(temp, self.running, min(stop.start, t) - clock)
86
+ clock = min(stop.start, t)
87
+ if clock >= t:
88
+ return temp
89
+ temp = self._approach(temp, self.idle, min(stop.end, t) - clock)
90
+ clock = min(stop.end, t)
91
+ if clock >= t:
92
+ return temp
93
+ return self._approach(temp, self.running, t - clock)
94
+
95
+ def _approach(self, start: float, target: float, seconds: float) -> float:
96
+ if seconds <= 0:
97
+ return start
98
+ return target + (start - target) * math.exp(-seconds / self.tau)
99
+
100
+ def _noise(self, t: float) -> float:
101
+ if not self.noise:
102
+ return 0.0
103
+ # Seeded on the tick so the same second always reads the same.
104
+ return random.Random(f"{self.seed}:{int(t)}").uniform(-self.noise, self.noise)
105
+
106
+
107
+ @dataclass
108
+ class Setpoint(Behaviour):
109
+ """A value the simulator writes once and then leaves to the client."""
110
+
111
+ value_: float = 0.0
112
+
113
+ def value(self, line: Line, t: float) -> Any:
114
+ return self.value_
115
+
116
+ @property
117
+ def writable(self) -> bool:
118
+ return True
119
+
120
+
121
+ BEHAVIOURS = {
122
+ "running": Running,
123
+ "counter": Counter,
124
+ "stopped_for": StoppedFor,
125
+ "temperature": Temperature,
126
+ "setpoint": Setpoint,
127
+ }