Release v0.34.0 — Series-4 parity, and most of Blastware's report from the event file alone #59

Merged
serversdown merged 245 commits from dev into main 2026-11-04 18:19:24 -05:00
4 changed files with 233 additions and 3 deletions
Showing only changes of commit 06fa56db09 - Show all commits

No files matched your search

+34 -3
View File
@@ -12,16 +12,22 @@ from typing import Any, Callable, Dict, Optional
from .errors import ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
from .events import parse_event_id
from .locks import UnitLocks
from .models import ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo,
UnitSettings, UnitStatus)
from .s3 import Series3Adapter, default_s3_client_factory
from .s4 import (
Series4Session, default_s4_client_factory, s4_change_monitoring, s4_download_event, s4_identify, s4_list_events,
s4_settings, s4_status,
Series4Session, default_s4_client_factory, s4_call_home_state, s4_change_call_home, s4_change_monitoring,
s4_download_event, s4_identify, s4_list_events, s4_settings, s4_status,
)
from .series import normalise_serial, series_for_serial
log = logging.getLogger("sfm.device_access")
# A config write is read back at once, not after a sensor check: up to three
# reads, a second apart -- not the start/stop window.
_CALL_HOME_VERIFY_TIMEOUT_S = 3.0
_CALL_HOME_VERIFY_INTERVAL_S = 1.0
class DeviceAccess:
def __init__(
@@ -109,6 +115,31 @@ class DeviceAccess:
lambda c, s: s4_change_monitoring(c, s, address=address, **kw),
change=True)
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
return self._dispatch(address, serial,
lambda a, s: self._s3.call_home_state(a, s),
lambda c, s: s4_call_home_state(c, s))
def set_call_home(self, address: UnitAddress, serial: str, *, enabled: bool,
dry_run: bool = False, even_if_already: bool = False,
caller: str = "api") -> ChangeResult:
"""Turn the unit's automatic call-home on or off (spec row 9): audited,
identity-checked, never retried, read back."""
serial = normalise_serial(serial)
series_for_serial(serial) # BadRequest (422) before the audit check
if not dry_run and self._audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
kw = dict(enabled=enabled, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, caller=caller, sleep=self._sleep,
verify_timeout_s=_CALL_HOME_VERIFY_TIMEOUT_S,
verify_interval_s=_CALL_HOME_VERIFY_INTERVAL_S)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_call_home(a, s, **kw),
lambda c, s: s4_change_call_home(c, s, address=address, **kw),
change=True)
def held_serial(self, address: UnitAddress) -> Optional[str]:
"""Serial of the OPEN held Series-4 line at this address, else None. No I/O."""
with self._sessions_guard:
+59
View File
@@ -425,6 +425,7 @@ _SERIAL_AWARE_PATHS = frozenset({
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
"/device/events", "/device/events/download",
"/device/monitor/start", "/device/monitor/stop",
"/device/call_home/state", "/device/call_home/enable", "/device/call_home/disable",
})
@@ -2055,6 +2056,64 @@ def device_monitor_stop(
# ── Call home config endpoints ───────────────────────────────────────────────
@app.get("/device/call_home/state")
def device_call_home_state(
serial: str = Query(..., description=_SERIAL_DOC),
host: Optional[str] = Query(None, description="TCP host — modem IP"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
) -> dict:
"""The unit's call-home switch and dial string, by serial, both series (phase 4).
`enabled` is null when the enable byte is not a value ever measured;
`detail` keeps `byte5` and the whole block as read."""
return _via_device_access(lambda: _device_access().call_home_state(
_unit_address(port, baud, host, tcp_port), serial))
def _set_call_home(enabled: bool, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller):
return _change_response(lambda: _device_access().set_call_home(
_unit_address(port, baud, host, tcp_port), serial, enabled=enabled, dry_run=dry_run,
even_if_already=even_if_already, caller=caller or "api"))
@app.post("/device/call_home/enable")
def device_call_home_enable(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
serial: str = Query(..., description=_SERIAL_DOC),
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
even_if_already: bool = Query(False, description="Send even if call-home is already on"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
"""Turn the unit's automatic call-home ON (spec row 9), by serial, both series.
The same audited change as /device/monitor/start: identity read first (a
different unit is a 409, nothing sent), the 0x2C block read, one write that
changes only the enable byte (0x7E + 0x7F), never retried, then read back.
Statuses as /device/monitor/start; a change that went out but was not
confirmed carries `sent` and `audit_id`."""
return _set_call_home(True, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller)
@app.post("/device/call_home/disable")
def device_call_home_disable(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
serial: str = Query(..., description=_SERIAL_DOC),
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
even_if_already: bool = Query(False, description="Send even if call-home is already off"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
"""Turn the unit's automatic call-home OFF -- as /device/call_home/enable."""
return _set_call_home(False, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller)
@app.get("/device/call_home")
def device_call_home_get(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
+80
View File
@@ -0,0 +1,80 @@
"""DeviceAccess routes call-home by series (phase 4): a read, and an audited
change that is never retried, verified over a short config window (3 reads,
1 s apart), not the monitoring one."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import micromate.protocol as mm_proto # noqa: E402
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient, um12947_call_home # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import DeviceError # noqa: E402
from sfm.device_access.models import UnitAddress # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
class Audit:
def __init__(self):
self.rows = {}
def begin(self, **f):
cid = f"c{len(self.rows) + 1}"
self.rows[cid] = dict(f, outcome="pending")
return cid
def finish(self, cid, **f):
self.rows[cid].update(f)
def access(*, s4=None, s3=None, sleeps=None):
return DeviceAccess(s4_client_factory=lambda a, **kw: s4, s3_client_factory=lambda a, **kw: s3,
start_reaper=False, audit=Audit(),
sleep=(sleeps.append if sleeps is not None else (lambda s: None)),
verify_timeout_s=60.0, verify_interval_s=5.0)
def test_call_home_state_dispatches_by_series():
assert access(s4=FakeMicromateClient()).call_home_state(ADDR, "UM20147").series == 4
assert access(s3=FakeMiniMateClient()).call_home_state(TCP3, "BE18193").series == 3
def test_set_call_home_dispatches_by_series():
s4 = FakeMicromateClient()
r = access(s4=s4).set_call_home(ADDR, "UM20147", enabled=False)
assert (r.series, r.outcome, r.verified) == (4, "sent", "ok") and len(s4.executed) == 1
s3 = FakeMiniMateClient()
r = access(s3=s3).set_call_home(TCP3, "BE18193", enabled=False)
assert (r.series, r.outcome, r.verified) == (3, "sent", "ok") and s3.writes == ["call_home"]
def test_the_verify_window_is_the_config_one_not_the_monitoring_one():
sleeps = []
s4 = FakeMicromateClient()
s4.protocol.execute = lambda plan: [type("Ack", (), {"sub": st.ack_sub, "data": bytes(11)})()
for st in plan.steps] # acked, but nothing changes
r = access(s4=s4, sleeps=sleeps).set_call_home(ADDR, "UM20147", enabled=False)
assert (r.outcome, r.verified) == ("failed", "mismatch")
assert sleeps == [1.0, 1.0, 1.0]
def test_set_call_home_on_a_dropped_held_line_is_not_retried():
fake = FakeMicromateClient(call_home=um12947_call_home(True))
da = access(s4=fake)
da.status(ADDR, "UM20147") # hold the line
fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails
with pytest.raises(DeviceError): # the failure, not a retry
da.set_call_home(ADDR, "UM20147", enabled=False)
assert fake.executed == []
def test_a_dry_run_needs_no_audit():
da = DeviceAccess(s4_client_factory=lambda a, **kw: FakeMicromateClient(), start_reaper=False,
audit=None, sleep=lambda s: None)
assert da.set_call_home(ADDR, "UM20147", enabled=False, dry_run=True).outcome == "dry_run"
+60
View File
@@ -435,3 +435,63 @@ def test_device_commands_normalises_the_serial(tmp_path, monkeypatch):
action="start monitoring", tier="change", request={}, caller="test")
monkeypatch.setattr(srv, "_get_db", lambda: db)
assert len(srv.db_device_commands(serial=" um20147 ", limit=100)["commands"]) == 1
# ── call-home by serial (phase 4) ─────────────────────────────────────────────
from device_access_fakes import um12947_call_home # noqa: E402
CH_STATE = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034, serial="UM20147")
def test_call_home_state_route(monkeypatch):
_s4(monkeypatch, FakeMicromateClient())
st = srv.device_call_home_state(**CH_STATE)
assert (st["series"], st["enabled"], st["dial_string"]) == (4, True, "RADIO RING")
def test_enable_route_returns_the_change_result(monkeypatch):
_s4(monkeypatch, FakeMicromateClient(call_home=um12947_call_home(False)))
resp = srv.device_call_home_enable(**CH)
assert resp.status_code == 200 and _body(resp)["action"] == "enable call-home"
def test_disable_route_returns_the_change_result(monkeypatch):
_s4(monkeypatch, FakeMicromateClient())
resp = srv.device_call_home_disable(**CH)
assert resp.status_code == 200 and _body(resp)["state_after"] == "disabled"
def _asgi(method, path, query=""):
import asyncio
msgs = []
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(m):
msgs.append(m)
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method,
"scheme": "http", "path": path, "raw_path": path.encode(), "root_path": "",
"query_string": query.encode(), "headers": [(b"host", b"sfm.local")],
"server": ("sfm.local", 80), "client": ("127.0.0.1", 1)}
asyncio.run(srv.app(scope, receive, send))
return next(m for m in msgs if m["type"] == "http.response.start")["status"]
@pytest.mark.parametrize("method,path", [("GET", "/device/call_home/state"),
("POST", "/device/call_home/enable"),
("POST", "/device/call_home/disable")])
def test_call_home_routes_need_a_serial(method, path):
assert _asgi(method, path, "host=10.0.0.5&tcp_port=9034") == 422
def test_call_home_routes_are_serial_aware():
assert {"/device/call_home/state", "/device/call_home/enable",
"/device/call_home/disable"} <= srv._SERIAL_AWARE_PATHS
def test_legacy_call_home_post_still_refuses_a_micromate_serial():
refusal = srv._device_guard("/device/call_home", {"serial": "UM20147"})
assert refusal is not None and refusal[0] == 501