s4_change_settings runs the shared change core with a read-back verdict for its state (as asked / unchanged / differs). It reads the active setup's name (unstripped), the preferences, trigger and setup blocks and the schedule; patches the setup through micromate.setup_fields; sends THOR's setup push (0xDA 68 73 82 83 71 72, now enableable) once; reads the setup back. Refused before sending: a monitoring unit, a value the unit does not allow (422), a stale preview (SettingsChanged, 409), and -- shown as 'blocked' in the preview -- the factory setup, a schedule that loads another setup, an unreadable schedule, or a block SFM has not seen (ChangeRefused, 409). s4_settings carries the editable fields. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
583 lines
27 KiB
Python
583 lines
27 KiB
Python
"""Series-4 sessions: call up once, stay on the line, hang up when idle.
|
|
|
|
⚠ **This module hosts a write path.** `s4_change_monitoring` is the Series-4
|
|
wrapper of the shared change core (`change.run_change`): it sends `0x96` /
|
|
`0x97` through `MicromateProtocol.execute()`, and it is the only caller of
|
|
`.protocol.execute(` in the codebase (a test pins that). Everything else here
|
|
is a read.
|
|
|
|
⚠ Imports only minimateplus.transport from the Series-3 package. Nothing
|
|
here may build or send a Series-3 frame -- SESSION_RESET (41 03) has never
|
|
been sent to a Micromate.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import time
|
|
from typing import Any, Callable, Optional, TypeVar
|
|
|
|
from micromate.client import MicromateClient
|
|
from micromate.opcodes import OpcodeRefused
|
|
from micromate.protocol import THOR_CHUNK_SIZE
|
|
from micromate.protocol import ProtocolError as _MMProtocolError
|
|
from micromate.schedule import parse_schedule, schedule_conflicts
|
|
from micromate.setup_block import decode_setup
|
|
from micromate.setup_fields import (
|
|
SettingsValueError, check_changes, editable_fields, encode_setup, field_rows, settings_state,
|
|
)
|
|
from micromate.setup_fields import revision as settings_revision
|
|
from micromate.writes import (
|
|
is_call_home_content, plan_call_home_enabled, plan_setup_push, plan_start_monitoring,
|
|
plan_stop_monitoring,
|
|
)
|
|
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
|
|
|
|
from .errors import (
|
|
AuditIncomplete, BadRequest, CallHomeInProgress, ChangeRefused, ChangeUnconfirmed, DeviceError,
|
|
EventNotFound, MalformedReply, SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit,
|
|
translate,
|
|
)
|
|
from .change import (
|
|
CALL_HOME_MESSAGE, call_home_change, monitoring_change, run_change, settings_change,
|
|
)
|
|
from .events import iso_of, make_event_id, stamp_of
|
|
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
|
|
UnitInfo, UnitSettings, UnitStatus)
|
|
from .series import normalise_serial
|
|
|
|
log = logging.getLogger("sfm.device_access")
|
|
|
|
T = TypeVar("T")
|
|
RING = b"RADIO RING"
|
|
S4_DEFAULT_BAUD = 115200
|
|
|
|
|
|
class RingDetected(Exception):
|
|
"""The unit sent RADIO RING: it is calling home up this connection."""
|
|
|
|
|
|
class RingWatchTransport(BaseTransport):
|
|
"""Passes bytes through; raises RingDetected the moment RADIO RING appears
|
|
OUTSIDE a frame, including when it is split across two reads.
|
|
|
|
Inside a frame the bytes are data: the 0x2C call-home config block's dial
|
|
string is literally "RADIO RING". A frame runs from STX to an unescaped
|
|
ETX; inside it DLE escapes the next byte.
|
|
"""
|
|
|
|
_STX, _ETX, _DLE = 0x02, 0x03, 0x10
|
|
|
|
def __init__(self, inner: BaseTransport) -> None:
|
|
self._inner = inner
|
|
self._tail = b""
|
|
self._in_frame = False
|
|
self._escaped = False
|
|
|
|
def connect(self) -> None:
|
|
self._inner.connect()
|
|
|
|
def disconnect(self) -> None:
|
|
self._inner.disconnect()
|
|
|
|
@property
|
|
def is_connected(self) -> bool:
|
|
return self._inner.is_connected
|
|
|
|
def write(self, data: bytes) -> None:
|
|
# A request starts a new exchange (MicromateProtocol resets its parser
|
|
# here too), so a stray STX on an idle line cannot hide the next ring.
|
|
self._in_frame = self._escaped = False
|
|
self._inner.write(data)
|
|
|
|
def read(self, n: int) -> bytes:
|
|
data = self._inner.read(n)
|
|
for b in data:
|
|
if self._in_frame:
|
|
if self._escaped:
|
|
self._escaped = False
|
|
elif b == self._DLE:
|
|
self._escaped = True
|
|
elif b == self._ETX:
|
|
self._in_frame = False
|
|
elif b == self._STX:
|
|
self._in_frame = True
|
|
self._tail = b""
|
|
else:
|
|
self._tail = (self._tail + bytes([b]))[-len(RING):]
|
|
if self._tail == RING:
|
|
self._tail = b""
|
|
raise RingDetected("RADIO RING")
|
|
return data
|
|
|
|
|
|
def default_s4_client_factory(address: UnitAddress, recv_timeout: float = 10.0) -> MicromateClient:
|
|
if address.host:
|
|
inner: BaseTransport = TcpTransport(address.host, port=address.tcp_port)
|
|
else:
|
|
inner = SerialTransport(address.port, address.baud or S4_DEFAULT_BAUD)
|
|
return MicromateClient(RingWatchTransport(inner), recv_timeout=recv_timeout)
|
|
|
|
|
|
def _close(client: Any) -> None:
|
|
try:
|
|
client.close()
|
|
except Exception: # noqa: BLE001
|
|
log.debug("close failed", exc_info=True)
|
|
|
|
|
|
_RING_MESSAGE = CALL_HOME_MESSAGE
|
|
|
|
|
|
class Series4Session:
|
|
"""One held line to one Micromate.
|
|
|
|
`last_used` is the last *user* request: the idle hang-up measures it.
|
|
`last_traffic` is any exchange, keep-alives included: the keep-alive
|
|
schedule measures it. If keep-alives counted as use, the line would never
|
|
go idle.
|
|
|
|
Invariant -- which errors keep the line. An operation raises a
|
|
`DeviceError` only for a verdict reached over a healthy link: the event is
|
|
not there, the id is stale, the record cannot be named. `_exchange` keeps
|
|
the line for those. Anything the library raises means the link is
|
|
suspect, and `_exchange` hangs up. `DecodeMismatch` is a library error,
|
|
so it hangs up too -- conservative, since the link may be fine. Operations
|
|
added in later phases must keep to this: never wrap a link failure in a
|
|
`DeviceError` inside an op, or the line stays open on a broken link.
|
|
The exceptions: `CallHomeInProgress` and `WrongUnit` release the line,
|
|
because the line itself is the problem; so does `ChangeUnconfirmed`, which
|
|
the change core raises only after a link fault or a ring, once the frame
|
|
has gone out. `AuditIncomplete` keeps the line unless its `release_line`
|
|
says the path would have hung up anyway (a ring, a link fault, a refusal).
|
|
"""
|
|
|
|
def __init__(self, address: UnitAddress, serial: str,
|
|
client_factory: Callable[[UnitAddress], Any],
|
|
clock: Callable[[], float] = time.monotonic) -> None:
|
|
self.address = address
|
|
self.serial = normalise_serial(serial)
|
|
self._factory = client_factory
|
|
self._clock = clock
|
|
self._client: Optional[Any] = None
|
|
self.info = None
|
|
self.last_used = clock()
|
|
self.last_traffic = self.last_used
|
|
|
|
@property
|
|
def is_open(self) -> bool:
|
|
client = self._client # one read: held_serial() calls this without the unit lock
|
|
return client is not None and client.is_open()
|
|
|
|
def call_up(self):
|
|
client = self._factory(self.address)
|
|
try:
|
|
client.open()
|
|
info = client.connect()
|
|
except RingDetected as exc:
|
|
_close(client)
|
|
log.warning("RADIO RING from %s during call-up -- released the line", self.address.key)
|
|
raise CallHomeInProgress(_RING_MESSAGE) from exc
|
|
except Exception as exc:
|
|
_close(client)
|
|
raise translate(exc, connecting=True) from exc
|
|
if normalise_serial(info.serial) != self.serial:
|
|
_close(client)
|
|
raise WrongUnit(f"asked for {self.serial} but {info.serial} answered at {self.address.key}")
|
|
self._client, self.info = client, info
|
|
self.last_used = self.last_traffic = self._clock()
|
|
log.info("call-up: %s at %s, staying on the line", self.serial, self.address.key)
|
|
return info
|
|
|
|
def _exchange(self, op: Callable[[Any], T]) -> T:
|
|
try:
|
|
return op(self._client)
|
|
except RingDetected as exc:
|
|
self.hang_up()
|
|
log.warning("RADIO RING from %s -- released the line so the call reaches THOR",
|
|
self.address.key)
|
|
raise CallHomeInProgress(_RING_MESSAGE) from exc
|
|
except (CallHomeInProgress, WrongUnit, ChangeUnconfirmed) as exc:
|
|
# The line itself is the problem: a call-home rides whatever holds the
|
|
# modem's single TCP session, and a line held for X that answers as Y
|
|
# must not stay held. ChangeUnconfirmed always follows a link fault
|
|
# or a ring (the core converts those itself, so the RingDetected
|
|
# clause above never sees them). All three are DeviceErrors, so this
|
|
# clause must stay above `except DeviceError`.
|
|
self.hang_up()
|
|
log.warning("%s at %s -- released the line: %s", type(exc).__name__,
|
|
self.address.key, exc)
|
|
raise
|
|
except AuditIncomplete as exc:
|
|
# A finish that failed on a path that hangs up anyway (ring, link
|
|
# fault, refusal) must still hang up; on a healthy path, keep the line.
|
|
if exc.release_line:
|
|
self.hang_up()
|
|
log.warning("AuditIncomplete at %s -- released the line: %s",
|
|
self.address.key, exc)
|
|
raise
|
|
except DeviceError:
|
|
# The operation's own verdict (event not found, stale id): the line
|
|
# is healthy, so keep it. Library errors still hang up below.
|
|
raise
|
|
except Exception as exc:
|
|
self.hang_up()
|
|
raise translate(exc, connecting=False) from exc
|
|
|
|
def run(self, op: Callable[[Any], T]) -> T:
|
|
"""A user request. Calls up first if the line is not open."""
|
|
if not self.is_open:
|
|
self.call_up()
|
|
result = self._exchange(op)
|
|
self.last_used = self.last_traffic = self._clock()
|
|
return result
|
|
|
|
def keepalive(self) -> None:
|
|
"""A POLL so the modem's idle timer does not drop the line. Not use."""
|
|
if not self.is_open:
|
|
return
|
|
self._exchange(lambda c: c.protocol.poll())
|
|
self.last_traffic = self._clock()
|
|
|
|
def listen(self) -> None:
|
|
"""Read anything the unit sent unprompted; send nothing. Not use."""
|
|
if not self.is_open:
|
|
return
|
|
self._exchange(lambda c: c.read_unsolicited())
|
|
|
|
def hang_up(self) -> None:
|
|
if self._client is not None:
|
|
_close(self._client)
|
|
self._client = None
|
|
log.info("hang-up: %s at %s", self.serial, self.address.key)
|
|
|
|
|
|
# ── Operations (each runs inside Series4Session.run) ──────────────────────────
|
|
|
|
def s4_identify(client: Any, serial: str) -> UnitInfo:
|
|
info = client.connect()
|
|
return UnitInfo(
|
|
serial=info.serial, series=4, model=info.model,
|
|
firmware=None, # the version string lives in 0x01, undecoded
|
|
monitoring=info.monitoring, active_setup=info.active_setup,
|
|
detail={"manufacturer": info.manufacturer, "firmware_line": info.firmware_line},
|
|
)
|
|
|
|
|
|
def s4_status(client: Any, serial: str, run_state: bool = False) -> UnitStatus:
|
|
st = client.get_state()
|
|
count = client.get_event_count()
|
|
detail = {}
|
|
if run_state: # one more round trip, so only when asked (the ring-path bench test)
|
|
rs = client.read_run_state()
|
|
detail["run_state"] = {"code": rs.code, "name": rs.name}
|
|
return UnitStatus(
|
|
serial=serial, series=4, monitoring=st.monitoring, battery_volts=st.battery_volts,
|
|
memory_total_bytes=st.memory_total_bytes, memory_free_bytes=st.memory_free_bytes,
|
|
device_time=st.device_time.isoformat() if st.device_time else None,
|
|
event_count=count, detail=detail,
|
|
)
|
|
|
|
|
|
def s4_settings(client: Any, serial: str) -> UnitSettings:
|
|
content = client.get_setup_content()
|
|
s = decode_setup(content)
|
|
return UnitSettings(
|
|
serial=serial, series=4, setup_name=s.name, record_mode=s.record_mode_name,
|
|
sample_rate=s.sample_rate, record_time_s=s.record_time_s,
|
|
histogram_interval_s=s.histogram_interval_s,
|
|
geo_trigger_ips=s.geo_trigger_ips[0], # the keypad writes all three the same
|
|
notes=dict(s.notes),
|
|
detail={
|
|
"pretrigger_s": s.pretrigger_s,
|
|
"auto_record_stop": s.auto_record_stop,
|
|
"auto_stop_after_s": s.auto_stop_after_s,
|
|
"geophones_active": s.geophones_active,
|
|
"mic_active": s.mic_active,
|
|
"trigger_on_geophones": s.trigger_on_geophones,
|
|
"trigger_on_mic": s.trigger_on_mic,
|
|
"geo_trigger_ips_per_channel": list(s.geo_trigger_ips),
|
|
"mic_type": s.mic_type,
|
|
"mic_trigger_psi": s.mic_trigger_psi,
|
|
"mic_trigger_db": s.mic_trigger_db,
|
|
"job_number_enabled": s.job_number_enabled,
|
|
"job_number": s.job_number,
|
|
"scaled_distance_enabled": s.scaled_distance_enabled,
|
|
"distance_ft": s.distance_ft,
|
|
"charge_weight_lb": s.charge_weight_lb,
|
|
"scaled_distance": s.scaled_distance,
|
|
"editable": editable_fields(content, 4),
|
|
},
|
|
)
|
|
|
|
|
|
def _s4_ref(ref: Any, serial: str) -> EventRef:
|
|
peaks = ref.peaks_ips or {}
|
|
return EventRef(
|
|
event_id=make_event_id(serial, ref.key, stamp_of(ref.timestamp)),
|
|
serial=serial, series=4, index=ref.index, timestamp=iso_of(ref.timestamp),
|
|
record_type=ref.record_type, peak_vector_sum_ips=ref.peak_vector_sum_ips,
|
|
peaks_ips={k.lower(): v for k, v in peaks.items() if k in ("Tran", "Vert", "Long")},
|
|
filename=ref.filename,
|
|
detail={"size_bytes": ref.size, "mic": peaks.get("Mic"), "setup": ref.setup,
|
|
"sensor_location": ref.sensor_location},
|
|
)
|
|
|
|
|
|
def s4_list_events(client: Any, serial: str) -> EventList:
|
|
return EventList(serial=serial, series=4,
|
|
events=[_s4_ref(r, serial) for r in client.list_events(with_records=True)])
|
|
|
|
|
|
def s4_download_event(client: Any, serial: str, key: bytes, stamp: Optional[str]) -> DownloadedEvent:
|
|
"""Walk to the event and download it there -- the order THOR uses, the only
|
|
one captured. Downloading at a parked cursor has never been tried."""
|
|
for ref in client.iter_events(with_records=True):
|
|
if ref.key != key:
|
|
continue
|
|
found = stamp_of(ref.timestamp)
|
|
if stamp is not None and found is None:
|
|
raise MalformedReply(
|
|
f"could not read event {key.hex()}'s record (0C) timestamp to confirm it "
|
|
"is the one listed -- not downloaded; try again")
|
|
if stamp is not None and found != stamp:
|
|
raise StaleEvent(
|
|
f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- "
|
|
"the unit was erased or wrapped since the list was read; list again")
|
|
if ref.filename is None:
|
|
raise MalformedReply(
|
|
f"event {key.hex()}: its record gave no type or timestamp, so it cannot be named or stored")
|
|
# THOR's chunk size. A 16 KB chunk takes ~7 s on cellular against the
|
|
# 10 s receive deadline; 1 KB is what THOR itself sends.
|
|
blob, result = client.fetch_event(ref, chunk_size=THOR_CHUNK_SIZE)
|
|
err = client.decode_error(ref, result)
|
|
return DownloadedEvent(
|
|
event_id=make_event_id(serial, key, found), serial=serial, series=4,
|
|
filename=ref.filename, verified=True if err is not None else None,
|
|
idf_bytes=blob, timestamp=ref.timestamp,
|
|
record={"peak_vector_sum_ips": ref.peak_vector_sum_ips,
|
|
"sensor_location": ref.sensor_location, "setup": ref.setup},
|
|
detail={"size_bytes": ref.size, "pvs_error": err},
|
|
)
|
|
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
|
|
|
|
|
|
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:
|
|
"""Series-4 pieces for the shared core in change.py."""
|
|
plan = plan_start_monitoring() if start else plan_stop_monitoring()
|
|
|
|
def send() -> dict:
|
|
acks = client.protocol.execute(plan)
|
|
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
|
|
|
return run_change(
|
|
kind=monitoring_change(start), serial=serial, series=4, 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),
|
|
# A RADIO RING already buffered is caught here, before 0x96/0x97 goes
|
|
# out. One transport read: RingWatchTransport over Tcp/SerialTransport,
|
|
# each with a 10 ms read timeout, so it returns at once on a quiet line.
|
|
pre_send=lambda: client.read_unsolicited())
|
|
|
|
|
|
def _dial_string(block: bytes) -> Optional[str]:
|
|
raw = bytes(block[6:46]).split(b"\x00", 1)[0]
|
|
return raw.decode("ascii", errors="replace") or None
|
|
|
|
|
|
def _changed_offsets(before: bytes, after: bytes) -> list:
|
|
return [i for i in range(max(len(before), len(after)))
|
|
if (before[i] if i < len(before) else None) != (after[i] if i < len(after) else None)]
|
|
|
|
|
|
# Measured 2026-11-03 (UM20147): monitoring, a Micromate returns its real call-home
|
|
# block and ACKS a write, but does not apply it -- its own menu: "Feature disabled
|
|
# while monitoring". So SFM refuses before sending one it would ignore.
|
|
S4_CALL_HOME_WHILE_MONITORING = ("is monitoring -- a Micromate ignores call-home changes while "
|
|
"monitoring (its own menu: 'Feature disabled while monitoring'); "
|
|
"stop monitoring first, then change call-home")
|
|
_NOT_CALL_HOME = "returned a block that is not its call-home block (header {}, not 007c)"
|
|
|
|
|
|
def s4_call_home_state(client: Any, serial: str) -> CallHomeState:
|
|
"""Bit 0 of content[5] is the enable (UM12947 reads 0x05 / 0x04, UM20147 0x01)."""
|
|
block = client.get_call_home_content()
|
|
detail = {"byte5": f"0x{block[5]:02X}" if len(block) > 5 else None, "block": block.hex()}
|
|
if not is_call_home_content(block):
|
|
detail["reason"] = "the unit " + _NOT_CALL_HOME.format(block[0:2].hex())
|
|
return CallHomeState(serial=serial, series=4, enabled=None, dial_string=None, detail=detail)
|
|
return CallHomeState(serial=serial, series=4, enabled=bool(block[5] & 0x01),
|
|
dial_string=_dial_string(block), detail=detail)
|
|
|
|
|
|
def s4_change_call_home(client: Any, serial: str, *, enabled: 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:
|
|
"""Series-4 pieces for the shared core: read 0x2C, flip bit 0 of [5], send the
|
|
rest back byte for byte, re-read. The plan is built from the read run_change
|
|
made just before it (spec: build the plan on the same line, right before
|
|
sending), and that same plan is the one sent."""
|
|
reads: list = []
|
|
planned: list = []
|
|
|
|
def read_state() -> str:
|
|
run = client.read_run_state().name
|
|
if run == "calling_home" or run.startswith("unknown"):
|
|
return run # the core refuses both; a write waits for a known state
|
|
if run == "monitoring" and not reads:
|
|
raise UnitStateUnknown(f"{serial} {S4_CALL_HOME_WHILE_MONITORING} -- nothing sent")
|
|
block = client.get_call_home_content()
|
|
if not is_call_home_content(block):
|
|
raise UnitStateUnknown(f"{serial} " + _NOT_CALL_HOME.format(block[0:2].hex())
|
|
+ " -- nothing sent")
|
|
reads.append(block)
|
|
return "enabled" if block[5] & 0x01 else "disabled"
|
|
|
|
def describe_plan() -> dict:
|
|
planned[:] = [plan_call_home_enabled(reads[-1], enabled)]
|
|
return planned[0].describe()
|
|
|
|
def send() -> dict:
|
|
acks = client.protocol.execute(planned[0])
|
|
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
|
|
|
def snapshot() -> dict:
|
|
before, after = reads[0], reads[-1]
|
|
return {"before": before.hex(), "after": after.hex(),
|
|
"changed_offsets": _changed_offsets(before, after)}
|
|
|
|
return run_change(
|
|
kind=call_home_change(enabled), serial=serial, series=4, 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=read_state, describe_plan=describe_plan, send=send,
|
|
is_refusal=lambda e: isinstance(e, OpcodeRefused),
|
|
is_ring=lambda e: isinstance(e, RingDetected),
|
|
pre_send=lambda: client.read_unsolicited(),
|
|
snapshot=snapshot)
|
|
|
|
|
|
# ── Changing settings (phase 5) ──────────────────────────────────────────────
|
|
|
|
S4_SETTINGS_WHILE_MONITORING = ("is monitoring -- stop it first (a stop makes it call in if "
|
|
"call-home is on)")
|
|
_EDIT_BUFFER_WARNING = ("this reads the unit's keypad edit buffer: if someone is in its menu, "
|
|
"their unsaved edits are sent too")
|
|
_FACTORY = "factory.mmb"
|
|
|
|
|
|
def s4_change_settings(client: Any, serial: str, *, changes: dict, revision: Optional[str],
|
|
dry_run: bool, audit: Any, address: UnitAddress, caller: str,
|
|
sleep: Callable[[float], None], verify_timeout_s: float,
|
|
verify_interval_s: float) -> ChangeResult:
|
|
"""Series-4 pieces for the shared core: read the name, preferences, trigger
|
|
and setup blocks and the schedule; patch the setup's fields
|
|
(micromate.setup_fields); send THOR's setup push under the active setup's own
|
|
name; read the setup back. The plan is built from the read run_change made
|
|
just before it, and that same plan is the one sent.
|
|
|
|
Refused before anything is sent: a monitoring unit; values the unit does not
|
|
allow (BadRequest); a live call whose `revision` is not this read's
|
|
(SettingsChanged); the factory setup, a schedule that would load another
|
|
setup, an unreadable schedule, or a block SFM has not seen (ChangeRefused,
|
|
shown as `blocked` in a preview)."""
|
|
st: dict = {}
|
|
reads: list = []
|
|
|
|
def first_read() -> str:
|
|
name = client.get_active_setup_raw()
|
|
prefs = client.get_prefs_content()
|
|
trigger = client.get_trigger_content()
|
|
setup = client.get_setup_content()
|
|
try:
|
|
normal = check_changes(setup, 4, changes)
|
|
except SettingsValueError as exc:
|
|
raise BadRequest(f"{exc} -- nothing sent") from exc
|
|
rev = settings_revision([name.encode("ascii", "replace"), prefs, trigger, setup])
|
|
if not dry_run and revision != rev:
|
|
raise SettingsChanged(f"{serial}'s settings changed since the preview -- preview "
|
|
"again; nothing sent")
|
|
image = encode_setup(setup, 4, normal)
|
|
blocked: list = []
|
|
warnings = [_EDIT_BUFFER_WARNING]
|
|
if name.strip().casefold() == _FACTORY:
|
|
blocked.append("this unit is running its factory setup; load any other setup on "
|
|
"its keypad, then try again")
|
|
try:
|
|
entries = parse_schedule(client.read_schedule())
|
|
except (_MMProtocolError, ValueError) as exc:
|
|
blocked.append(f"could not read this unit's schedule ({exc}) -- SFM will not change "
|
|
"a unit whose schedule it cannot check")
|
|
else:
|
|
conflicts = schedule_conflicts(entries, name)
|
|
for e in conflicts:
|
|
blocked.append(f"this unit's schedule loads {e.setup} at {e.time}, which would "
|
|
"replace this change")
|
|
for e in entries:
|
|
if "start_with_setup" in e.actions and e not in conflicts:
|
|
warnings.append(f"the unit's schedule loads this setup at {e.time}; the "
|
|
"change survives it")
|
|
plan = None
|
|
try:
|
|
plan = plan_setup_push(prefs, trigger, image, name)
|
|
except ValueError as exc:
|
|
blocked.append(f"this unit's {exc} -- SFM has not seen a block like it")
|
|
st.update(name=name, prefs=prefs, trigger=trigger, setup=setup, image=image,
|
|
changes=normal, revision=rev, blocked=blocked, warnings=warnings, plan=plan)
|
|
reads.append(setup)
|
|
return settings_state(setup, image, setup, series=4)
|
|
|
|
def read_state() -> str:
|
|
run = client.read_run_state().name
|
|
if run == "calling_home" or run.startswith("unknown"):
|
|
return run # the core refuses both; a write waits for a known state
|
|
if not st:
|
|
if run == "monitoring":
|
|
raise UnitStateUnknown(f"{serial} {S4_SETTINGS_WHILE_MONITORING} -- nothing sent")
|
|
return first_read()
|
|
now = client.get_setup_content()
|
|
reads.append(now)
|
|
return settings_state(st["setup"], st["image"], now, series=4)
|
|
|
|
def describe_plan() -> dict:
|
|
ok = st["plan"] is not None and not st["blocked"]
|
|
d = st["plan"].describe() if ok else {"action": "setup push", "steps": [], "warnings": []}
|
|
d["warnings"] = list(st["warnings"]) + list(d.get("warnings", []))
|
|
d.update(fields=field_rows(st["setup"], st["image"], 4, st["changes"]),
|
|
revision=st["revision"], blocked=list(st["blocked"]))
|
|
if st["blocked"] and not dry_run:
|
|
raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent")
|
|
return d
|
|
|
|
def send() -> dict:
|
|
acks = client.protocol.execute(st["plan"])
|
|
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
|
|
|
def snapshot() -> dict:
|
|
before, after = st["setup"], reads[-1]
|
|
return {"fields": field_rows(before, st["image"], 4, st["changes"], now=after),
|
|
"before": before.hex(), "after": after.hex(),
|
|
"changed_offsets": _changed_offsets(before, after),
|
|
"prefs": st["prefs"].hex(), "trigger": st["trigger"].hex()}
|
|
|
|
return run_change(
|
|
kind=settings_change(), serial=serial, series=4, dry_run=dry_run, even_if_already=False,
|
|
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=read_state, describe_plan=describe_plan, send=send,
|
|
is_refusal=lambda e: isinstance(e, OpcodeRefused),
|
|
is_ring=lambda e: isinstance(e, RingDetected),
|
|
pre_send=lambda: client.read_unsolicited(),
|
|
snapshot=snapshot)
|