Files
seismo-relay/sfm/device_access/s4.py
T
serversdownandClaude Opus 5.5 cdc6360ec0 fix(sfm): an audit finish that fails on a hang-up path still releases the line
The final fix wave's AuditIncomplete landed in _exchange's `except DeviceError`,
which keeps the line -- so on the nine ring / link-fault paths (and a refusal) a
failed audit write turned a hang-up into a held Series-4 line, blocking a THOR
call-home for up to the 5-minute idle hang-up and making "SFM hung up" false.
AuditIncomplete now carries release_line, set by every finish whose path hangs
up anyway, and _exchange honours it.  Also pins the Series-3 change path's
retry=False again (the rewritten lost-ack test no longer could).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-23 19:36:00 -04:00

368 lines
16 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.writes import plan_start_monitoring, plan_stop_monitoring
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
from .errors import (
AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound,
MalformedReply, StaleEvent, 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
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) -> UnitStatus:
st = client.get_state()
count = client.get_event_count()
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,
)
def s4_settings(client: Any, serial: str) -> UnitSettings:
s = client.get_setup()
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,
},
)
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(
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),
# 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())