feat(sfm): Series-4 events -- chain-walk list, download at THOR's cursor
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
b79309eb72
commit
0a01a8d2db
3 files changed
+148
-4
No files matched your search
+48
-2
@@ -11,10 +11,12 @@ import time
|
|||||||
from typing import Any, Callable, Optional, TypeVar
|
from typing import Any, Callable, Optional, TypeVar
|
||||||
|
|
||||||
from micromate.client import MicromateClient
|
from micromate.client import MicromateClient
|
||||||
|
from micromate.protocol import THOR_CHUNK_SIZE
|
||||||
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
|
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
|
||||||
|
|
||||||
from .errors import CallHomeInProgress, WrongUnit, translate
|
from .errors import CallHomeInProgress, EventNotFound, MalformedReply, StaleEvent, WrongUnit, translate
|
||||||
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
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
|
from .series import normalise_serial
|
||||||
|
|
||||||
log = logging.getLogger("sfm.device_access")
|
log = logging.getLogger("sfm.device_access")
|
||||||
@@ -238,3 +240,47 @@ def s4_settings(client: Any, serial: str) -> UnitSettings:
|
|||||||
"scaled_distance": s.scaled_distance,
|
"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, detail={"size_bytes": ref.size, "pvs_error": err},
|
||||||
|
)
|
||||||
|
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
|
||||||
@@ -10,11 +10,12 @@ import copy
|
|||||||
import datetime
|
import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from micromate.models import MicromateDeviceInfo, MicromateState
|
from micromate.models import MicromateDeviceInfo, MicromateEventRef, MicromateState
|
||||||
from micromate.setup_block import decode_setup
|
from micromate.setup_block import decode_setup
|
||||||
from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp
|
from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp
|
||||||
|
|
||||||
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
|
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
|
||||||
|
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
|
||||||
|
|
||||||
|
|
||||||
class _Base:
|
class _Base:
|
||||||
@@ -114,6 +115,22 @@ class FakeMiniMateClient(_Base):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def s4_ref(index, key_hex, when, record_type, *, pvs=0.2):
|
||||||
|
"""Fixture-backed: the filename it produces names a real file in thor-idf/."""
|
||||||
|
ref = MicromateEventRef(index=index, key=bytes.fromhex(key_hex), size=0, serial="UM20147",
|
||||||
|
record_type=record_type, timestamp=when, peak_vector_sum_ips=pvs,
|
||||||
|
peaks_ips={"Tran": 0.1, "Vert": 0.15, "Long": 0.05, "Mic": 0.0002})
|
||||||
|
ref.size = (THOR_IDF / ref.filename).stat().st_size
|
||||||
|
return ref
|
||||||
|
|
||||||
|
|
||||||
|
def default_s4_refs():
|
||||||
|
return [
|
||||||
|
s4_ref(0, "055d4a81", datetime.datetime(2025, 5, 31, 13, 59, 1), "waveform"),
|
||||||
|
s4_ref(1, "055d4a83", datetime.datetime(2025, 3, 30, 7, 1, 10), "histogram"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class _FakeProtocol:
|
class _FakeProtocol:
|
||||||
def __init__(self, owner):
|
def __init__(self, owner):
|
||||||
self._owner = owner
|
self._owner = owner
|
||||||
@@ -124,13 +141,16 @@ class _FakeProtocol:
|
|||||||
|
|
||||||
class FakeMicromateClient(_Base):
|
class FakeMicromateClient(_Base):
|
||||||
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
|
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
|
||||||
unsolicited=b"", **kw):
|
unsolicited=b"", event_refs=None, **kw):
|
||||||
super().__init__(**kw)
|
super().__init__(**kw)
|
||||||
self.serial = serial
|
self.serial = serial
|
||||||
self.monitoring = monitoring
|
self.monitoring = monitoring
|
||||||
self.events = events
|
self.events = events
|
||||||
self.unsolicited = unsolicited
|
self.unsolicited = unsolicited
|
||||||
self.protocol = _FakeProtocol(self)
|
self.protocol = _FakeProtocol(self)
|
||||||
|
self.event_refs = default_s4_refs() if event_refs is None else event_refs
|
||||||
|
self.cursor = None
|
||||||
|
self.fetched: list = []
|
||||||
|
|
||||||
def is_open(self) -> bool:
|
def is_open(self) -> bool:
|
||||||
return self._open
|
return self._open
|
||||||
@@ -162,3 +182,22 @@ class FakeMicromateClient(_Base):
|
|||||||
self._step("read_unsolicited")
|
self._step("read_unsolicited")
|
||||||
data, self.unsolicited = self.unsolicited, b""
|
data, self.unsolicited = self.unsolicited, b""
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
def list_events(self, *, with_records=True):
|
||||||
|
self._step("list_events")
|
||||||
|
return list(self.event_refs)
|
||||||
|
|
||||||
|
def iter_events(self, *, with_records=True):
|
||||||
|
self._step("iter_events")
|
||||||
|
for ref in self.event_refs:
|
||||||
|
self.cursor = ref.index
|
||||||
|
yield ref
|
||||||
|
|
||||||
|
def fetch_event(self, ref, *, verify=True, tolerance=0.01, chunk_size=None):
|
||||||
|
self._step("fetch_event")
|
||||||
|
self.fetched.append((ref.key_hex, chunk_size))
|
||||||
|
return (THOR_IDF / ref.filename).read_bytes(), object()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def decode_error(ref, result):
|
||||||
|
return None if ref.record_type == "histogram" else 0.0
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""Series-4 events: the chain walk mapped into the shared shape; download at the cursor."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from device_access_fakes import THOR_IDF, FakeMicromateClient # noqa: E402
|
||||||
|
from micromate.protocol import THOR_CHUNK_SIZE # noqa: E402
|
||||||
|
from sfm.device_access.errors import EventNotFound, StaleEvent # noqa: E402
|
||||||
|
from sfm.device_access.s4 import s4_download_event, s4_list_events # noqa: E402
|
||||||
|
|
||||||
|
W_KEY, H_KEY = bytes.fromhex("055d4a81"), bytes.fromhex("055d4a83")
|
||||||
|
|
||||||
|
|
||||||
|
def test_listing_maps_each_ref_into_the_shared_shape():
|
||||||
|
out = s4_list_events(FakeMicromateClient(), "UM20147")
|
||||||
|
assert (out.serial, out.series, len(out.events)) == ("UM20147", 4, 2)
|
||||||
|
e = out.events[0]
|
||||||
|
assert e.event_id == "UM20147:055d4a81:20250531135901"
|
||||||
|
assert (e.index, e.timestamp, e.record_type) == (0, "2025-05-31T13:59:01", "waveform")
|
||||||
|
assert e.peaks_ips == {"tran": 0.1, "vert": 0.15, "long": 0.05}
|
||||||
|
assert e.filename == "UM20147_20250531135901.IDFW"
|
||||||
|
assert e.detail["mic"] == 0.0002 and e.detail["size_bytes"] > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_download_walks_to_the_event_and_uses_thors_chunk_size():
|
||||||
|
fake = FakeMicromateClient()
|
||||||
|
dl = s4_download_event(fake, "UM20147", W_KEY, "20250531135901")
|
||||||
|
assert "iter_events" in fake.calls and "list_events" not in fake.calls
|
||||||
|
assert fake.fetched == [("055d4a81", THOR_CHUNK_SIZE)]
|
||||||
|
assert dl.idf_bytes == (THOR_IDF / "UM20147_20250531135901.IDFW").read_bytes()
|
||||||
|
assert (dl.series, dl.filename, dl.verified) == (4, "UM20147_20250531135901.IDFW", True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_walk_stops_at_the_event_rather_than_reading_ahead():
|
||||||
|
fake = FakeMicromateClient()
|
||||||
|
s4_download_event(fake, "UM20147", W_KEY, None)
|
||||||
|
assert fake.cursor == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_histogram_has_no_self_check_so_verified_is_none():
|
||||||
|
dl = s4_download_event(FakeMicromateClient(), "UM20147", H_KEY, None)
|
||||||
|
assert dl.verified is None and dl.filename.endswith(".IDFH")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_stale_id_is_refused_and_nothing_is_downloaded():
|
||||||
|
fake = FakeMicromateClient()
|
||||||
|
with pytest.raises(StaleEvent, match="20250531135901"):
|
||||||
|
s4_download_event(fake, "UM20147", W_KEY, "20240101000000")
|
||||||
|
assert fake.fetched == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_key_that_is_not_stored_is_404():
|
||||||
|
with pytest.raises(EventNotFound):
|
||||||
|
s4_download_event(FakeMicromateClient(), "UM20147", bytes.fromhex("deadbeef"), None)
|
||||||
Reference in new issue
Block a user