sme-sim-common 1.0.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.
- sme_sim_common/__init__.py +3 -0
- sme_sim_common/__pyinstaller/__init__.py +8 -0
- sme_sim_common/__pyinstaller/hook-sme_sim_common.py +14 -0
- sme_sim_common/behaviors.py +424 -0
- sme_sim_common/cli.py +104 -0
- sme_sim_common/config.py +132 -0
- sme_sim_common/engine.py +321 -0
- sme_sim_common/static/brand/company-logo.svg +2 -0
- sme_sim_common/static/i18n/common.js +131 -0
- sme_sim_common/static/shell/shell.css +243 -0
- sme_sim_common/static/shell/shell.js +511 -0
- sme_sim_common/static/vendor/vendor.js +76 -0
- sme_sim_common/templates.py +331 -0
- sme_sim_common/testing/__init__.py +91 -0
- sme_sim_common/testing/plugin.py +51 -0
- sme_sim_common/web.py +616 -0
- sme_sim_common/xlsx.py +455 -0
- sme_sim_common-1.0.0.dist-info/METADATA +229 -0
- sme_sim_common-1.0.0.dist-info/RECORD +23 -0
- sme_sim_common-1.0.0.dist-info/WHEEL +5 -0
- sme_sim_common-1.0.0.dist-info/entry_points.txt +5 -0
- sme_sim_common-1.0.0.dist-info/licenses/LICENSE +21 -0
- sme_sim_common-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""PyInstaller integration (``pyinstaller40`` entry point): products bundling sme-sim-common get its static
|
|
2
|
+
assets and the uvicorn / multipart hidden imports without listing them in their spec."""
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_hook_dirs():
|
|
8
|
+
return [os.path.dirname(__file__)]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# PyInstaller hook for sme_sim_common (found through the pyinstaller40 "hook-dirs" entry point).
|
|
2
|
+
# Mirrors what sme-bac-sim v0.4.0 packaging/sme-bacnet-sim.spec listed by hand for the web stack.
|
|
3
|
+
from PyInstaller.utils.hooks import collect_data_files, collect_submodules
|
|
4
|
+
|
|
5
|
+
datas = collect_data_files("sme_sim_common", includes=["static/**/*"])
|
|
6
|
+
|
|
7
|
+
hiddenimports = collect_submodules("uvicorn") + [
|
|
8
|
+
"multipart",
|
|
9
|
+
"python_multipart",
|
|
10
|
+
"yaml",
|
|
11
|
+
"h11",
|
|
12
|
+
"websockets",
|
|
13
|
+
"httptools",
|
|
14
|
+
]
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
# Shared by the SME simulators. Taken from sme-modbus-sim sme_modbus_sim/behaviors.py @ 085fe59
|
|
2
|
+
# (itself generalised from sme-bac-sim @ ebd27ec: Replay takes ``discrete`` / ``coerce`` hooks instead of
|
|
3
|
+
# BACnet object types). ``reserved_names`` / ``check_point_names`` come from sme-modbus-sim config.py @ 085fe59.
|
|
4
|
+
"""Value simulation behaviors and a restricted expression evaluator.
|
|
5
|
+
|
|
6
|
+
Expressions are plain Python expressions restricted to arithmetic, comparisons,
|
|
7
|
+
boolean logic, conditional expressions and a whitelist of functions. Names
|
|
8
|
+
refer to points of the same device (point name with non-identifier chars
|
|
9
|
+
replaced by ``_``); other devices are reachable with ``pv("Device", "point")``.
|
|
10
|
+
The engine supplies ``t`` (sim seconds), ``dt``, ``hour`` and ``pv`` in the name map
|
|
11
|
+
(``ENGINE_NAMES``); together with ``FUNCTIONS`` they are reserved (``reserved_names``).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
import bisect
|
|
18
|
+
import csv
|
|
19
|
+
import math
|
|
20
|
+
import random as _random
|
|
21
|
+
import re
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
|
|
25
|
+
|
|
26
|
+
_ALLOWED_NODES = (
|
|
27
|
+
ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare, ast.IfExp,
|
|
28
|
+
ast.Call, ast.Name, ast.Load, ast.Constant, ast.Tuple, ast.List,
|
|
29
|
+
ast.And, ast.Or, ast.Not, ast.USub, ast.UAdd,
|
|
30
|
+
ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.Pow,
|
|
31
|
+
ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def ident(name: str) -> str:
|
|
36
|
+
"""Point name -> expression identifier."""
|
|
37
|
+
s = re.sub(r"\W", "_", name)
|
|
38
|
+
return "_" + s if s[:1].isdigit() else s
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _clamp(v, lo, hi):
|
|
42
|
+
return max(lo, min(hi, v))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
FUNCTIONS: Dict[str, Any] = {
|
|
46
|
+
"sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "log": math.log,
|
|
47
|
+
"sqrt": math.sqrt, "pi": math.pi, "abs": abs, "min": min, "max": max, "round": round,
|
|
48
|
+
"int": int, "float": float, "bool": bool, "sum": sum, "clamp": _clamp,
|
|
49
|
+
"random": _random.random, "uniform": _random.uniform,
|
|
50
|
+
"noise": lambda a=1.0: _random.uniform(-a, a),
|
|
51
|
+
"gauss": lambda sigma=1.0: _random.gauss(0, sigma),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ExpressionError(ValueError):
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
ENGINE_NAMES: Tuple[str, ...] = ("t", "dt", "hour", "pv")
|
|
60
|
+
"""Names the engine puts into every expression's name map."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def reserved_names(extra: Iterable[str] = ()) -> set:
|
|
64
|
+
"""Identifiers a point may not take: ``ENGINE_NAMES`` + ``FUNCTIONS`` (+ product-specific ``extra``)."""
|
|
65
|
+
return set(ENGINE_NAMES) | set(FUNCTIONS) | set(extra)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def check_point_names(owner: str, names: Iterable[str], reserved: Optional[Iterable[str]] = None,
|
|
69
|
+
*, kind: str = "point") -> None:
|
|
70
|
+
"""Reject names whose expression identifier (``ident(name)``) collides with a reserved name.
|
|
71
|
+
|
|
72
|
+
``owner`` is used in the message (typically the device name); ``names`` is any iterable of
|
|
73
|
+
point / object names; ``kind`` is the noun used in the message (``"point"``, ``"object"`` ...).
|
|
74
|
+
"""
|
|
75
|
+
reserved = reserved_names() if reserved is None else set(reserved)
|
|
76
|
+
bad = [f"{n!r}" + (f" (as {ident(n)!r})" if ident(n) != n else "")
|
|
77
|
+
for n in names if ident(n) in reserved]
|
|
78
|
+
if bad:
|
|
79
|
+
raise ValueError(f"device {owner!r}: {kind} name {', '.join(bad)} is reserved in behavior expressions "
|
|
80
|
+
f"(reserved: {', '.join(sorted(reserved))}); rename the {kind}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def compile_expr(src: str) -> Callable[[Dict[str, Any]], Any]:
|
|
84
|
+
"""Compile a restricted expression; returns fn(names) -> value."""
|
|
85
|
+
try:
|
|
86
|
+
tree = ast.parse(str(src), mode="eval")
|
|
87
|
+
except SyntaxError as e:
|
|
88
|
+
raise ExpressionError(f"syntax error in {src!r}: {e.msg}") from None
|
|
89
|
+
for node in ast.walk(tree):
|
|
90
|
+
if not isinstance(node, _ALLOWED_NODES):
|
|
91
|
+
raise ExpressionError(f"not allowed in expression {src!r}: {type(node).__name__}")
|
|
92
|
+
if isinstance(node, ast.Name) and node.id.startswith("__"):
|
|
93
|
+
raise ExpressionError(f"dunder names not allowed in {src!r}")
|
|
94
|
+
if isinstance(node, ast.Call) and not isinstance(node.func, ast.Name):
|
|
95
|
+
raise ExpressionError(f"only plain function calls allowed in {src!r}")
|
|
96
|
+
code = compile(tree, "<expr>", "eval")
|
|
97
|
+
env = {"__builtins__": {}, **FUNCTIONS}
|
|
98
|
+
|
|
99
|
+
def run(names: Dict[str, Any]) -> Any:
|
|
100
|
+
return eval(code, env, names) # noqa: S307 - AST-whitelisted
|
|
101
|
+
|
|
102
|
+
return run
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Behavior:
|
|
106
|
+
"""Base class: step() returns the new value, or None to leave it unchanged."""
|
|
107
|
+
|
|
108
|
+
def __init__(self, spec: Dict[str, Any]):
|
|
109
|
+
self.spec = spec
|
|
110
|
+
|
|
111
|
+
def step(self, names: Dict[str, Any], current: float, dt: float) -> Optional[float]:
|
|
112
|
+
raise NotImplementedError
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class Sine(Behavior):
|
|
116
|
+
def __init__(self, spec):
|
|
117
|
+
super().__init__(spec)
|
|
118
|
+
self.lo, self.hi = float(spec.get("min", 0)), float(spec.get("max", 100))
|
|
119
|
+
self.period = float(spec.get("period", 60))
|
|
120
|
+
self.phase = float(spec.get("phase", 0))
|
|
121
|
+
self.noise = float(spec.get("noise", 0))
|
|
122
|
+
|
|
123
|
+
def step(self, names, current, dt):
|
|
124
|
+
mid, amp = (self.hi + self.lo) / 2, (self.hi - self.lo) / 2
|
|
125
|
+
v = mid + amp * math.sin(2 * math.pi * (names["t"] / self.period) + self.phase)
|
|
126
|
+
return v + (_random.uniform(-self.noise, self.noise) if self.noise else 0)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Random(Behavior):
|
|
130
|
+
def step(self, names, current, dt):
|
|
131
|
+
return _random.uniform(float(self.spec.get("min", 0)), float(self.spec.get("max", 100)))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class RandomWalk(Behavior):
|
|
135
|
+
def step(self, names, current, dt):
|
|
136
|
+
lo, hi = float(self.spec.get("min", 0)), float(self.spec.get("max", 100))
|
|
137
|
+
step = float(self.spec.get("step", (hi - lo) / 50))
|
|
138
|
+
v = (current if current is not None else (lo + hi) / 2) + _random.uniform(-step, step)
|
|
139
|
+
return _clamp(v, lo, hi)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class Expr(Behavior):
|
|
143
|
+
def __init__(self, spec):
|
|
144
|
+
super().__init__(spec)
|
|
145
|
+
self.fn = compile_expr(spec["expr"])
|
|
146
|
+
|
|
147
|
+
def step(self, names, current, dt):
|
|
148
|
+
return self.fn(names)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class Follow(Behavior):
|
|
152
|
+
"""First-order lag toward a target expression (e.g. room temperature)."""
|
|
153
|
+
|
|
154
|
+
def __init__(self, spec):
|
|
155
|
+
super().__init__(spec)
|
|
156
|
+
self.target = compile_expr(spec["target"])
|
|
157
|
+
self.tau = max(float(spec.get("tau", 60)), 1e-3)
|
|
158
|
+
self.noise = float(spec.get("noise", 0))
|
|
159
|
+
|
|
160
|
+
def step(self, names, current, dt):
|
|
161
|
+
target = float(self.target(names))
|
|
162
|
+
cur = target if current is None else float(current)
|
|
163
|
+
v = cur + (target - cur) * (1 - math.exp(-dt / self.tau))
|
|
164
|
+
return v + (_random.uniform(-self.noise, self.noise) if self.noise else 0)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class Ramp(Behavior):
|
|
168
|
+
"""Slew-rate limited tracking: moves toward ``target`` by at most ``rate`` units per (sim) second.
|
|
169
|
+
|
|
170
|
+
``target`` is an expression (a plain point name works too); ``rate`` is a number or an expression.
|
|
171
|
+
Typical use: a PCS active power output following its setpoint (kW/s).
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def __init__(self, spec):
|
|
175
|
+
super().__init__(spec)
|
|
176
|
+
self.target = compile_expr(spec["target"])
|
|
177
|
+
self.rate = compile_expr(spec.get("rate", 1))
|
|
178
|
+
|
|
179
|
+
def step(self, names, current, dt):
|
|
180
|
+
target = float(self.target(names))
|
|
181
|
+
if current is None:
|
|
182
|
+
return target
|
|
183
|
+
cur = float(current)
|
|
184
|
+
limit = abs(float(self.rate(names))) * dt
|
|
185
|
+
diff = target - cur
|
|
186
|
+
if abs(diff) <= limit:
|
|
187
|
+
return target
|
|
188
|
+
return cur + math.copysign(limit, diff)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class Counter(Behavior):
|
|
192
|
+
"""Integrates a rate expression (units per second), e.g. energy from power."""
|
|
193
|
+
|
|
194
|
+
def __init__(self, spec):
|
|
195
|
+
super().__init__(spec)
|
|
196
|
+
self.rate = compile_expr(spec.get("rate", 1))
|
|
197
|
+
|
|
198
|
+
def step(self, names, current, dt):
|
|
199
|
+
return float(current or 0) + float(self.rate(names)) * dt
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class Pulse(Behavior):
|
|
203
|
+
"""Pulse counter for accumulators: adds ``rate`` pulses per second (fractions carried over).
|
|
204
|
+
|
|
205
|
+
Wrapping (if any) is up to the product (e.g. a BACnet accumulator's max-pres-value).
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
def __init__(self, spec):
|
|
209
|
+
super().__init__(spec)
|
|
210
|
+
self.rate = compile_expr(spec.get("rate", 1))
|
|
211
|
+
self.frac = 0.0
|
|
212
|
+
|
|
213
|
+
def step(self, names, current, dt):
|
|
214
|
+
x = max(0.0, float(self.rate(names))) * dt + self.frac
|
|
215
|
+
n = math.floor(x)
|
|
216
|
+
self.frac = x - n
|
|
217
|
+
return int(current or 0) + n
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# --------------------------------------------------------------------------- CSV replay
|
|
221
|
+
|
|
222
|
+
_HMS = re.compile(r"^(\d+):([0-5]?\d)(?::([0-5]?\d(?:\.\d*)?))?$")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def parse_elapsed(value: Any) -> Optional[float]:
|
|
226
|
+
"""``HH:MM:SS`` / ``HH:MM`` / plain seconds -> seconds; None if it is neither."""
|
|
227
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
228
|
+
return float(value)
|
|
229
|
+
s = str(value).strip()
|
|
230
|
+
m = _HMS.match(s)
|
|
231
|
+
if m:
|
|
232
|
+
return int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3) or 0)
|
|
233
|
+
try:
|
|
234
|
+
v = float(s)
|
|
235
|
+
except ValueError:
|
|
236
|
+
return None
|
|
237
|
+
return v if math.isfinite(v) else None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def parse_iso(value: Any) -> Optional[float]:
|
|
241
|
+
"""ISO 8601 datetime -> epoch seconds; None if it is not one."""
|
|
242
|
+
try:
|
|
243
|
+
return datetime.fromisoformat(str(value).strip().replace("Z", "+00:00")).timestamp()
|
|
244
|
+
except ValueError:
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def fmt_elapsed(sec: float) -> str:
|
|
249
|
+
sec = int(sec)
|
|
250
|
+
return f"{sec // 3600:02d}:{sec // 60 % 60:02d}:{sec % 60:02d}"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class ReplayTable:
|
|
254
|
+
"""A parsed replay CSV: times relative to the first row (seconds) and one value list per column."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, path: Path):
|
|
257
|
+
self.path = path
|
|
258
|
+
try:
|
|
259
|
+
with open(path, newline="", encoding="utf-8-sig") as f:
|
|
260
|
+
rows = [r for r in csv.reader(f) if any(c.strip() for c in r)]
|
|
261
|
+
except OSError as e:
|
|
262
|
+
raise ValueError(f"replay: cannot read {path}: {e.strerror or e}") from None
|
|
263
|
+
if len(rows) < 2:
|
|
264
|
+
raise ValueError(f"replay: {path}: needs a header row and at least one data row")
|
|
265
|
+
header = [h.strip() for h in rows[0]]
|
|
266
|
+
if len(header) < 2:
|
|
267
|
+
raise ValueError(f"replay: {path}: needs a timestamp column and at least one value column")
|
|
268
|
+
self.columns: Dict[str, List[Any]] = {h: [] for h in header[1:] if h}
|
|
269
|
+
times: List[float] = []
|
|
270
|
+
self.iso = parse_elapsed(rows[1][0]) is None # format decided by the first data row
|
|
271
|
+
for n, row in enumerate(rows[1:], start=2):
|
|
272
|
+
cell = row[0].strip() if row else ""
|
|
273
|
+
t = parse_iso(cell) if self.iso else parse_elapsed(cell)
|
|
274
|
+
if t is None:
|
|
275
|
+
kind = "an ISO datetime" if self.iso else "HH:MM:SS or seconds"
|
|
276
|
+
raise ValueError(f"replay: {path} line {n}: bad timestamp {cell!r} (expected {kind})")
|
|
277
|
+
if times and t < times[-1]:
|
|
278
|
+
raise ValueError(f"replay: {path} line {n}: timestamp {cell!r} goes backwards")
|
|
279
|
+
times.append(t)
|
|
280
|
+
for i, h in enumerate(header[1:], start=1):
|
|
281
|
+
if not h:
|
|
282
|
+
continue
|
|
283
|
+
raw = row[i].strip() if i < len(row) else ""
|
|
284
|
+
col = self.columns[h]
|
|
285
|
+
if raw == "":
|
|
286
|
+
if not col:
|
|
287
|
+
raise ValueError(f"replay: {path} line {n}: column {h!r} has no value")
|
|
288
|
+
col.append(col[-1]) # an empty cell holds the previous value
|
|
289
|
+
continue
|
|
290
|
+
try:
|
|
291
|
+
col.append(float(raw))
|
|
292
|
+
except ValueError:
|
|
293
|
+
col.append(raw) # non-numeric text (e.g. enum labels); converted by ``coerce``
|
|
294
|
+
self.t0 = times[0]
|
|
295
|
+
self.times = [t - self.t0 for t in times]
|
|
296
|
+
self.duration = self.times[-1]
|
|
297
|
+
|
|
298
|
+
def column(self, name: str) -> List[Any]:
|
|
299
|
+
if name not in self.columns:
|
|
300
|
+
raise ValueError(f"replay: {self.path}: no column {name!r} (columns: {', '.join(self.columns)})")
|
|
301
|
+
return self.columns[name]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
_TABLES: Dict[Path, Tuple[Tuple[float, int], ReplayTable]] = {}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def load_table(path: Path) -> ReplayTable:
|
|
308
|
+
"""Parse a replay CSV once per path (shared by all points); re-parsed when the file changes."""
|
|
309
|
+
path = path.resolve()
|
|
310
|
+
try:
|
|
311
|
+
st = path.stat()
|
|
312
|
+
except OSError as e:
|
|
313
|
+
raise ValueError(f"replay: cannot read {path}: {e.strerror or e}") from None
|
|
314
|
+
sig = (st.st_mtime, st.st_size)
|
|
315
|
+
hit = _TABLES.get(path)
|
|
316
|
+
if hit and hit[0] == sig:
|
|
317
|
+
return hit[1]
|
|
318
|
+
table = ReplayTable(path)
|
|
319
|
+
_TABLES[path] = (sig, table)
|
|
320
|
+
return table
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class Replay(Behavior):
|
|
324
|
+
"""Plays one column of a CSV time series on the simulation clock.
|
|
325
|
+
|
|
326
|
+
Replay time 0 is the first row. It advances with the simulated time (so it follows
|
|
327
|
+
``simulation.time_scale``), starts at ``offset`` and optionally loops; past the end without
|
|
328
|
+
``loop`` the last value is held. ``discrete`` points (e.g. bool / bit / enum / binary /
|
|
329
|
+
multi-state) always step-hold; ``coerce`` (optional) converts each produced value to the point's
|
|
330
|
+
datatype (e.g. label -> enum int, ``active`` -> 1). Both are decided by the product from its point model.
|
|
331
|
+
"""
|
|
332
|
+
|
|
333
|
+
def __init__(self, spec, base_dir: Optional[Path] = None, discrete: bool = False,
|
|
334
|
+
coerce: Optional[Callable[[Any], Any]] = None):
|
|
335
|
+
super().__init__(spec)
|
|
336
|
+
p = Path(str(spec["file"]))
|
|
337
|
+
if not p.is_absolute():
|
|
338
|
+
p = (base_dir or Path.cwd()) / p
|
|
339
|
+
self.table = load_table(p)
|
|
340
|
+
self.values = self.table.column(str(spec["column"]))
|
|
341
|
+
mode = str(spec.get("interpolate", "linear")).lower()
|
|
342
|
+
if mode not in ("linear", "step"):
|
|
343
|
+
raise ValueError(f"replay: interpolate must be 'linear' or 'step', got {mode!r}")
|
|
344
|
+
self.coerce = coerce
|
|
345
|
+
self.linear = mode == "linear" and not discrete
|
|
346
|
+
self.loop = bool(spec.get("loop", False))
|
|
347
|
+
off = spec.get("offset", 0)
|
|
348
|
+
o = parse_elapsed(off)
|
|
349
|
+
if o is None:
|
|
350
|
+
iso = parse_iso(off)
|
|
351
|
+
if iso is None:
|
|
352
|
+
raise ValueError(f"replay: bad offset {off!r} (HH:MM:SS, seconds or an ISO datetime)")
|
|
353
|
+
if not self.table.iso:
|
|
354
|
+
raise ValueError("replay: an ISO datetime offset needs a CSV with ISO timestamps")
|
|
355
|
+
o = iso - self.table.t0
|
|
356
|
+
self.offset = max(0.0, o)
|
|
357
|
+
self.start: Optional[float] = None
|
|
358
|
+
self.pos = min(self.offset, self.table.duration)
|
|
359
|
+
|
|
360
|
+
def position(self, t: float) -> float:
|
|
361
|
+
"""Simulated time -> replay time (seconds from the first row)."""
|
|
362
|
+
pos = self.offset + (t - self.start)
|
|
363
|
+
dur = self.table.duration
|
|
364
|
+
if self.loop and dur > 0:
|
|
365
|
+
return pos % dur
|
|
366
|
+
return min(pos, dur)
|
|
367
|
+
|
|
368
|
+
def value_at(self, pos: float) -> Any:
|
|
369
|
+
times, vals = self.table.times, self.values
|
|
370
|
+
i = max(0, bisect.bisect_right(times, pos) - 1)
|
|
371
|
+
if i >= len(times) - 1 or not self.linear:
|
|
372
|
+
return vals[i]
|
|
373
|
+
a, b = vals[i], vals[i + 1]
|
|
374
|
+
t0, t1 = times[i], times[i + 1]
|
|
375
|
+
if not isinstance(a, float) or not isinstance(b, float) or t1 <= t0:
|
|
376
|
+
return a
|
|
377
|
+
return a + (b - a) * (pos - t0) / (t1 - t0)
|
|
378
|
+
|
|
379
|
+
def step(self, names, current, dt):
|
|
380
|
+
if self.start is None:
|
|
381
|
+
self.start = names["t"] - dt # replay time `offset` = when the behavior started
|
|
382
|
+
self.pos = self.position(names["t"])
|
|
383
|
+
v = self.value_at(self.pos)
|
|
384
|
+
return self.coerce(v) if self.coerce else v
|
|
385
|
+
|
|
386
|
+
def progress(self) -> Dict[str, Any]:
|
|
387
|
+
dur = self.table.duration
|
|
388
|
+
return {"t": fmt_elapsed(self.pos), "pct": int(100 * self.pos / dur) if dur > 0 else 100}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
BEHAVIORS = {
|
|
392
|
+
"sine": Sine,
|
|
393
|
+
"random": Random,
|
|
394
|
+
"random_walk": RandomWalk,
|
|
395
|
+
"expr": Expr,
|
|
396
|
+
"follow": Follow,
|
|
397
|
+
"ramp": Ramp,
|
|
398
|
+
"counter": Counter,
|
|
399
|
+
"pulse": Pulse,
|
|
400
|
+
"replay": Replay,
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def make_behavior(spec: Optional[Dict[str, Any]], base_dir: Optional[Path] = None,
|
|
405
|
+
discrete: bool = False, coerce: Optional[Callable[[Any], Any]] = None) -> Optional[Behavior]:
|
|
406
|
+
"""Build a behavior; ``base_dir`` resolves relative replay files (the config file's directory).
|
|
407
|
+
|
|
408
|
+
``discrete`` / ``coerce`` only affect ``replay`` (step-hold and value conversion for the point's datatype;
|
|
409
|
+
the product derives both from its own point model).
|
|
410
|
+
"""
|
|
411
|
+
if not spec:
|
|
412
|
+
return None
|
|
413
|
+
kind = spec.get("type")
|
|
414
|
+
if kind in (None, "none", "static"):
|
|
415
|
+
return None
|
|
416
|
+
cls = BEHAVIORS.get(kind)
|
|
417
|
+
if cls is None:
|
|
418
|
+
raise ValueError(f"unknown behavior type: {kind!r} (known: {', '.join(BEHAVIORS)})")
|
|
419
|
+
try:
|
|
420
|
+
if cls is Replay:
|
|
421
|
+
return Replay(spec, base_dir, discrete, coerce)
|
|
422
|
+
return cls(spec)
|
|
423
|
+
except KeyError as e:
|
|
424
|
+
raise ValueError(f"behavior {kind!r} missing parameter {e}") from None
|
sme_sim_common/cli.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Command line helpers shared by the simulators (design §7.1).
|
|
2
|
+
|
|
3
|
+
Generalised from sme-modbus-sim 085fe59 ``__main__.py`` (``--http-port`` / ``--no-browser`` / ``--templates-dir``
|
|
4
|
+
/ ``validate``) and sme-bac-sim v0.4.0 ``__main__.py`` (``--port``, kept as a hidden alias).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
import webbrowser
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Callable, Optional, Sequence
|
|
15
|
+
|
|
16
|
+
__all__ = ["LOCAL_HOSTS", "add_common_args", "browser_url", "run_web", "add_validate_args", "run_validate"]
|
|
17
|
+
|
|
18
|
+
LOCAL_HOSTS = ("127.0.0.1", "localhost", "::1")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def add_common_args(ap: argparse.ArgumentParser, *, default_http_port: int, app_name: str,
|
|
22
|
+
version: Optional[str] = None, templates: bool = True,
|
|
23
|
+
open_browser: bool = True) -> argparse.ArgumentParser:
|
|
24
|
+
"""Add ``-c/--config``, ``--host`` (127.0.0.1), ``--http-port`` (hidden alias ``--port``), ``--no-browser`` /
|
|
25
|
+
``--browser``, ``--version``, ``-v/--verbose`` and (``templates=True``) ``--templates-dir``. The product passes
|
|
26
|
+
its own default port (series port table in the README); ``app_name`` is the dist name (``sme-modbus-sim``).
|
|
27
|
+
``open_browser`` is the default of ``args.no_browser`` (inverted): ``False`` = only ``--browser`` opens it."""
|
|
28
|
+
if version is not None:
|
|
29
|
+
ap.add_argument("--version", action="version", version=f"{app_name} {version}")
|
|
30
|
+
ap.add_argument("-c", "--config", help="YAML / JSON config file")
|
|
31
|
+
ap.add_argument("--host", default="127.0.0.1", help="web UI host (use 0.0.0.0 to expose on the LAN)")
|
|
32
|
+
ap.add_argument("--http-port", dest="http_port", type=int, default=default_http_port,
|
|
33
|
+
help=f"web UI port (default {default_http_port})")
|
|
34
|
+
ap.add_argument("--port", dest="http_port", type=int, default=argparse.SUPPRESS, help=argparse.SUPPRESS)
|
|
35
|
+
grp = ap.add_mutually_exclusive_group()
|
|
36
|
+
grp.add_argument("--no-browser", dest="no_browser", action="store_true",
|
|
37
|
+
help="do not open the web UI in a browser" + (" (default)" if not open_browser else ""))
|
|
38
|
+
grp.add_argument("--browser", dest="no_browser", action="store_false",
|
|
39
|
+
help="open the web UI in a browser" + (" (default)" if open_browser else ""))
|
|
40
|
+
ap.set_defaults(no_browser=not open_browser)
|
|
41
|
+
if templates:
|
|
42
|
+
from .templates import env_var_for
|
|
43
|
+
|
|
44
|
+
env = env_var_for(app_name)
|
|
45
|
+
ap.add_argument("--templates-dir",
|
|
46
|
+
help=f"user template directory (default: ${env} or ~/.{app_name}/templates)")
|
|
47
|
+
ap.add_argument("-v", "--verbose", action="store_true", help="debug logging")
|
|
48
|
+
return ap
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def browser_url(host: str, port: int) -> str:
|
|
52
|
+
"""URL to open locally for a bind address (a wildcard bind is opened on 127.0.0.1)."""
|
|
53
|
+
h = "127.0.0.1" if host in ("0.0.0.0", "::", "") else host
|
|
54
|
+
if ":" in h and not h.startswith("["):
|
|
55
|
+
h = f"[{h}]"
|
|
56
|
+
return f"http://{h}:{port}/"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def run_web(app: Any, args: argparse.Namespace, *, name: Optional[str] = None, delay: float = 1.5) -> None:
|
|
60
|
+
"""Serve ``app`` with uvicorn (``log_level="warning"``) on ``args.host`` / ``args.http_port``.
|
|
61
|
+
|
|
62
|
+
Prints the URL, warns when the host is not loopback (the UI has no authentication) and opens the browser
|
|
63
|
+
unless ``--no-browser``."""
|
|
64
|
+
import uvicorn
|
|
65
|
+
|
|
66
|
+
url = browser_url(args.host, args.http_port)
|
|
67
|
+
print(f"{name + ' ' if name else ''}web UI: {url}", flush=True)
|
|
68
|
+
if args.host not in LOCAL_HOSTS:
|
|
69
|
+
print(f"WARNING: the web UI listens on {args.host}, reachable from other hosts; it has no "
|
|
70
|
+
f"authentication. Use --host 127.0.0.1 unless you need LAN access.", file=sys.stderr, flush=True)
|
|
71
|
+
if not getattr(args, "no_browser", False):
|
|
72
|
+
threading.Timer(delay, lambda: webbrowser.open(url)).start()
|
|
73
|
+
uvicorn.run(app, host=args.host, port=args.http_port, log_level="warning")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def add_validate_args(ap: argparse.ArgumentParser, *, templates: bool = True) -> argparse.ArgumentParser:
|
|
77
|
+
"""Arguments of the ``validate CONFIG`` subcommand."""
|
|
78
|
+
ap.add_argument("config", help="YAML / JSON config file to check")
|
|
79
|
+
if templates:
|
|
80
|
+
ap.add_argument("--templates-dir", help="user template directory")
|
|
81
|
+
return ap
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def run_validate(argv: Sequence[str], *, prog: str, load: Callable[[Path], Any],
|
|
85
|
+
build: Optional[Callable[[Any, Path], Any]] = None,
|
|
86
|
+
before: Optional[Callable[[argparse.Namespace], None]] = None,
|
|
87
|
+
summary: Optional[Callable[[Any], str]] = None) -> int:
|
|
88
|
+
"""``<prog> validate CONFIG``: ``load(path)`` the config, then ``build(cfg, path)`` once (e.g. construct the
|
|
89
|
+
Engine to compile behaviors). Returns 0 when valid, 2 on a config error (message on stderr).
|
|
90
|
+
``before(args)`` runs first (e.g. load user templates from ``--templates-dir``)."""
|
|
91
|
+
ap = add_validate_args(argparse.ArgumentParser(prog=f"{prog} validate", description="check a config file"))
|
|
92
|
+
args = ap.parse_args(list(argv))
|
|
93
|
+
path = Path(args.config)
|
|
94
|
+
try:
|
|
95
|
+
if before is not None:
|
|
96
|
+
before(args)
|
|
97
|
+
cfg = load(path)
|
|
98
|
+
if build is not None:
|
|
99
|
+
build(cfg, path)
|
|
100
|
+
except Exception as e: # file, YAML, validation or build error
|
|
101
|
+
print(f"{path}: invalid\n{e}", file=sys.stderr)
|
|
102
|
+
return 2
|
|
103
|
+
print(f"{path}: OK" + (f" ({summary(cfg)})" if summary else ""))
|
|
104
|
+
return 0
|