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:
1 parent
c85244e0fe
commit
b79309eb72
3 files changed
+242
-11
No files matched your search
+95
-9
@@ -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)
|
||||
@@ -6,12 +6,13 @@ call pops one, if any, and raises it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from micromate.models import MicromateDeviceInfo, MicromateState
|
||||
from micromate.setup_block import decode_setup
|
||||
from minimateplus.models import ComplianceConfig, DeviceInfo, MonitorStatus
|
||||
from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp
|
||||
|
||||
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
|
||||
|
||||
@@ -41,8 +42,29 @@ class _Base:
|
||||
self._open = False
|
||||
|
||||
|
||||
def s3_event(index, key_hex, when, *, record_type="Waveform", pvs=0.12, frames=True):
|
||||
ev = Event(index=index)
|
||||
ev._waveform_key = bytes.fromhex(key_hex)
|
||||
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=when.year, unknown_byte=0,
|
||||
month=when.month, day=when.day, hour=when.hour,
|
||||
minute=when.minute, second=when.second)
|
||||
ev.record_type = record_type
|
||||
ev.peak_values = PeakValues(tran=0.05, vert=0.08, long=0.03, micl=0.0001,
|
||||
peak_vector_sum=pvs)
|
||||
if frames:
|
||||
ev._a5_frames = ["frame"]
|
||||
return ev
|
||||
|
||||
|
||||
def default_s3_events():
|
||||
return [
|
||||
s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)),
|
||||
s3_event(1, "0111245a", datetime.datetime(2026, 10, 2, 9, 30, 15), record_type="Histogram"),
|
||||
]
|
||||
|
||||
|
||||
class FakeMiniMateClient(_Base):
|
||||
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", **kw):
|
||||
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None, **kw):
|
||||
super().__init__(**kw)
|
||||
self.serial = serial
|
||||
self.monitoring = monitoring
|
||||
@@ -54,6 +76,7 @@ class FakeMiniMateClient(_Base):
|
||||
operator="BH", sensor_location="Loc 1", notes=None,
|
||||
)
|
||||
self.compliance = compliance
|
||||
self.events = default_s3_events() if events is None else events
|
||||
|
||||
def connect(self) -> DeviceInfo:
|
||||
self._step("connect")
|
||||
@@ -74,6 +97,23 @@ class FakeMiniMateClient(_Base):
|
||||
)
|
||||
|
||||
|
||||
def list_event_headers(self):
|
||||
self._step("list_event_headers")
|
||||
out = []
|
||||
for ev in self.events:
|
||||
h = copy.copy(ev)
|
||||
h._a5_frames = None
|
||||
out.append(h)
|
||||
return out
|
||||
|
||||
def download_event_by_key(self, key4):
|
||||
self._step("download_event_by_key")
|
||||
for ev in self.events:
|
||||
if ev._waveform_key == key4:
|
||||
return ev
|
||||
return None
|
||||
|
||||
|
||||
class _FakeProtocol:
|
||||
def __init__(self, owner):
|
||||
self._owner = owner
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Series-3 events: listed from headers, one downloaded, mapped into the shared shape."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402
|
||||
from sfm.device_access.errors import ( # noqa: E402
|
||||
EventNotFound, MalformedReply, StaleEvent, WrongUnit,
|
||||
)
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s3 import Series3Adapter # noqa: E402
|
||||
|
||||
TCP = UnitAddress(host="10.0.0.5", tcp_port=12345, port=None, baud=None)
|
||||
FIRST = bytes.fromhex("01110000")
|
||||
|
||||
|
||||
def adapter(*clients):
|
||||
queue = list(clients)
|
||||
seen = []
|
||||
|
||||
def factory(address, **kw):
|
||||
seen.append(kw)
|
||||
return queue.pop(0)
|
||||
a = Series3Adapter(client_factory=factory)
|
||||
a.seen = seen
|
||||
return a
|
||||
|
||||
|
||||
def test_listing_maps_each_header_into_the_shared_shape():
|
||||
out = adapter(FakeMiniMateClient()).list_events(TCP, "BE18193")
|
||||
assert (out.serial, out.series, len(out.events)) == ("BE18193", 3, 2)
|
||||
e = out.events[1]
|
||||
assert e.event_id == "BE18193:0111245a:20261002093015"
|
||||
assert (e.index, e.timestamp, e.record_type) == (1, "2026-10-02T09:30:15", "histogram")
|
||||
assert e.peaks_ips == {"tran": 0.05, "vert": 0.08, "long": 0.03}
|
||||
assert e.peak_vector_sum_ips == 0.12 and e.detail["mic_psi"] == 0.0001
|
||||
assert e.filename and e.filename.startswith("T193")
|
||||
|
||||
|
||||
def test_listing_uses_the_header_walk_and_the_long_timeout():
|
||||
fake = FakeMiniMateClient()
|
||||
a = adapter(fake)
|
||||
a.list_events(TCP, "BE18193")
|
||||
assert "list_event_headers" in fake.calls and "download_event_by_key" not in fake.calls
|
||||
assert a.seen == [{"timeout": 120.0}]
|
||||
assert fake.closed == 1
|
||||
|
||||
|
||||
def test_listing_refuses_a_different_unit():
|
||||
with pytest.raises(WrongUnit):
|
||||
adapter(FakeMiniMateClient(serial="BE11529")).list_events(TCP, "BE18193")
|
||||
|
||||
|
||||
def test_download_returns_the_event_its_frames_and_the_settings():
|
||||
fake = FakeMiniMateClient()
|
||||
dl = adapter(fake).download_event(TCP, "BE18193", FIRST, "20261001080000")
|
||||
assert (dl.series, dl.event_id, dl.verified) == (3, "BE18193:01110000:20261001080000", None)
|
||||
assert dl.event is fake.events[0] and dl.a5_frames == ["frame"]
|
||||
assert dl.compliance is fake.compliance and dl.filename.startswith("T193")
|
||||
|
||||
|
||||
def test_download_refuses_a_different_unit_before_downloading():
|
||||
fake = FakeMiniMateClient(serial="BE11529")
|
||||
with pytest.raises(WrongUnit):
|
||||
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
|
||||
assert "download_event_by_key" not in fake.calls
|
||||
|
||||
|
||||
def test_a_key_that_is_not_stored_is_404():
|
||||
with pytest.raises(EventNotFound):
|
||||
adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", bytes.fromhex("0111ffff"), None)
|
||||
|
||||
|
||||
def test_a_stale_id_is_refused_rather_than_downloading_another_event():
|
||||
with pytest.raises(StaleEvent, match="20261001080000"):
|
||||
adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, "20250101000000")
|
||||
|
||||
|
||||
def test_an_id_without_a_timestamp_skips_the_check():
|
||||
dl = adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, None)
|
||||
assert dl.event_id == "BE18193:01110000:20261001080000"
|
||||
|
||||
|
||||
def test_a_failed_5a_is_a_clear_error():
|
||||
fake = FakeMiniMateClient(events=[s3_event(0, "01110000",
|
||||
datetime.datetime(2026, 10, 1, 8, 0, 0), frames=False)])
|
||||
with pytest.raises(MalformedReply, match="5A"):
|
||||
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
|
||||
|
||||
|
||||
def test_the_64k_page_bug_is_named_not_a_bare_500():
|
||||
fake = FakeMiniMateClient()
|
||||
|
||||
def boom(key4):
|
||||
raise struct.error("argument out of range")
|
||||
fake.download_event_by_key = boom
|
||||
with pytest.raises(MalformedReply, match="64 KB"):
|
||||
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
|
||||
Reference in new issue
Block a user