feat(sfm): start/stop monitoring for Series 3 through the same safety layer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
78c3d568d5
commit
ce5d2cb0d6
5 files changed
+332
-106
No files matched your search
+14
-99
@@ -20,6 +20,7 @@ from .errors import (
|
||||
AuditUnavailable, CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent,
|
||||
UnitStateUnknown, WrongUnit, translate,
|
||||
)
|
||||
from .change import CALL_HOME_MESSAGE, run_change
|
||||
from .events import iso_of, make_event_id, stamp_of
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
from .series import normalise_serial
|
||||
@@ -104,8 +105,7 @@ def _close(client: Any) -> None:
|
||||
log.debug("close failed", exc_info=True)
|
||||
|
||||
|
||||
_RING_MESSAGE = ("the unit started calling home; SFM hung up so the call can "
|
||||
"reach THOR -- try again in a few minutes")
|
||||
_RING_MESSAGE = CALL_HOME_MESSAGE
|
||||
|
||||
|
||||
class Series4Session:
|
||||
@@ -325,104 +325,19 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
even_if_already: bool, audit: Any, address: UnitAddress,
|
||||
caller: str, sleep: Callable[[float], None],
|
||||
verify_timeout_s: float, verify_interval_s: float) -> ChangeResult:
|
||||
"""Identity -> state -> (dry run | skip | audit -> send -> read back -> audit)."""
|
||||
action = "start monitoring" if start else "stop monitoring"
|
||||
want = "monitoring" if start else "idle"
|
||||
|
||||
reported = normalise_serial(client.serial(refresh=True))
|
||||
if reported != serial:
|
||||
raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- "
|
||||
"nothing sent")
|
||||
before = client.read_run_state()
|
||||
if before.name == "calling_home":
|
||||
raise CallHomeInProgress(_RING_MESSAGE)
|
||||
if before.name.startswith("unknown") and not dry_run:
|
||||
raise UnitStateUnknown(f"the unit reports run state {before.name}, which has never "
|
||||
"been measured -- nothing sent")
|
||||
"""Series-4 pieces for the shared core in change.py."""
|
||||
plan = plan_start_monitoring() if start else plan_stop_monitoring()
|
||||
planned = dict(plan.describe(), sends_nothing=dry_run)
|
||||
base = dict(serial=serial, series=4, action=action, plan=planned,
|
||||
state_before=before.name)
|
||||
|
||||
if dry_run:
|
||||
return ChangeResult(dry_run=True, sent=False, outcome="dry_run",
|
||||
verified="not_checked", state_after=None, audit_id=None, **base)
|
||||
if audit is None:
|
||||
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
|
||||
"without one (nothing sent)")
|
||||
request = {"plan": planned, "even_if_already": even_if_already}
|
||||
try:
|
||||
cid = audit.begin(serial=serial, series=4, address=address.key, action=action,
|
||||
tier="change", request=request, caller=caller)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise AuditUnavailable(
|
||||
f"the audit log could not be written -- nothing sent: {exc}") from exc
|
||||
if before.name == want and not even_if_already:
|
||||
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None,
|
||||
error=f"already {want}")
|
||||
return ChangeResult(dry_run=False, sent=False, outcome="skipped",
|
||||
verified="not_checked", state_after=before.name,
|
||||
audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base)
|
||||
|
||||
try:
|
||||
def send() -> dict:
|
||||
acks = client.protocol.execute(plan)
|
||||
except OpcodeRefused as exc: # refused by the gate: nothing went out
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"refused before sending: {exc}")
|
||||
raise
|
||||
except RingDetected as exc:
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"a call-home began in place of the ack: {exc}")
|
||||
raise # _exchange releases the line
|
||||
except Exception as exc: # noqa: BLE001 -- recorded, never retried
|
||||
try:
|
||||
after = _try_run_state(client)
|
||||
except RingDetected as ring:
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; a call-home began: {ring}")
|
||||
raise
|
||||
if after == "calling_home":
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; the unit is now calling home")
|
||||
raise CallHomeInProgress(_RING_MESSAGE) from exc
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}")
|
||||
if after is None:
|
||||
raise # the line is suspect: let _exchange hang up
|
||||
return ChangeResult(dry_run=False, sent=True, outcome="failed",
|
||||
verified="not_checked", state_after=after, audit_id=cid,
|
||||
detail={"error": f"no clean ack: {exc}"}, **base)
|
||||
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
||||
|
||||
ack = {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
||||
seen = [before.name]
|
||||
polls = int(verify_timeout_s // verify_interval_s)
|
||||
try:
|
||||
for _ in range(polls):
|
||||
sleep(verify_interval_s)
|
||||
seen.append(client.read_run_state().name)
|
||||
if seen[-1] == want or seen[-1] == "calling_home":
|
||||
break
|
||||
except Exception as exc: # noqa: BLE001 -- the row must not stay pending
|
||||
audit.finish(cid, outcome="sent", verified="not_checked", ack=ack,
|
||||
error=f"sent and acknowledged; reading the state back failed: {exc}")
|
||||
raise
|
||||
if seen[-1] == "calling_home":
|
||||
audit.finish(cid, outcome="sent", verified="not_checked", ack=ack,
|
||||
error="sent and acknowledged; the unit then began calling home")
|
||||
raise CallHomeInProgress(_RING_MESSAGE)
|
||||
ok = seen[-1] == want
|
||||
outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch")
|
||||
audit.finish(cid, outcome=outcome, verified=verified, ack=ack,
|
||||
error=None if ok else f"unit reads {seen[-1]}, expected {want}")
|
||||
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
|
||||
state_after=seen[-1], audit_id=cid,
|
||||
detail={"states_seen": seen, "ack": ack}, **base)
|
||||
|
||||
|
||||
def _try_run_state(client: Any) -> Optional[str]:
|
||||
try:
|
||||
return client.read_run_state().name
|
||||
except RingDetected:
|
||||
raise
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return run_change(
|
||||
serial=serial, series=4, start=start, dry_run=dry_run, even_if_already=even_if_already,
|
||||
audit=audit, address=address, caller=caller, sleep=sleep,
|
||||
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=lambda: client.serial(refresh=True),
|
||||
read_state=lambda: client.read_run_state().name,
|
||||
describe_plan=plan.describe, send=send,
|
||||
is_refusal=lambda e: isinstance(e, OpcodeRefused),
|
||||
is_ring=lambda e: isinstance(e, RingDetected))
|
||||
Reference in new issue
Block a user