Files
seismo-relay/sfm/device_access/s4.py
T
serversdownandClaude Opus 5.5 ef096e3082 fix(sfm): a download never downgrades a stored event -- an existing row is returned, nothing written
THOR's watcher (and Blastware's ACH) store every event through
/db/import/idf_file and /db/import/blastware_file, with the paired report.
Storing a download of the same event afterwards overwrote that richer copy:
on Series 4 the file, .h5 and sidecar were rewritten (extensions dropped);
on Series 3 the row lost PVS, project strings and ZC frequencies and was
repointed at a second, review-less file set.

persist_download now looks up (serial, timestamp) first.  A row there is
returned as it stands -- inserted false, detail.already_stored true -- with
no store call, no insert_events and no sidecar write.  Never merge.

- DownloadedEvent gains `timestamp` (the unit's own event time) and
  `record` (Series 4's 0x0C fields); both adapters set them.
- The Series-3 `event is None` guard now runs before backfill/save, with a
  message that is true there ("nothing was stored").
- Tests build the watcher's state exactly as the import endpoints do and
  prove the row dict, the sidecar bytes and the file mtimes are unchanged.

No schema change, no migration, no codec change.

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

296 lines
12 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 minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
from .errors import (
CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, StaleEvent, WrongUnit, translate,
)
from .events import iso_of, make_event_id, stamp_of
from .models import 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.
"""
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 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 != 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")