Files
seismo-relay/sfm/device_access/s4.py
T

397 lines
17 KiB
Python

"""Series-4 sessions: call up once, stay on the line, hang up when idle.
⚠ 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.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 (
CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent,
WrongUnit, translate,
)
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 = ("the unit started calling home; SFM hung up so the call can "
"reach THOR -- try again in a few minutes")
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 one exception: `CallHomeInProgress` and `WrongUnit` release the line,
because the line itself is the problem.
"""
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) 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.
self.hang_up()
log.warning("%s at %s -- released the line: %s", type(exc).__name__,
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:
"""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)
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}
cid = audit.begin(serial=serial, series=4, address=address.key, action=action,
tier="change", request=request, caller=caller)
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:
acks = client.protocol.execute(plan)
except Exception as exc: # noqa: BLE001 -- recorded, never retried
after = _try_run_state(client)
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)
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:
break
except Exception as exc: # noqa: BLE001 -- the row must not stay pending
audit.finish(cid, outcome="failed", verified="not_checked", ack=ack,
error=f"sent, but the read-back failed: {exc}")
raise
ok = seen[-1] == want
audit.finish(cid, outcome="sent" if ok else "failed", verified="ok" if ok else "mismatch",
ack=ack, error=None if ok else f"unit reads {seen[-1]}, expected {want}")
return ChangeResult(dry_run=False, sent=True, outcome="sent" if ok else "failed",
verified="ok" if ok else "mismatch", 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 Exception: # noqa: BLE001
return None