elmulator 0.1.0__tar.gz

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,20 @@
1
+ # Swift / SwiftPM
2
+ .build/
3
+ Package.resolved
4
+ *.xcodeproj
5
+ .DS_Store
6
+
7
+ # Python
8
+ __pycache__/
9
+ *.py[cod]
10
+ python/build/
11
+ python/dist/
12
+ python/*.egg-info/
13
+ src/*.egg-info/
14
+ .pytest_cache/
15
+ .venv/
16
+ venv/
17
+
18
+ # Editors
19
+ .idea/
20
+ .vscode/
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: elmulator
3
+ Version: 0.1.0
4
+ Summary: A scriptable Bluetooth + TCP OBD2 (ELM327) adapter emulator and CI test harness.
5
+ Project-URL: Homepage, https://github.com/qadanm/elmulator
6
+ Project-URL: Repository, https://github.com/qadanm/elmulator
7
+ Project-URL: Specification, https://github.com/qadanm/elmulator/blob/main/SPEC.md
8
+ Author: elmulator contributors
9
+ License: MIT
10
+ Keywords: automotive,ble,bluetooth,ci,elm327,emulator,obd2,testing
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Testing
15
+ Classifier: Topic :: System :: Emulators
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+
19
+ # elmulator — Python package
20
+
21
+ A pure-standard-library ELM327 TCP server and scenario validator. No third-party dependencies. Python 3.9+.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install elmulator # once published
27
+ # or from this checkout:
28
+ pip install -e .
29
+ ```
30
+
31
+ ## CLI
32
+
33
+ ```bash
34
+ elmulator serve SCENARIO [--host H] [--port N] [--echo on|off|scenario] \
35
+ [--split a,b,c] [--latency-ms N] [--jitter-ms N] [--seed N]
36
+ elmulator validate [PATHS...] # files or dirs; defaults to the bundled examples
37
+ elmulator self-test # in-process loopback smoke test
38
+ ```
39
+
40
+ `serve` prints `LISTENING <port>` on stdout once bound (`--port 0` picks a free port) and logs activity to stderr. Each client gets its own scenario cursor state.
41
+
42
+ ## Library
43
+
44
+ ```python
45
+ from elmulator import Scenario, serve
46
+ import argparse
47
+
48
+ scenario = Scenario.from_path("scenarios/p0420_basic.scenario.json")
49
+ args = argparse.Namespace(host="127.0.0.1", port=0, echo="scenario",
50
+ split=None, latency_ms=0, jitter_ms=0, seed=0)
51
+ serve(args, scenario) # blocking; pass ready_event/stop_event for threaded use
52
+ ```
53
+
54
+ The matching, echo, splitting, and jitter semantics are identical to the Swift engine; the [conformance suite](../conformance/) proves byte-for-byte parity.
55
+
56
+ ## Test
57
+
58
+ ```bash
59
+ pip install pytest
60
+ pytest -q
61
+ ```
@@ -0,0 +1,43 @@
1
+ # elmulator — Python package
2
+
3
+ A pure-standard-library ELM327 TCP server and scenario validator. No third-party dependencies. Python 3.9+.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install elmulator # once published
9
+ # or from this checkout:
10
+ pip install -e .
11
+ ```
12
+
13
+ ## CLI
14
+
15
+ ```bash
16
+ elmulator serve SCENARIO [--host H] [--port N] [--echo on|off|scenario] \
17
+ [--split a,b,c] [--latency-ms N] [--jitter-ms N] [--seed N]
18
+ elmulator validate [PATHS...] # files or dirs; defaults to the bundled examples
19
+ elmulator self-test # in-process loopback smoke test
20
+ ```
21
+
22
+ `serve` prints `LISTENING <port>` on stdout once bound (`--port 0` picks a free port) and logs activity to stderr. Each client gets its own scenario cursor state.
23
+
24
+ ## Library
25
+
26
+ ```python
27
+ from elmulator import Scenario, serve
28
+ import argparse
29
+
30
+ scenario = Scenario.from_path("scenarios/p0420_basic.scenario.json")
31
+ args = argparse.Namespace(host="127.0.0.1", port=0, echo="scenario",
32
+ split=None, latency_ms=0, jitter_ms=0, seed=0)
33
+ serve(args, scenario) # blocking; pass ready_event/stop_event for threaded use
34
+ ```
35
+
36
+ The matching, echo, splitting, and jitter semantics are identical to the Swift engine; the [conformance suite](../conformance/) proves byte-for-byte parity.
37
+
38
+ ## Test
39
+
40
+ ```bash
41
+ pip install pytest
42
+ pytest -q
43
+ ```
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "elmulator"
7
+ version = "0.1.0"
8
+ description = "A scriptable Bluetooth + TCP OBD2 (ELM327) adapter emulator and CI test harness."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "elmulator contributors" }]
13
+ keywords = ["obd2", "elm327", "emulator", "bluetooth", "ble", "automotive", "testing", "ci"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Software Development :: Testing",
19
+ "Topic :: System :: Emulators",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/qadanm/elmulator"
25
+ Repository = "https://github.com/qadanm/elmulator"
26
+ Specification = "https://github.com/qadanm/elmulator/blob/main/SPEC.md"
27
+
28
+ [project.scripts]
29
+ elmulator = "elmulator.cli:main"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/elmulator"]
@@ -0,0 +1,11 @@
1
+ """elmulator — a scriptable Bluetooth + TCP OBD2 (ELM327) adapter emulator.
2
+
3
+ The Python package provides the language-neutral TCP server and the scenario
4
+ validator. See the `elmulator` console command (`elmulator --help`).
5
+ """
6
+
7
+ from .server import EngineState, Scenario, normalize, serve, self_test
8
+
9
+ __all__ = ["Scenario", "EngineState", "normalize", "serve", "self_test", "__version__"]
10
+
11
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env python3
2
+ """`elmulator` command line entry point.
3
+
4
+ Subcommands:
5
+ elmulator serve SCENARIO [options] host a scenario over TCP
6
+ elmulator validate [PATHS...] validate scenario files (or the bundled examples)
7
+ elmulator self-test run an in-process loopback smoke test
8
+ """
9
+
10
+ import argparse
11
+ import sys
12
+
13
+ from . import server, validate
14
+
15
+
16
+ def _split_list(text: str):
17
+ return [int(piece) for piece in text.split(",") if piece]
18
+
19
+
20
+ def build_parser() -> argparse.ArgumentParser:
21
+ parser = argparse.ArgumentParser(
22
+ prog="elmulator",
23
+ description="Scriptable Bluetooth + TCP OBD2 (ELM327) adapter emulator.",
24
+ )
25
+ sub = parser.add_subparsers(dest="command")
26
+
27
+ serve = sub.add_parser("serve", help="host a scenario over localhost TCP")
28
+ serve.add_argument("scenario", help="path to a .scenario.json file")
29
+ serve.add_argument("--host", default="127.0.0.1")
30
+ serve.add_argument("--port", type=int, default=35000, help="0 picks a free port")
31
+ serve.add_argument(
32
+ "--echo", choices=["on", "off", "scenario"], default="scenario",
33
+ help="force echo on or off, or follow the scenario (default)",
34
+ )
35
+ serve.add_argument(
36
+ "--split", type=_split_list, default=None,
37
+ help="cycled piece sizes, for example 1,2,5",
38
+ )
39
+ serve.add_argument("--latency-ms", type=int, default=0)
40
+ serve.add_argument("--jitter-ms", type=int, default=0)
41
+ serve.add_argument("--seed", type=int, default=0, help="deterministic jitter seed")
42
+
43
+ check = sub.add_parser("validate", help="validate scenario files")
44
+ check.add_argument(
45
+ "paths", nargs="*",
46
+ help="scenario files or directories (default: the bundled examples)",
47
+ )
48
+
49
+ sub.add_parser("self-test", help="run an in-process loopback smoke test")
50
+ return parser
51
+
52
+
53
+ def main(argv=None) -> int:
54
+ parser = build_parser()
55
+ args = parser.parse_args(argv)
56
+ if args.command == "serve":
57
+ return server.run_serve(args)
58
+ if args.command == "validate":
59
+ return validate.run(args.paths)
60
+ if args.command == "self-test":
61
+ return server.self_test()
62
+ parser.print_help()
63
+ return 2
64
+
65
+
66
+ if __name__ == "__main__":
67
+ sys.exit(main())
@@ -0,0 +1,320 @@
1
+ #!/usr/bin/env python3
2
+ """Scriptable ELM327 TCP server.
3
+
4
+ Serves an obd2.sim_scenario.v1 scenario over localhost TCP so an app in a
5
+ simulator, or any TCP client in any language, can run a full OBD2 session
6
+ without a car. The matching, echo, splitting, and jitter semantics are the
7
+ same as the Swift `FakeELMScenarioEngine` — the two implementations are held
8
+ byte-for-byte equivalent by the conformance suite.
9
+
10
+ Pure Python standard library; no third-party dependencies.
11
+
12
+ Behavior:
13
+ - prints "LISTENING <port>" on stdout once bound (port 0 picks a free port)
14
+ - accepts one or more clients, each with its own scenario cursor state
15
+ - reads commands until CR or LF; partial reads stay buffered
16
+ - logs every command and reply timing to stderr
17
+ - exits cleanly on SIGINT / Ctrl-C
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import selectors
23
+ import signal
24
+ import socket
25
+ import sys
26
+ import threading
27
+ import time
28
+ from pathlib import Path
29
+
30
+ POST_ACTIONS = ("none", "stall", "disconnect")
31
+
32
+
33
+ class SplitMix64:
34
+ """Deterministic jitter source; clean-room SplitMix64."""
35
+
36
+ MASK = (1 << 64) - 1
37
+
38
+ def __init__(self, seed: int):
39
+ self.state = seed & self.MASK
40
+
41
+ def next(self) -> int:
42
+ self.state = (self.state + 0x9E3779B97F4A7C15) & self.MASK
43
+ z = self.state
44
+ z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & self.MASK
45
+ z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & self.MASK
46
+ return z ^ (z >> 31)
47
+
48
+
49
+ class Scenario:
50
+ def __init__(self, data: dict):
51
+ if data.get("schema_version") != "obd2.sim_scenario.v1":
52
+ raise ValueError(f"unsupported schema_version {data.get('schema_version')!r}")
53
+ if data.get("synthetic") is not True:
54
+ raise ValueError("scenario must declare synthetic true")
55
+ self.scenario_id = data["scenario_id"]
56
+ self.defaults = data["defaults"]
57
+ self.stream_split_bytes = data.get("stream_split_bytes")
58
+ self.commands = data["commands"]
59
+ for command in self.commands:
60
+ action = command.get("post_action", "none")
61
+ if action not in POST_ACTIONS:
62
+ raise ValueError(f"unknown post_action {action!r}")
63
+
64
+ @classmethod
65
+ def from_path(cls, path: Path) -> "Scenario":
66
+ return cls(json.loads(Path(path).read_text(encoding="utf-8")))
67
+
68
+
69
+ def normalize(command: str) -> str:
70
+ return "".join(command.upper().split())
71
+
72
+
73
+ class EngineState:
74
+ """Per-connection cursor state, mirroring the Swift engine semantics:
75
+ entries per request consume in order, the last entry repeats, and an
76
+ entry with repeat true pins the cursor."""
77
+
78
+ def __init__(self, scenario: Scenario, args):
79
+ self.scenario = scenario
80
+ self.args = args
81
+ self.cursors = {}
82
+ self.random = SplitMix64(args.seed)
83
+
84
+ def plan(self, raw_command: str):
85
+ normalized = normalize(raw_command)
86
+ entries = [
87
+ command for command in self.scenario.commands
88
+ if normalize(command["request"]) == normalized
89
+ ]
90
+ if not entries:
91
+ return self._default_plan(normalized)
92
+
93
+ cursor = self.cursors.get(normalized, 0)
94
+ position = min(cursor, len(entries) - 1)
95
+ command = entries[position]
96
+ if not command.get("repeat", False):
97
+ self.cursors[normalized] = min(position + 1, len(entries) - 1)
98
+
99
+ echo = command.get("echo", False)
100
+ if self.args.echo == "on":
101
+ echo = True
102
+ elif self.args.echo == "off":
103
+ echo = False
104
+
105
+ text = (normalized + "\r" if echo else "") + "".join(command["response_chunks"])
106
+ pieces = self._split(text)
107
+ first_delay = command.get("delay_ms", 0) + self.args.latency_ms + self._jitter()
108
+ return pieces, first_delay, command.get("post_action", "none"), command["request"]
109
+
110
+ def _default_plan(self, normalized: str):
111
+ body = (
112
+ self.scenario.defaults["at_response"]
113
+ if normalized.startswith("AT")
114
+ else self.scenario.defaults["obd_response"]
115
+ )
116
+ text = (normalized + "\r" if self.args.echo == "on" else "") + body
117
+ return self._split(text), self.args.latency_ms + self._jitter(), "none", None
118
+
119
+ def _jitter(self) -> int:
120
+ if self.args.jitter_ms <= 0:
121
+ return 0
122
+ return self.random.next() % (self.args.jitter_ms + 1)
123
+
124
+ def _split(self, text: str):
125
+ pieces = [text] if text else []
126
+ if self.scenario.stream_split_bytes:
127
+ pieces = self._slice(pieces, [self.scenario.stream_split_bytes])
128
+ if self.args.split:
129
+ pieces = self._slice(pieces, self.args.split)
130
+ return [piece for piece in pieces if piece]
131
+
132
+ @staticmethod
133
+ def _slice(pieces, sizes):
134
+ result = []
135
+ for piece in pieces:
136
+ index = 0
137
+ size_index = 0
138
+ while index < len(piece):
139
+ size = max(1, sizes[size_index % len(sizes)])
140
+ result.append(piece[index:index + size])
141
+ index += size
142
+ size_index += 1
143
+ return result
144
+
145
+
146
+ def log(message: str):
147
+ print(f"[elmulator] {message}", file=sys.stderr, flush=True)
148
+
149
+
150
+ def handle_client(client: socket.socket, address, scenario: Scenario, args):
151
+ engine = EngineState(scenario, args)
152
+ buffer = ""
153
+ log(f"client connected: {address}")
154
+ try:
155
+ while True:
156
+ data = client.recv(4096)
157
+ if not data:
158
+ break
159
+ buffer += data.decode("ascii", errors="replace")
160
+ while True:
161
+ cr = buffer.find("\r")
162
+ lf = buffer.find("\n")
163
+ cut = min(x for x in (cr, lf) if x >= 0) if (cr >= 0 or lf >= 0) else -1
164
+ if cut < 0:
165
+ break
166
+ line, buffer = buffer[:cut].strip(), buffer[cut + 1:]
167
+ if not line:
168
+ continue
169
+ started = time.monotonic()
170
+ pieces, first_delay, action, matched = engine.plan(line)
171
+ if action == "stall":
172
+ log(f"{line!r} -> stall (no reply)")
173
+ continue
174
+ for index, piece in enumerate(pieces):
175
+ delay = first_delay if index == 0 else 0
176
+ if delay > 0:
177
+ time.sleep(delay / 1000.0)
178
+ client.sendall(piece.encode("ascii"))
179
+ elapsed_ms = int((time.monotonic() - started) * 1000)
180
+ source = "scenario" if matched else "default"
181
+ log(f"{line!r} -> {sum(len(p) for p in pieces)} bytes in {len(pieces)} piece(s), {elapsed_ms}ms ({source})")
182
+ if action == "disconnect":
183
+ log(f"{line!r} -> disconnect (scenario action)")
184
+ return
185
+ except (ConnectionResetError, BrokenPipeError):
186
+ pass
187
+ finally:
188
+ client.close()
189
+ log(f"client closed: {address}")
190
+
191
+
192
+ def serve(args, scenario: Scenario, ready_event=None, stop_event=None):
193
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
194
+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
195
+ server.bind((args.host, args.port))
196
+ server.listen(4)
197
+ bound_port = server.getsockname()[1]
198
+ print(f"LISTENING {bound_port}", flush=True)
199
+ log(f"scenario {scenario.scenario_id!r} on {args.host}:{bound_port}")
200
+ if ready_event is not None:
201
+ args.port = bound_port
202
+ ready_event.set()
203
+
204
+ selector = selectors.DefaultSelector()
205
+ selector.register(server, selectors.EVENT_READ)
206
+ threads = []
207
+ try:
208
+ while stop_event is None or not stop_event.is_set():
209
+ if not selector.select(timeout=0.2):
210
+ continue
211
+ client, address = server.accept()
212
+ thread = threading.Thread(
213
+ target=handle_client,
214
+ args=(client, address, scenario, args),
215
+ daemon=True,
216
+ )
217
+ thread.start()
218
+ threads.append(thread)
219
+ except KeyboardInterrupt:
220
+ log("interrupted, shutting down")
221
+ finally:
222
+ selector.close()
223
+ server.close()
224
+ return 0
225
+
226
+
227
+ def run_serve(args) -> int:
228
+ """Entry point used by the `elmulator serve` CLI subcommand."""
229
+ try:
230
+ scenario = Scenario.from_path(Path(args.scenario))
231
+ except (OSError, ValueError, KeyError, json.JSONDecodeError) as error:
232
+ log(f"scenario load failed: {error}")
233
+ return 2
234
+ signal.signal(signal.SIGINT, signal.default_int_handler)
235
+ return serve(args, scenario)
236
+
237
+
238
+ # A tiny, fully self-contained scenario so `self-test` works even when the
239
+ # package is pip-installed and no example files are on disk.
240
+ SELF_TEST_SCENARIO = {
241
+ "schema_version": "obd2.sim_scenario.v1",
242
+ "scenario_id": "self_test",
243
+ "synthetic": True,
244
+ "description": "inline loopback self-test scenario",
245
+ "adapter_profile": "elm327_like_tcp",
246
+ "defaults": {"at_response": "OK\r\r>", "obd_response": "NO DATA\r\r>"},
247
+ "stream_split_bytes": None,
248
+ "warnings": [],
249
+ "commands": [
250
+ {"request": "ATZ", "response_chunks": ["ELM327 v1.5\r\r>"], "echo": True, "prompt": True},
251
+ {"request": "03", "response_chunks": ["43 01 04 20\r\r>"], "prompt": True},
252
+ ],
253
+ "expected_scan_summary": {},
254
+ }
255
+
256
+
257
+ def _self_test_args():
258
+ return argparse.Namespace(
259
+ host="127.0.0.1", port=0, echo="scenario",
260
+ split=None, latency_ms=0, jitter_ms=0, seed=0,
261
+ )
262
+
263
+
264
+ def self_test() -> int:
265
+ """Loopback check: serve the inline scenario on an ephemeral port, speak a
266
+ short ELM conversation, and verify echo, prompt, defaults, and code bytes."""
267
+ scenario = Scenario(SELF_TEST_SCENARIO)
268
+ args = _self_test_args()
269
+ ready = threading.Event()
270
+ stop = threading.Event()
271
+ server_thread = threading.Thread(
272
+ target=serve, args=(args, scenario, ready, stop), daemon=True
273
+ )
274
+ server_thread.start()
275
+ if not ready.wait(timeout=5):
276
+ print("SELF-TEST FAIL: server did not start")
277
+ return 1
278
+
279
+ failures = []
280
+
281
+ def exchange(sock, command: str) -> str:
282
+ sock.sendall((command + "\r").encode("ascii"))
283
+ reply = ""
284
+ while ">" not in reply:
285
+ chunk = sock.recv(4096).decode("ascii")
286
+ if not chunk:
287
+ failures.append(f"{command}: connection closed before prompt")
288
+ return reply
289
+ reply += chunk
290
+ return reply
291
+
292
+ try:
293
+ with socket.create_connection(("127.0.0.1", args.port), timeout=5) as sock:
294
+ reset = exchange(sock, "ATZ")
295
+ if not reset.startswith("ATZ\r"):
296
+ failures.append(f"ATZ echo missing: {reset!r}")
297
+ if "ELM327 v1.5" not in reset:
298
+ failures.append(f"ATZ banner missing: {reset!r}")
299
+ for setup in ("ATE0", "ATL0", "ATH1", "ATSP0"):
300
+ reply = exchange(sock, setup)
301
+ if "OK" not in reply:
302
+ failures.append(f"{setup} expected OK: {reply!r}")
303
+ stored = exchange(sock, "03")
304
+ if "43 01 04 20" not in stored:
305
+ failures.append(f"03 expected P0420 bytes: {stored!r}")
306
+ unknown = exchange(sock, "0142")
307
+ if "NO DATA" not in unknown:
308
+ failures.append(f"0142 expected default NO DATA: {unknown!r}")
309
+ except OSError as error:
310
+ failures.append(f"socket error: {error}")
311
+ finally:
312
+ stop.set()
313
+ server_thread.join(timeout=5)
314
+
315
+ if failures:
316
+ for failure in failures:
317
+ print(f"SELF-TEST FAIL: {failure}")
318
+ return 1
319
+ print("SELF-TEST OK")
320
+ return 0
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env python3
2
+ """Validates obd2.sim_scenario.v1 scenario files.
3
+
4
+ Checks:
5
+ - JSON parses and schema_version is obd2.sim_scenario.v1
6
+ - required fields present, synthetic is true
7
+ - scenario_id matches the file name
8
+ - command entries are well formed (request, chunks, delays, actions)
9
+ - prompt-terminated entries actually contain the prompt character
10
+ - stall entries have no chunks and no prompt
11
+ - expected_scan_summary uses only known keys
12
+ - stream_split_bytes is null or a positive integer
13
+
14
+ Exit 0 clean, 1 violations.
15
+ """
16
+
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ # The bundled example library, relative to this source file in the repo.
22
+ # (python/src/elmulator/validate.py -> repo root -> scenarios/)
23
+ BUNDLED_SCENARIOS = Path(__file__).resolve().parents[3] / "scenarios"
24
+
25
+ REQUIRED_FIELDS = {
26
+ "schema_version", "scenario_id", "synthetic", "description",
27
+ "adapter_profile", "defaults", "commands", "expected_scan_summary",
28
+ "warnings",
29
+ }
30
+ POST_ACTIONS = {"none", "stall", "disconnect"}
31
+ SUMMARY_KEYS = {
32
+ "stored_codes", "pending_codes", "permanent_codes", "mil_reported_on",
33
+ "vin_reported", "live_value_count", "min_session_warnings",
34
+ "no_stored_codes_observation", "scan_error",
35
+ }
36
+
37
+
38
+ def validate(path: Path) -> list:
39
+ problems = []
40
+ try:
41
+ scenario = json.loads(path.read_text(encoding="utf-8"))
42
+ except json.JSONDecodeError as error:
43
+ return [f"{path.name}: invalid JSON: {error}"]
44
+
45
+ missing = REQUIRED_FIELDS - scenario.keys()
46
+ if missing:
47
+ problems.append(f"{path.name}: missing fields {sorted(missing)}")
48
+ return problems
49
+
50
+ if scenario["schema_version"] != "obd2.sim_scenario.v1":
51
+ problems.append(f"{path.name}: unknown schema_version")
52
+ if scenario["synthetic"] is not True:
53
+ problems.append(f"{path.name}: synthetic must be true")
54
+ expected_id = path.name.removesuffix(".scenario.json")
55
+ if scenario["scenario_id"] != expected_id:
56
+ problems.append(f"{path.name}: scenario_id {scenario['scenario_id']!r} does not match file name")
57
+ if not scenario["description"].strip():
58
+ problems.append(f"{path.name}: empty description")
59
+
60
+ defaults = scenario["defaults"]
61
+ for key in ("at_response", "obd_response"):
62
+ if not defaults.get(key):
63
+ problems.append(f"{path.name}: defaults missing {key}")
64
+
65
+ split = scenario.get("stream_split_bytes")
66
+ if split is not None and (not isinstance(split, int) or split < 1):
67
+ problems.append(f"{path.name}: stream_split_bytes must be null or a positive integer")
68
+
69
+ if not scenario["commands"]:
70
+ problems.append(f"{path.name}: no commands")
71
+ for index, command in enumerate(scenario["commands"]):
72
+ label = f"{path.name} command {index}"
73
+ request = command.get("request", "")
74
+ if not request.strip():
75
+ problems.append(f"{label}: empty request")
76
+ chunks = command.get("response_chunks")
77
+ if not isinstance(chunks, list) or not all(isinstance(chunk, str) for chunk in chunks):
78
+ problems.append(f"{label}: response_chunks must be a list of strings")
79
+ continue
80
+ delay = command.get("delay_ms", 0)
81
+ if not isinstance(delay, int) or delay < 0:
82
+ problems.append(f"{label}: delay_ms must be a non-negative integer")
83
+ action = command.get("post_action", "none")
84
+ if action not in POST_ACTIONS:
85
+ problems.append(f"{label}: unknown post_action {action!r}")
86
+ prompt = command.get("prompt", True)
87
+ joined = "".join(chunks)
88
+ if action == "stall":
89
+ if chunks:
90
+ problems.append(f"{label}: stall entries must have no response_chunks")
91
+ if prompt:
92
+ problems.append(f"{label}: stall entries must set prompt false")
93
+ elif action == "disconnect":
94
+ if prompt and ">" not in joined:
95
+ problems.append(f"{label}: prompt true but no '>' before disconnect")
96
+ else:
97
+ if prompt and ">" not in joined:
98
+ problems.append(f"{label}: prompt true but chunks contain no '>'")
99
+ if not prompt and ">" in joined:
100
+ problems.append(f"{label}: prompt false but chunks contain '>'")
101
+
102
+ unknown = set(scenario["expected_scan_summary"].keys()) - SUMMARY_KEYS
103
+ if unknown:
104
+ problems.append(f"{path.name}: unknown expected_scan_summary keys {sorted(unknown)}")
105
+
106
+ return problems
107
+
108
+
109
+ def _collect(paths) -> list:
110
+ """Expand file and directory arguments into a sorted list of scenarios."""
111
+ files = []
112
+ for raw in paths:
113
+ path = Path(raw)
114
+ if path.is_dir():
115
+ files.extend(sorted(path.glob("*.scenario.json")))
116
+ else:
117
+ files.append(path)
118
+ return files
119
+
120
+
121
+ def run(paths=None) -> int:
122
+ """Entry point used by the `elmulator validate` CLI subcommand.
123
+
124
+ With no paths, validates the bundled example library (repo checkout).
125
+ """
126
+ if paths:
127
+ files = _collect(paths)
128
+ else:
129
+ files = sorted(BUNDLED_SCENARIOS.glob("*.scenario.json"))
130
+ if not files:
131
+ print("FAIL: no scenario paths given and no bundled examples found")
132
+ return 1
133
+
134
+ if not files:
135
+ print("FAIL: no scenario files found")
136
+ return 1
137
+
138
+ problems = []
139
+ for path in files:
140
+ problems.extend(validate(path))
141
+ if problems:
142
+ for problem in problems:
143
+ print(f"SCENARIO VALIDATION: {problem}")
144
+ print(f"FAIL: {len(problems)} problem(s)")
145
+ return 1
146
+ print(f"OK: {len(files)} scenario(s) validated")
147
+ return 0
148
+
149
+
150
+ def main() -> int:
151
+ return run(sys.argv[1:])
152
+
153
+
154
+ if __name__ == "__main__":
155
+ sys.exit(main())
@@ -0,0 +1,64 @@
1
+ """Smoke tests for the elmulator Python package.
2
+
3
+ Pure stdlib + pytest; no network fixtures beyond localhost loopback.
4
+ """
5
+
6
+ import socket
7
+ import threading
8
+ from pathlib import Path
9
+
10
+ from elmulator import Scenario, self_test
11
+ from elmulator import server as srv
12
+ from elmulator import validate as vld
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parents[2]
15
+ SCENARIOS = REPO_ROOT / "scenarios"
16
+
17
+
18
+ def test_self_test_passes():
19
+ assert self_test() == 0
20
+
21
+
22
+ def test_bundled_scenarios_validate():
23
+ assert vld.run([str(SCENARIOS)]) == 0
24
+
25
+
26
+ def test_normalize_is_case_and_space_insensitive():
27
+ assert srv.normalize(" at z \r") == "ATZ"
28
+ assert srv.normalize("0 1 0 0") == "0100"
29
+
30
+
31
+ def _args(**overrides):
32
+ import argparse
33
+ base = dict(host="127.0.0.1", port=0, echo="scenario",
34
+ split=None, latency_ms=0, jitter_ms=0, seed=0)
35
+ base.update(overrides)
36
+ return argparse.Namespace(**base)
37
+
38
+
39
+ def test_p0420_scan_over_tcp():
40
+ scenario = Scenario.from_path(SCENARIOS / "p0420_basic.scenario.json")
41
+ args = _args()
42
+ ready, stop = threading.Event(), threading.Event()
43
+ thread = threading.Thread(target=srv.serve, args=(args, scenario, ready, stop), daemon=True)
44
+ thread.start()
45
+ assert ready.wait(timeout=5)
46
+
47
+ def exchange(sock, command):
48
+ sock.sendall((command + "\r").encode("ascii"))
49
+ reply = ""
50
+ while ">" not in reply:
51
+ chunk = sock.recv(4096).decode("ascii")
52
+ if not chunk:
53
+ break
54
+ reply += chunk
55
+ return reply
56
+
57
+ try:
58
+ with socket.create_connection(("127.0.0.1", args.port), timeout=5) as sock:
59
+ assert "ELM327 v1.5" in exchange(sock, "ATZ")
60
+ assert "43 01 04 20" in exchange(sock, "03") # P0420 stored code bytes
61
+ assert "NO DATA" in exchange(sock, "0142") # falls through to default
62
+ finally:
63
+ stop.set()
64
+ thread.join(timeout=5)