feat(sfm): Series-3 events -- header list, one-event download, stale ids refused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-21 16:57:26 -04:00
1 parent c85244e0fe
commit b79309eb72
3 files changed
+242 -11

No files matched your search

+95 -9
View File
@@ -2,14 +2,18 @@
MiniMates -- a held session waits for the bench test in the spec."""
from __future__ import annotations
import datetime
import logging
from typing import Any, Callable
import struct
from typing import Any, Callable, Optional
from minimateplus import MiniMateClient
from minimateplus.blastware_file import blastware_filename
from minimateplus.transport import TcpTransport
from .errors import DeviceError, MalformedReply, NoAnswer, WrongUnit, translate
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate
from .events import iso_of, make_event_id, stamp_of
from .models import DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
log = logging.getLogger("sfm.device_access")
@@ -17,10 +21,16 @@ S3_DEFAULT_BAUD = 38400
S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "Histogram + Continuous"}
def default_s3_client_factory(address: UnitAddress, timeout: float = 10.0) -> MiniMateClient:
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
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=timeout)
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD)
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:
@@ -30,13 +40,47 @@ def _close(client: Any) -> None:
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
def _s3_ref(ev: Any, serial: str) -> EventRef:
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=ev.record_type.lower() if ev.record_type else 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},
)
class Series3Adapter:
def __init__(self, client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory) -> None:
def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None:
self._factory = client_factory
def _run(self, address: UnitAddress, fn: Callable[[Any], Any]) -> Any:
def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any:
def attempt() -> Any:
client = self._factory(address)
client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)
try:
client.open()
except Exception as exc:
@@ -121,3 +165,45 @@ class Series3Adapter:
"geo_range": cc.geo_range},
)
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()])
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
def download_event(self, address: UnitAddress, serial: str, key: bytes,
stamp: Optional[str]) -> DownloadedEvent:
def op(client: Any) -> DownloadedEvent:
info = client.connect()
self._check(info.serial, serial, address)
try:
ev = client.download_event_by_key(key)
except struct.error as exc:
# Inferred, not measured here: the known 5A page bug. An event past the unit's
# first 64 KB drives TERM's offset negative, and struct.pack rejects it
# (seismo-relay CLAUDE.md, "KNOWN BUG").
raise MalformedReply(
f"event {key.hex()}: its download could not be assembled ({exc}) -- most "
"likely the known bug with events past the unit's first 64 KB; 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 != 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")
return DownloadedEvent(
event_id=make_event_id(serial, key, found), serial=serial, series=3,
filename=filename, verified=None, event=ev, a5_frames=ev._a5_frames,
compliance=info.compliance_config, detail={"a5_frames": len(ev._a5_frames)},
)
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)