fieldsim 0.2.0__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.
fieldsim/simulator.py ADDED
@@ -0,0 +1,96 @@
1
+ """Runs every device of a simulation file together."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from pathlib import Path
7
+ from types import TracebackType
8
+ from typing import Any
9
+
10
+ from fieldsim.config import (
11
+ DeviceSpec,
12
+ ModbusDeviceSpec,
13
+ SimulationConfig,
14
+ load_config,
15
+ parse_config,
16
+ )
17
+ from fieldsim.core.clock import Clock, RealClock
18
+ from fieldsim.core.device import Device
19
+
20
+
21
+ def create_device(spec: DeviceSpec, *, clock: Clock | None = None) -> Device[Any]:
22
+ """Instantiate the device class matching ``spec.protocol``."""
23
+ if isinstance(spec, ModbusDeviceSpec):
24
+ from fieldsim.protocols.modbus.device import ModbusDevice
25
+
26
+ return ModbusDevice(spec, clock=clock)
27
+ raise TypeError(f"unsupported device spec: {type(spec).__name__}") # pragma: no cover
28
+
29
+
30
+ class Simulator:
31
+ """A group of devices started and stopped as a unit.
32
+
33
+ ::
34
+
35
+ async with Simulator.from_yaml("plant.yaml") as sim:
36
+ plc = sim["boiler-plc"]
37
+ plc.set("temperature", 85.0)
38
+ """
39
+
40
+ def __init__(self, config: SimulationConfig, *, clock: Clock | None = None):
41
+ self.config = config
42
+ #: Shared by every device, so their scenarios stay in step.
43
+ self.clock: Clock = clock or RealClock()
44
+ self.devices: dict[str, Device[Any]] = {
45
+ spec.name: create_device(spec, clock=self.clock) for spec in config.devices
46
+ }
47
+
48
+ @classmethod
49
+ def from_yaml(cls, path: str | Path, *, clock: Clock | None = None) -> Simulator:
50
+ return cls(load_config(path), clock=clock)
51
+
52
+ @classmethod
53
+ def from_dict(cls, data: dict[str, Any], *, clock: Clock | None = None) -> Simulator:
54
+ return cls(parse_config(data), clock=clock)
55
+
56
+ def __getitem__(self, name: str) -> Device[Any]:
57
+ try:
58
+ return self.devices[name]
59
+ except KeyError:
60
+ raise KeyError(
61
+ f"no device named {name!r}; available: {', '.join(self.devices)}"
62
+ ) from None
63
+
64
+ def __iter__(self) -> Iterator[Device[Any]]:
65
+ return iter(self.devices.values())
66
+
67
+ def __len__(self) -> int:
68
+ return len(self.devices)
69
+
70
+ async def start(self) -> None:
71
+ """Start all devices. If one fails, the ones already started are stopped again."""
72
+ started: list[Device[Any]] = []
73
+ try:
74
+ for device in self.devices.values():
75
+ await device.start()
76
+ started.append(device)
77
+ except BaseException:
78
+ for device in reversed(started):
79
+ await device.stop()
80
+ raise
81
+
82
+ async def stop(self) -> None:
83
+ for device in reversed(list(self.devices.values())):
84
+ await device.stop()
85
+
86
+ async def __aenter__(self) -> Simulator:
87
+ await self.start()
88
+ return self
89
+
90
+ async def __aexit__(
91
+ self,
92
+ exc_type: type[BaseException] | None,
93
+ exc: BaseException | None,
94
+ tb: TracebackType | None,
95
+ ) -> None:
96
+ await self.stop()
@@ -0,0 +1,257 @@
1
+ Metadata-Version: 2.5
2
+ Name: fieldsim
3
+ Version: 0.2.0
4
+ Summary: Virtual Modbus, OPC UA and S7 devices for testing industrial software without hardware.
5
+ Project-URL: Homepage, https://github.com/enesuslu15/fieldsim
6
+ Project-URL: Issues, https://github.com/enesuslu15/fieldsim/issues
7
+ Author: enesuslu15
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 enesuslu15
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: iiot,industrial,modbus,opc-ua,plc,pytest,s7,simulator,testing
31
+ Classifier: Development Status :: 3 - Alpha
32
+ Classifier: Framework :: AsyncIO
33
+ Classifier: Framework :: Pytest
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: Intended Audience :: Manufacturing
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Operating System :: OS Independent
38
+ Classifier: Programming Language :: Python :: 3
39
+ Classifier: Programming Language :: Python :: 3.10
40
+ Classifier: Programming Language :: Python :: 3.11
41
+ Classifier: Programming Language :: Python :: 3.12
42
+ Classifier: Programming Language :: Python :: 3.13
43
+ Classifier: Topic :: Software Development :: Testing
44
+ Classifier: Topic :: System :: Networking
45
+ Classifier: Typing :: Typed
46
+ Requires-Python: >=3.10
47
+ Requires-Dist: pydantic<3,>=2.6
48
+ Requires-Dist: pyyaml>=6.0
49
+ Requires-Dist: typer>=0.12
50
+ Provides-Extra: dev
51
+ Requires-Dist: mypy>=1.10; extra == 'dev'
52
+ Requires-Dist: pre-commit>=3.5; extra == 'dev'
53
+ Requires-Dist: pymodbus<4,>=3.10; extra == 'dev'
54
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
55
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
56
+ Requires-Dist: pytest>=8.0; extra == 'dev'
57
+ Requires-Dist: ruff>=0.6; extra == 'dev'
58
+ Requires-Dist: types-pyyaml; extra == 'dev'
59
+ Description-Content-Type: text/markdown
60
+
61
+ # fieldsim
62
+
63
+ **Virtual industrial devices for testing software without hardware.**
64
+
65
+ fieldsim starts fake Modbus devices (OPC UA and S7 are on the roadmap) from a YAML
66
+ file, drives their values with generators, breaks them on purpose with fault
67
+ injection and plays scripted scenarios — so you can test gateways, SCADA
68
+ connectors and edge apps in CI, no PLC on your desk required.
69
+
70
+ > Status: alpha (`0.2.0`). The file format may still change before 1.0.
71
+
72
+ ## Install
73
+
74
+ ```bash
75
+ pip install fieldsim
76
+ ```
77
+
78
+ ## Test with pytest
79
+
80
+ Installing fieldsim registers a pytest plugin. With no configuration at all you
81
+ get a Modbus TCP device whose whole address space is plain memory:
82
+
83
+ ```python
84
+ def test_gateway_writes_registers(modbus_device):
85
+ Gateway(modbus_device.host, modbus_device.port).write_register(100, 42)
86
+ event = modbus_device.wait_for_write(timeout=2)
87
+ assert event.address == 100 and event.values == (42,)
88
+ ```
89
+
90
+ Point it at a device file to get named points, generators and scenarios:
91
+
92
+ ```python
93
+ import pytest
94
+
95
+
96
+ @pytest.mark.fieldsim("boiler.yaml")
97
+ def test_gateway_reads_temperature(modbus_device):
98
+ modbus_device.set("temperature", 85.0) # pauses the generator
99
+ assert Gateway(*modbus_device.address).temperature() == 85.0
100
+
101
+
102
+ @pytest.mark.fieldsim("boiler.yaml")
103
+ def test_gateway_survives_a_slow_plc(modbus_device):
104
+ with modbus_device.fault("latency", delay="800ms"):
105
+ assert Gateway(*modbus_device.address, timeout=1).temperature() is not None
106
+
107
+
108
+ @pytest.mark.fieldsim("boiler.yaml")
109
+ def test_gateway_retries_lost_responses(modbus_device):
110
+ with modbus_device.fault("drop", count=2) as fault:
111
+ Gateway(*modbus_device.address, retries=3).temperature()
112
+ assert fault.hits == 2
113
+
114
+
115
+ @pytest.mark.fieldsim("boiler.yaml")
116
+ def test_gateway_reconnects_after_outage(modbus_device):
117
+ gw = Gateway(*modbus_device.address)
118
+ with modbus_device.offline():
119
+ assert not gw.healthy()
120
+ assert gw.healthy()
121
+
122
+
123
+ @pytest.mark.fieldsim("boiler.yaml")
124
+ def test_gateway_writes_setpoint(modbus_device):
125
+ Gateway(*modbus_device.address).set_setpoint(80)
126
+ modbus_device.wait_for_write("setpoint", timeout=2)
127
+ assert modbus_device.get("setpoint") == 80
128
+
129
+
130
+ @pytest.mark.fieldsim("boiler.yaml", clock="virtual")
131
+ def test_overheat_alarm(modbus_device):
132
+ modbus_device.advance(600) # ten minutes, instantly
133
+ ...
134
+ ```
135
+
136
+ Fixtures and options:
137
+
138
+ | | |
139
+ |---|---|
140
+ | `modbus_device` | The Modbus device of the simulation (choose with `mark.fieldsim(device="name")` if there are several). |
141
+ | `fieldsim` | The whole running simulation: `fieldsim["plc-1"]`, `fieldsim.advance(10)`. |
142
+ | `make_modbus_device` | Factory for ad-hoc devices: `make_modbus_device(registers={...}, unit_id=3)`. |
143
+ | `@pytest.mark.fieldsim(config, device=, clock=, free_ports=)` | Per-test configuration. `config` is a YAML path (relative to the test file or rootdir) or a dict. |
144
+ | ini `fieldsim_config`, `fieldsim_clock`, `fieldsim_free_ports` | Project-wide defaults. |
145
+
146
+ Devices run in a background thread on free ports, so the fixtures work in plain,
147
+ asyncio and trio tests, and with `pytest-xdist`. In async tests use
148
+ `await device.wait_for_write_async(...)` and `await device.advance_async(...)`.
149
+
150
+ ## Describe a device
151
+
152
+ ```yaml
153
+ # boiler.yaml
154
+ version: 1
155
+ devices:
156
+ - name: boiler-plc
157
+ protocol: modbus_tcp # or modbus_rtu_over_tcp
158
+ port: 5020
159
+ registers:
160
+ coils:
161
+ - { name: pump_on, address: 0, value: true }
162
+ holding_registers:
163
+ - name: temperature
164
+ address: 0
165
+ type: float32
166
+ generator: { type: sine, min: 60, max: 90, period: 30s }
167
+ - { name: setpoint, address: 2, type: uint16, value: 75 }
168
+
169
+ faults: # active from the start
170
+ - { type: latency, delay: 20ms, jitter: 10ms }
171
+
172
+ scenario: # relative to device start
173
+ - { at: 30s, set: { temperature: 120 } }
174
+ - { at: 40s, fault: { type: exception, code: 6 }, duration: 5s }
175
+ - { at: 60s, offline: 10s }
176
+ - { at: 90s, release: [temperature] }
177
+ ```
178
+
179
+ Run it standalone, e.g. as a service container in CI:
180
+
181
+ ```bash
182
+ fieldsim validate boiler.yaml
183
+ fieldsim run boiler.yaml
184
+ ```
185
+
186
+ Get a JSON Schema for editor autocompletion with `fieldsim schema -o fieldsim.schema.json`.
187
+
188
+ ### Device options
189
+
190
+ | Key | Meaning |
191
+ |---|---|
192
+ | `protocol` | `modbus_tcp`, or `modbus_rtu_over_tcp` for RTU frames (with CRC) tunnelled over TCP. |
193
+ | `host`, `port` | Listen address. `port: 0` picks a free port. |
194
+ | `unit_id` | Only answer this unit id (default: answer all). |
195
+ | `unmapped` | `error` (exception 02 for undefined addresses, default) or `allow` (plain memory). |
196
+ | `update_interval` | Generator refresh rate, e.g. `100ms`. |
197
+ | `faults` | Faults active from the start (see below). |
198
+ | `scenario` | Timed steps: `set`, `release`, `fault` (+ `duration`), `offline`. |
199
+ | `seed` | Makes random faults reproducible. |
200
+
201
+ Points live in `registers.coils`, `discrete_inputs`, `holding_registers` and
202
+ `input_registers`, with `name`, `address`, `value`, `generator`, `description` and —
203
+ for registers — `type` (`int16 uint16 int32 uint32 int64 uint64 float32 float64`),
204
+ `byte_order` and `word_order`. Coils and holding registers take `writable: false`.
205
+
206
+ Generators: `constant`, `sine`, `ramp` (`sawtooth` / `triangle` / `once`),
207
+ `random_walk`, `sequence`.
208
+
209
+ ### Faults
210
+
211
+ | Type | Effect |
212
+ |---|---|
213
+ | `latency` | Delay responses by `delay` + random `0..jitter`. |
214
+ | `drop` | No response. `executed: true` still performs the request (lost reply). |
215
+ | `disconnect` | Close the connection instead of answering. |
216
+ | `exception` | Answer with Modbus exception `code` (default 6, SERVER DEVICE BUSY). |
217
+ | `corrupt` | Damage the response: `bit_flip`, `truncate`, `garbage`, `bad_length` (TCP), `transaction_id` (TCP), `bad_crc` (RTU). |
218
+
219
+ Every fault accepts `probability` (0..1), `function_codes` (list) and `count`
220
+ (remove after N hits).
221
+
222
+ ## Use from Python
223
+
224
+ ```python
225
+ from fieldsim import Simulator, VirtualClock
226
+
227
+ clock = VirtualClock()
228
+ async with Simulator.from_yaml("boiler.yaml", clock=clock) as sim:
229
+ plc = sim["boiler-plc"]
230
+ with plc.fault("corrupt", mode="bit_flip", probability=0.1):
231
+ await clock.advance(60)
232
+ ```
233
+
234
+ From synchronous code use `BackgroundSimulator("boiler.yaml")` as a context
235
+ manager; its device handles are thread-safe.
236
+
237
+ ## Supported Modbus function codes
238
+
239
+ 01 Read Coils · 02 Read Discrete Inputs · 03 Read Holding Registers · 04 Read Input Registers ·
240
+ 05 Write Single Coil · 06 Write Single Register · 15 Write Multiple Coils · 16 Write Multiple Registers
241
+
242
+ ## Development
243
+
244
+ ```bash
245
+ python -m venv .venv
246
+ .venv/Scripts/activate # Windows; use .venv/bin/activate elsewhere
247
+ pip install -e ".[dev]"
248
+ pre-commit install
249
+ coverage run -m pytest && coverage report
250
+ ```
251
+
252
+ `coverage run` is used instead of `pytest --cov` because fieldsim's own pytest
253
+ plugin is imported before pytest-cov starts measuring.
254
+
255
+ ## License
256
+
257
+ MIT
@@ -0,0 +1,30 @@
1
+ fieldsim/__init__.py,sha256=QVPnmoNFwYc3LnQyITsMCbS-N7JLNVIyhsNm4msSTvY,724
2
+ fieldsim/__main__.py,sha256=575oCPMSTNWqEq_bWvd-wdIGfuCJXt9WQ3_oF6Q579s,56
3
+ fieldsim/background.py,sha256=FF9qae_jbjIBdFaGFBRMA9C-ZNx_V0Twt8A7UbYmzy8,12697
4
+ fieldsim/cli.py,sha256=5ayTJSziAgQiqsAcM_RgBrhs6di310WIMiW_x7a2kQU,4317
5
+ fieldsim/config.py,sha256=C-Enbk_COSUxwt5QN9g1pbY8dlUY1JDJWEI2l6SU2KI,18236
6
+ fieldsim/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ fieldsim/pytest_plugin.py,sha256=uoDxqkdQjq6abJi4VGMgvb80SfLQb9x-TtnsdGPdzc4,5782
8
+ fieldsim/simulator.py,sha256=eD5av0g5MLqIuK1-i7cwuUSWQ2wjQ-Yk5CV5cztJjcM,3019
9
+ fieldsim/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ fieldsim/core/clock.py,sha256=EZC-It7erFFV3B_Idojxekq4uiFORqnoPCWy_kzGEGo,2850
11
+ fieldsim/core/datastore.py,sha256=LJvvpJ66S5uIGMA0YvpgTqsOm7YA9oB2FYJPpQv36Co,1053
12
+ fieldsim/core/device.py,sha256=oso6m9aJxvUt3kIIj7UlcvJyC0h8xMOWcRjAL5dwTFo,6624
13
+ fieldsim/core/engine.py,sha256=c7P3bzt5sHkJsptPqoxh_XowWRJ6E3vwTJq4W7MkwJM,2757
14
+ fieldsim/core/faults.py,sha256=9PPDtgVTU1ffTc_l9iZoCDMnplLewS2t7i0h9jZm8vU,4533
15
+ fieldsim/core/generators.py,sha256=lfDvPnC1DwbTb49vtTeEZJJAWX6LVQErlGbsANH6bgs,3936
16
+ fieldsim/core/scenario.py,sha256=MSVKG8Z1zd7n5g7WyDKAeHRVQnDPrR7qUqanwGgyUOo,4652
17
+ fieldsim/core/types.py,sha256=_Se0UEIA5ZXy-rFTqA8vMn3puRSZUpuWEIv_68t3KD8,4570
18
+ fieldsim/protocols/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ fieldsim/protocols/modbus/__init__.py,sha256=C2k1HP2l-DLppJqFEtI6VZYzpOilYbK33QWXYghUEKE,525
20
+ fieldsim/protocols/modbus/constants.py,sha256=6XiMMKrjA5gVcFgOMB6CnTTkQReihkzomku-0gRv_NU,1104
21
+ fieldsim/protocols/modbus/datastore.py,sha256=mYjJp_IKURXMI19UZC2ob--b8b0tcWK300n5jEhZePo,7894
22
+ fieldsim/protocols/modbus/device.py,sha256=sAvQFc6vj8YKQwSwVvLr9CLdcuu_WEpRgMiJRbPXo2Y,4232
23
+ fieldsim/protocols/modbus/framer.py,sha256=f5J7pK_4mvtsr8ew5_L5EuGLX4Ua6aSAZq2FER4S0fM,6693
24
+ fieldsim/protocols/modbus/pdu.py,sha256=i1XI_uKB7ycumS_ZeaAe6a5oHVWKJnI4AbVQndlIWMI,6022
25
+ fieldsim/protocols/modbus/server.py,sha256=gNXssAXMjx3xCsZVir2bd1HnLZtFG5taxs6EEJ9L8Xw,4975
26
+ fieldsim-0.2.0.dist-info/METADATA,sha256=VFYyPPm1RY_l7r2EpqA7UESEaANobAJoKQI-GNlwyn8,9762
27
+ fieldsim-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
28
+ fieldsim-0.2.0.dist-info/entry_points.txt,sha256=kpLImS8JxSzWBAv4AgLmal0Uvel1UVKIZlxwteaEbp0,92
29
+ fieldsim-0.2.0.dist-info/licenses/LICENSE,sha256=_fEF_ueN5_od-1I-9UBdMtvB6fCphiGDkEIXhl082C0,1067
30
+ fieldsim-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ fieldsim = fieldsim.cli:app
3
+
4
+ [pytest11]
5
+ fieldsim = fieldsim.pytest_plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 enesuslu15
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.