Files
serversdownandClaude Opus 5.5 c790e20116 fix: bench follow-ups -- the setup-menu warning, observed call-home values, waveform read
From the 2026-11-04 bench:
- A MiniMate settings preview warns that a change is lost if someone is in
  the unit's setup menu: a write sent with the menu open was acknowledged
  and read back, then lost on Cancel or Save -- the menu writes its own
  copy of the whole block back (measured both ways on BE9441).
- The two bytes after the MiniMate settings block went out as 00 00 and
  the unit took them; the preview note says so instead of 'unmeasured'.
- A Micromate call-home plan no longer warns about 0x00 / 0x01: UM20147
  took both, each way, on 11-03 and 11-04, matching its menu.
- read_waveform_data_raw drops the escaped-checksum's stray 0x10, as the
  settings read does (it failed closed: the write's block check refused
  203 bytes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 16:15:28 -05:00

644 lines
35 KiB
Python

"""Series-3 adapter. Connect-per-request, as SFM has always done for
MiniMates -- a held session waits for the bench test in the spec."""
from __future__ import annotations
import datetime
import logging
import struct
from typing import Any, Callable, Optional
from minimateplus import MiniMateClient
from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter
from minimateplus.event_file_io import _GEO_INT16_FS
from minimateplus.framing import build_bw_write_frame, unescape_reply
from micromate.setup_block import decode_setup
from micromate.setup_fields import (
SettingsValueError, changes_bytes, check_changes, editable_fields, encode_setup, field_rows,
field_values, settings_state,
)
from micromate.setup_fields import revision as settings_revision
from minimateplus.protocol import (
SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, SUB_COMPLIANCE_WRITE, SUB_EVENT_INDEX_WRITE,
SUB_START_MONITORING, SUB_STOP_MONITORING, SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE,
ImageRefused, call_home_enabled, call_home_image, is_call_home_block, is_compliance_content,
write_image,
)
from minimateplus.transport import TcpTransport
from .errors import (BadRequest, ChangeRefused, DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported,
SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit, translate)
from .change import 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)
log = logging.getLogger("sfm.device_access")
S3_DEFAULT_BAUD = 38400
S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "Histogram + Continuous"}
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
# A MiniMate call-home write goes out only once SFM's 0x7E / 0x7F frames are
# reproduced from Blastware's own; shut, a live change is refused before any
# connection (a dry run still works). OPEN since 2026-11-02:
# tests/test_s3_call_home_bw_frames.py rebuilds Blastware's enable and disable
# writes (BE11529, 2026-04-20) byte for byte from the unit's own reads.
S3_CALL_HOME_FRAME_VERIFIED = True
# Measured 2026-11-03 (BE9441): while monitoring, a MiniMate answers the 0x2C read
# with its device-info block, as it answers 1A -- its call-home settings cannot be
# read, so they cannot be changed (SFM writes back only a block it just read).
S3_CALL_HOME_WHILE_MONITORING = ("did not return its call-home settings -- a MiniMate answers the "
"call-home read with its device-info block while monitoring; "
"stop monitoring first, then change call-home")
# The 0x1C flag byte (section[1]): the only values ever measured. 0x10 is
# BE11529 monitoring (2026-04-08); 0x0B is BE9441 recording a histogram,
# confirmed at the unit (2026-10-26). Anything else is refused for a change.
# Measured 2026-11-03 (BE9441's 10-26 recording, 5 / 5 reads): while monitoring, a
# MiniMate answers the 1A settings read with its device-info block.
S3_SETTINGS_WHILE_MONITORING = ("did not return its settings -- a MiniMate answers this way "
"while monitoring; stop monitoring first (a stop makes it call in "
"if call-home is on)")
# Blastware's settings write, in its order (push_config_raw): event index, the
# settings block in addressed chunks, trigger, waveform data, with their confirms.
_S3_SETTINGS_STEPS = ((0x68, "event index (as read)"), (0x73, "confirm B"),
(0x71, "settings block"), (0x72, "confirm A"),
(0x82, "trigger block (as read)"), (0x83, "trigger confirm"),
(0x69, "waveform data (as read)"), (0x74, "confirm C"), (0x72, "confirm A"))
_S3_TAIL_WARNING = ("the two bytes after the settings block go out as 00 00 (Blastware sends "
"its own constant; the unit took it at the bench 2026-11-04)")
# Measured at the bench 2026-11-04 (BE9441): a write sent while the setup menu was open
# was acknowledged and read back, then lost when the operator pressed Cancel or Save --
# the menu writes its own copy of the whole block back.
_S3_MENU_WARNING = ("if someone is in this unit's setup menu, this change is lost when they "
"leave it (Cancel or Save writes the menu's copy back)")
S3_RUN_STATES = {0x00: "idle", 0x10: "monitoring", 0x0B: "monitoring"}
def s3_run_state(status: Any) -> str:
"""The change path's state name from the raw 0x1C flag -- never
`is_monitoring`, which reads every byte but 0x10 as idle. A value never
measured is `unknown(0x..)`, and the change core refuses it."""
flag = getattr(status, "state_flag", None)
if flag is None:
return "unknown(short)"
return S3_RUN_STATES.get(flag, f"unknown(0x{flag:02X})")
# A start makes the unit run its sensor check before "Recording..." -- ~30 s
# (Brian, 2026-10-26), ~40 s on BE11529 (2026-04-08). A start's read-back waits
# this long before asking, then wakes the unit with retries (S3_WAKE_*).
S3_SENSOR_CHECK_S = 30.0
S3_WAKE_ATTEMPT_S = 5.0
S3_WAKE_DEADLINE_S = 60.0
def _woken_state(client: Any) -> str:
"""The run state, read after waking the unit: SESSION_RESET + POLL first,
re-sent until it answers.
A monitoring MiniMate ignores a bare request until it is woken (measured
2026-04-08). On 2026-10-26 BE9441 acked a start, then left a bare 0x1C, and
later a single SESSION_RESET + POLL, unanswered for 120 s: both went out 2 s
after the start, inside the sensor check, and were never re-sent."""
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
return s3_run_state(client.get_monitor_status())
def default_s3_client_factory(address: UnitAddress, timeout: Optional[float] = None) -> MiniMateClient:
if address.host:
return MiniMateClient(transport=TcpTransport(address.host, port=address.tcp_port),
timeout=10.0 if timeout is None else timeout)
if timeout is None:
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD)
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD, timeout=timeout)
def _close(client: Any) -> None:
try:
client.close()
except Exception: # noqa: BLE001
log.debug("close failed", exc_info=True)
def _s3_dt(ev: Any) -> Optional[datetime.datetime]:
ts = getattr(ev, "timestamp", None)
if ts is None or ts.hour is None:
return None
try:
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
except (TypeError, ValueError):
return None
def _s3_filename(ev: Any, serial: str) -> Optional[str]:
try:
return blastware_filename(ev, serial)
except Exception: # noqa: BLE001
return None
S3_RECORD_TYPE_NOTE = "Series 3's event record does not say waveform or histogram; not decoded yet"
def _s3_ref(ev: Any, serial: str) -> EventRef:
"""record_type is always None: minimateplus's 0C decode reports "Waveform"
for every record layout, histograms included, so it cannot be trusted
here. Null rather than wrong until a histogram's 0C is captured."""
dt = _s3_dt(ev)
pv = ev.peak_values
peaks = {}
if pv is not None:
peaks = {k: v for k, v in (("tran", pv.tran), ("vert", pv.vert), ("long", pv.long))
if v is not None}
return EventRef(
event_id=make_event_id(serial, ev._waveform_key, stamp_of(dt)),
serial=serial, series=3, index=ev.index, timestamp=iso_of(dt),
record_type=None,
peak_vector_sum_ips=pv.peak_vector_sum if pv is not None else None,
peaks_ips=peaks, filename=_s3_filename(ev, serial),
detail={"mic_psi": pv.micl if pv is not None else None,
"record_type_note": S3_RECORD_TYPE_NOTE},
)
_GEO_FULL_SCALE_IPS = 10.0 # normal range; one decoder step = 0.005 in/s
_PEAK_TOLERANCE_IPS = 0.0051 # one 0.005 in/s step, plus the 0C's float32 slop
def verify_s3_download(ev: Any, compliance: Any, body: Optional[bytes] = None) -> tuple:
"""Check a downloaded event against itself and the unit's own 0C record: (verified, why).
A short or misassembled event must not reach the store -- BE9441's bench
(2026-10-25) stored two as successes before this existed. `body` is the
event's 5A body (taken from `ev._a5_frames` when not given). In order:
* No waveform decode: it must decode as a histogram (stored unverified --
its peaks are not compared yet), or it is refused. 0 of ~430 fixture
histograms decode as a waveform; a corrupted waveform decodes as neither.
* A waveform's record chain must end on its END record (0x06), as the
file reader requires; a cut-short stream does not.
* All three geophone channels must be the same length.
* Each channel's peak must be the unit's own to one 0.005 in/s step (a
clipped blast -- both at full scale -- counts as a match). Only for a
unit confirmed in normal range: a sensitive-range unit's scale is still
open (the 8x discrepancy), and an unread range is not assumed.
Raises MalformedReply ("not saved") on any failure.
"""
from minimateplus.blastware_file import extract_body_bytes
from minimateplus.histogram_codec import decode_histogram_body
from minimateplus.waveform_codec import STREAM_END_ID, walk_records
if body is None:
frames = getattr(ev, "_a5_frames", None)
body = extract_body_bytes(frames)[1] if frames else b""
samples = getattr(ev, "raw_samples", None) or {}
chans = ("Tran", "Vert", "Long")
if not all(samples.get(c) for c in chans):
if body and decode_histogram_body(body):
return None, "a histogram: stored unverified (its peaks are not compared yet)"
raise MalformedReply(
"the downloaded event decodes as neither a waveform nor a histogram -- the "
"download is incomplete or misassembled; not saved")
try:
recs = walk_records(body)
except Exception: # noqa: BLE001 -- treated as no chain
recs = []
tail = recs[-1]["end"] if recs else None
if tail is None or tail + 5 > len(body) or body[tail + 4] != STREAM_END_ID:
raise MalformedReply(
"the downloaded waveform's record chain has no end record -- the download is "
"cut short; not saved")
lengths = {c: len(samples[c]) for c in chans}
if len(set(lengths.values())) != 1:
raise MalformedReply(
f"the downloaded waveform's channels have different lengths {lengths} -- the "
"download is incomplete or misassembled; not saved")
if getattr(compliance, "geo_range", None) != 0:
return None, ("whole, but peaks not checked: the unit is not confirmed in normal "
"range (a sensitive-range scale is not settled)")
pv = ev.peak_values
unit = {"Tran": pv.tran, "Vert": pv.vert, "Long": pv.long} if pv else {}
clip = _GEO_FULL_SCALE_IPS - _PEAK_TOLERANCE_IPS
for c in chans:
if unit.get(c) is None:
return None, f"whole, but the unit's record gives no {c} peak to check against"
decoded = max(abs(x) for x in samples[c]) * _GEO_FULL_SCALE_IPS / _GEO_INT16_FS
if decoded >= clip and unit[c] >= clip:
continue # both at full scale: a clipped blast
if abs(decoded - unit[c]) > _PEAK_TOLERANCE_IPS:
raise MalformedReply(
f"the downloaded {c} peak is {decoded:.4f} in/s but the unit's own record says "
f"{unit[c]:.4f} -- the download is incomplete or misassembled; not saved")
return True, f"{lengths['Tran']} samples per channel, peaks match the unit's own"
class Series3Adapter:
def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None:
self._factory = client_factory
def change_monitoring(self, address: UnitAddress, serial: str, *, start: bool, dry_run: bool,
even_if_already: bool, audit: Any, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-3 pieces for the shared core in change.py. One attempt, never
retried: `retry=False` stops _run's cold-boot second attempt, and the
core calls the write once."""
sub = SUB_START_MONITORING if start else SUB_STOP_MONITORING
ack_sub = 0xFF - sub
def op(client: Any) -> ChangeResult:
def read_serial() -> str:
info = client.connect() # a fresh connection: connect() is the fresh 0x15 read
return info.serial or ""
def describe_plan() -> dict:
what = "start monitoring" if start else "stop monitoring"
return {"action": what, "sends_nothing": True, "warnings": [],
"steps": [{"sub": f"0x{sub:02X}", "what": what, "offset": "0x0000",
"data_len": 0, "expect_ack": f"0x{ack_sub:02X}",
"frame": build_bw_write_frame(sub, b"").hex()}]}
settle: list = []
def send() -> dict:
# The client validates the ack SUB; it returns nothing else, so none is claimed.
(client.start_monitoring if start else client.stop_monitoring)()
if start:
settle.append(S3_SENSOR_CHECK_S) # the first read waits out the check
return {"subs": [f"0x{ack_sub:02X}"]}
reconnected: list = []
def read_state() -> str:
if settle:
sleep(settle.pop())
try:
return _woken_state(client)
except OSError as exc:
# The modem can drop the line while the unit sensor-checks
# after a start: BE9441's first wake hit "[Errno 32] Broken
# pipe" (2026-10-29), and a fresh connection read it as
# monitoring. Reconnect once, TCP only (opening a MiniMate's
# serial port reboots it), check it is still the same unit,
# and read. A read -- nothing is re-sent.
if reconnected or not address.host:
raise
reconnected.append(True)
log.warning("Series 3 at %s: the line dropped during the read-back (%s) -- "
"reconnecting to read the state; nothing is re-sent",
address.key, exc)
client.close()
client.open()
# Wake first: the identity read is a bare 0x15, which a unit that
# has just started ignores until SESSION_RESET + POLL (the order
# the status read and the legacy write routes use: poll, then read).
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
self._check(client.read_serial(), serial, address)
return s3_run_state(client.get_monitor_status())
return run_change(
kind=monitoring_change(start), serial=serial, series=3, 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=read_serial,
read_state=read_state,
describe_plan=describe_plan, send=send)
return self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False)
def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None,
retry: bool = True) -> Any:
def attempt() -> Any:
client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)
try:
client.open()
except Exception as exc:
_close(client)
raise translate(exc, connecting=True) from exc
try:
return fn(client)
except DeviceError:
raise
except Exception as exc:
raise translate(exc, connecting=False) from exc
finally:
_close(client)
try:
return attempt()
except NoAnswer:
# A MiniMate that has just had its serial lines asserted can take
# 5-10 s to boot, and shows it as silence; one retry covers it. TCP
# only -- on a serial cable a silence is a real fault. Narrower than
# server._run_with_retry (any protocol error): retrying a
# MalformedReply would also retry "no settings block", which a
# reconnect cannot fix.
if not retry or not address.host:
raise
log.info("Series 3 at %s: no clean answer, retrying once (unit may be cold)", address.key)
return attempt()
@staticmethod
def _check(serial_reported: str, serial: str, address: UnitAddress) -> None:
if (serial_reported or "").strip().upper() != serial:
raise WrongUnit(f"asked for {serial} but {serial_reported} answered at {address.key}")
def identify(self, address: UnitAddress, serial: str) -> UnitInfo:
def op(client: Any) -> UnitInfo:
info = client.connect()
self._check(info.serial, serial, address)
cc = info.compliance_config
return UnitInfo(
serial=info.serial, series=3, model=info.model, firmware=info.firmware_version,
monitoring=None, active_setup=cc.setup_name if cc else None,
detail={"manufacturer": info.manufacturer, "dsp_version": info.dsp_version},
)
return self._run(address, op)
def status(self, address: UnitAddress, serial: str) -> UnitStatus:
def op(client: Any) -> UnitStatus:
client.poll()
ms = client.get_monitor_status()
# The change path's reading, not a guess: an unmeasured flag is None.
monitoring = {"monitoring": True, "idle": False}.get(s3_run_state(ms))
return UnitStatus(
serial=serial, series=3, monitoring=monitoring,
battery_volts=round(ms.battery_v, 2) if ms.battery_v is not None else None,
memory_total_bytes=ms.memory_total, memory_free_bytes=ms.memory_free,
device_time=None, event_count=None,
# Series 3 status reads no serial, so the serial shown is the one requested, not one the unit reported.
detail={"serial_verified": False},
)
return self._run(address, op)
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
"""The unit's call-home switch and dial string (0x2C), after a wake. Like
status, it reads no serial: the one shown is the one requested."""
def op(client: Any) -> CallHomeState:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
raw = client.read_call_home_raw()
image = unescape_reply(raw)
detail = {"byte5": f"0x{image[5]:02X}" if len(image) > 5 else None,
"block": bytes(raw).hex(), "serial_verified": False}
if not is_call_home_block(raw):
detail["reason"] = f"the unit {S3_CALL_HOME_WHILE_MONITORING}"
return CallHomeState(serial=serial, series=3, enabled=None, dial_string=None, detail=detail)
dial = bytes(image[6:46]).split(b"\x00", 1)[0].decode("ascii", errors="replace") or None
return CallHomeState(serial=serial, series=3, enabled=call_home_enabled(raw),
dial_string=dial, detail=detail)
return self._run(address, op)
def change_call_home(self, address: UnitAddress, serial: str, *, enabled: bool, dry_run: bool,
even_if_already: bool, audit: Any, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-3 pieces for the shared core: read 0x2C, set byte 5 of the
unescaped image, send it (0x7E) and confirm (0x7F), re-read. One attempt,
never retried; refused live until the frame is verified against Blastware."""
if not dry_run and not S3_CALL_HOME_FRAME_VERIFIED:
raise NotSupported("a MiniMate call-home write waits until its frame has been "
"reproduced from a Blastware capture -- nothing sent")
what = "call-home " + ("enable" if enabled else "disable")
def op(client: Any) -> ChangeResult:
reads: list = []
images: list = []
def read_serial() -> str:
return client.connect().serial or "" # a fresh connection: the 0x15 read
def read_state() -> str:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
raw = client.read_call_home_raw()
if not is_call_home_block(raw):
raise UnitStateUnknown(f"{serial} {S3_CALL_HOME_WHILE_MONITORING} -- nothing sent")
reads.append(raw)
on = call_home_enabled(raw)
if on is None:
image = unescape_reply(raw)
return f"unknown(0x{image[5]:02X})" if len(image) > 5 else "unknown(short)"
return "enabled" if on else "disabled"
def describe_plan() -> dict:
try:
image = call_home_image(reads[-1], enabled)
except ValueError as exc:
images[:] = []
return {"action": what, "steps": [], "warnings": [f"{exc}; nothing would be sent"]}
images[:] = [image]
warnings = []
if image == write_image(SUB_CALL_HOME_WRITE, reads[-1]):
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
" -- this write changes nothing")
return {"action": what, "warnings": warnings, "steps": [
{"sub": f"0x{SUB_CALL_HOME_WRITE:02X}", "what": "call-home config write",
"data_len": len(image), "frame": build_bw_write_frame(SUB_CALL_HOME_WRITE, image).hex()},
{"sub": f"0x{SUB_CALL_HOME_CONFIRM:02X}", "what": "call-home config confirm",
"data_len": 0, "frame": build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"").hex()}]}
def send() -> dict:
client.write_call_home_image(images[0])
return {"subs": [f"0x{0xFF - SUB_CALL_HOME_WRITE:02X}", f"0x{0xFF - SUB_CALL_HOME_CONFIRM:02X}"]}
def snapshot() -> dict:
before = write_image(SUB_CALL_HOME_WRITE, reads[0])
after = write_image(SUB_CALL_HOME_WRITE, reads[-1])
return {"before": before.hex(), "after": after.hex(),
"changed_offsets": [i for i in range(min(len(before), len(after)))
if before[i] != after[i]]}
return run_change(
kind=call_home_change(enabled), serial=serial, series=3, 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=read_serial, read_state=read_state,
describe_plan=describe_plan, send=send, snapshot=snapshot,
# raised before the frame goes out: audited as nothing sent
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def change_settings(self, address: UnitAddress, serial: str, *, changes: dict,
revision: Optional[str], dry_run: bool, audit: Any, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-3 pieces for the shared core (phase 5): read the four settings
blocks, patch the settings block's fields (micromate.setup_fields), send
Blastware's sequence through push_config_raw with the other three blocks
as read, re-read the settings. One attempt, never retried.
Refused before anything is sent: a monitoring unit (it answers 1A with its
device-info block); a value the unit does not allow (BadRequest); a live
call whose `revision` is not this read's (SettingsChanged)."""
def op(client: Any) -> ChangeResult:
st: dict = {}
reads: list = []
def read_serial() -> str:
return client.connect().serial or "" # a fresh connection: the 0x15 read
def read_state() -> str:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
if st:
now = client.read_compliance_content()
if not is_compliance_content(now):
raise MalformedReply("the read-back did not return the settings block")
reads.append(now)
return settings_state(st["setup"], st["image"], now, series=3)
blocks = client.read_settings_blocks()
setup = blocks["compliance"]
if not is_compliance_content(setup):
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")
try:
normal = check_changes(setup, 3, changes)
except SettingsValueError as exc:
raise BadRequest(f"{exc} -- nothing sent") from exc
# What the preview showed: the settings block and the changes. The other
# three blocks are re-read here and sent back as read (the trigger block's
# byte 5 "differs by unit and session", #46).
rev = settings_revision([setup, changes_bytes(normal)])
if not dry_run and revision != rev:
raise SettingsChanged(f"{serial}'s settings, or the changes asked for, are not "
"the ones previewed -- preview again; nothing sent")
image = encode_setup(setup, 3, normal)
blocked = []
for sub, block in ((SUB_EVENT_INDEX_WRITE, blocks["event_index"]),
(SUB_COMPLIANCE_WRITE, image),
(SUB_TRIGGER_CONFIG_WRITE, blocks["trigger"]),
(SUB_WAVEFORM_DATA_WRITE, blocks["waveform"])):
try:
write_image(sub, block, escaped=False) # push_config_raw's own check
except ValueError as exc:
blocked.append(f"this unit's {exc} -- SFM has not seen a block like it")
st.update(blocks=blocks, setup=setup, image=image, changes=normal, revision=rev,
blocked=blocked)
reads.append(setup)
return settings_state(setup, image, setup, series=3)
def describe_plan() -> dict:
b = st["blocks"]
lens = {0x68: len(b["event_index"]), 0x71: len(st["image"]) + 2,
0x82: len(b["trigger"]), 0x69: len(b["waveform"])}
if st["blocked"] and not dry_run:
raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent")
steps = [] if st["blocked"] else [
{"sub": f"0x{sub:02X}", "what": what, "data_len": lens.get(sub, 0)}
for sub, what in _S3_SETTINGS_STEPS]
return {"action": "settings write", "blocked": list(st["blocked"]), "steps": steps,
"fields": field_rows(st["setup"], st["image"], 3, st["changes"]),
"revision": st["revision"], "warnings": [_S3_MENU_WARNING, _S3_TAIL_WARNING]}
def send() -> dict:
b = st["blocks"]
client.push_config_raw(b["event_index"], st["image"], b["trigger"], b["waveform"],
escaped=False) # every block read is logical
return {"subs": [f"0x{0xFF - sub:02X}" for sub, _ in _S3_SETTINGS_STEPS]}
def snapshot() -> dict:
before, after = st["setup"], reads[-1]
return {"fields": field_rows(before, st["image"], 3, st["changes"], now=after),
"before": before.hex(), "after": after.hex(),
"changed_offsets": [i for i in range(min(len(before), len(after)))
if before[i] != after[i]]}
return run_change(
kind=settings_change(), serial=serial, series=3, 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=read_serial, read_state=read_state, describe_plan=describe_plan,
send=send, snapshot=snapshot,
# raised before the first frame goes out: audited as nothing sent
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
"""The 1A read assembled into the logical block and decoded by the shared
settings codec (phase 5)."""
def op(client: Any) -> UnitSettings:
info = client.connect()
self._check(info.serial, serial, address)
content = client.read_compliance_content()
if not is_compliance_content(content):
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING}")
v = field_values(content, 3)
name = decode_setup(content + bytes(2), verify=False).name # Series 3 reads no CRC
labels = {d["field"]: d["label"] for d in editable_fields(content, 3)}
notes = {labels[f]: v[f] for f in ("note_1", "note_2", "note_3", "note_4")}
code = content[5]
return UnitSettings(
serial=info.serial, series=3, setup_name=name or None,
record_mode=S3_MODES.get(code, f"unknown (0x{code:02x})"),
sample_rate=v["sample_rate"], record_time_s=v["record_time_s"],
histogram_interval_s=v["histogram_interval_s"], geo_trigger_ips=v["geo_trigger_ips"],
notes=notes,
detail={"record_mode_code": code, "alarm_level_geo": v["geo_alarm_ips"],
"geo_range": v["geo_range"], "editable": editable_fields(content, 3)},
)
return self._run(address, op)
def list_events(self, address: UnitAddress, serial: str) -> EventList:
def op(client: Any) -> EventList:
info = client.connect()
self._check(info.serial, serial, address)
return EventList(serial=serial, series=3,
events=[_s3_ref(ev, serial) for ev in client.list_event_headers()])
# The default timeout: a header walk is small replies only, so a lost
# one costs 10 s (TCP) with the unit locked, not 120 s.
return self._run(address, op)
def download_event(self, address: UnitAddress, serial: str, key: bytes,
stamp: Optional[str]) -> DownloadedEvent:
# The walk compares this with the target's 0C and, on a mismatch, sends
# no 5A: a stale id costs a header walk, not a full download of the
# wrong event.
iso = datetime.datetime.strptime(stamp, "%Y%m%d%H%M%S").isoformat() if stamp is not None else None
def op(client: Any) -> DownloadedEvent:
info = client.connect()
self._check(info.serial, serial, address)
try:
ev = client.download_event_by_key(key, expected_timestamp=iso)
except struct.error as exc:
# Defensive. This once caught the 64 KB page bug (TERM's offset driven
# negative); the walk is 32-bit linear since 2026-10-26 and no longer
# produces it, so reaching here is a new fault.
raise MalformedReply(
f"event {key.hex()}: its download could not be assembled ({exc}); not saved"
) from exc
if ev is None:
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
found = stamp_of(_s3_dt(ev))
if stamp is not None and found is None:
raise MalformedReply(
f"could not read event {key.hex()}'s record (0C) 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 not ev._a5_frames:
raise MalformedReply(f"event {key.hex()}: no waveform data received (the 5A download failed)")
filename = _s3_filename(ev, serial)
if filename is None:
raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored")
verified, why = verify_s3_download(ev, info.compliance_config)
try:
bw_bytes = blastware_file_bytes(ev, ev._a5_frames)
except ValueError as exc:
raise MalformedReply(
f"event {key.hex()}: its Blastware file could not be assembled ({exc}); not saved"
) from exc
filename = with_type_letter(filename, bw_bytes) # ...900 -> ...900H, from the file's own bytes
return DownloadedEvent(
event_id=make_event_id(serial, key, found), serial=serial, series=3,
filename=filename, verified=verified, event=ev, a5_frames=ev._a5_frames,
bw_bytes=bw_bytes,
compliance=info.compliance_config, timestamp=_s3_dt(ev),
detail={"a5_frames": len(ev._a5_frames), "check": why},
)
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)