Blastware names a direct download K441LTON.900 and only its call-in copy K441LTON.900H, so a folder of directly downloaded events cannot be sorted by kind. SFM's own files now always carry the letter. It is read from the file's own record-type byte (STRT[18], #41) by the new with_type_letter() -- not from the recording mode: BE9441's K441LTOK.R10 is a waveform that triggered 2 s into histogram K441LTOK.QZ0 (Histogram+Continuous). A file whose type does not read keeps the plain name; a name never fails a download. All three paths that name a MiniMate file SFM builds: the device-access download (the page's event list), WaveformStore.save (the legacy route's store copy, the bench call-in server), and the legacy /device/event/{i}/blastware_file download. Verified on BE9441's recorded 5A walk: 0111f210 -> K441LTON.900H, 011106a0 -> K441LTOK.R10W, byte-identical to Blastware's files. find_event_by_blastware_name tightens with it: a lettered name matches itself and the letterless form, not the other letter (a waveform and a histogram in the same second are different events); a letterless name still matches all three. Store consequence: new downloads only; rows and files stored before keep their names, and 'already stored' still finds them. No schema change, no migration. The event list shows the plain name until the event is downloaded (the type is not known before the 5A). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
321 lines
12 KiB
Python
321 lines
12 KiB
Python
"""Fakes of both device clients for sfm.device_access tests.
|
|
|
|
They return the libraries' real dataclasses, and FakeMicromateClient's setup
|
|
is decoded from a real UM20147 read. `fail` is a queue of exceptions; each
|
|
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, MicromateEventRef, MicromateState
|
|
from micromate.setup_block import decode_setup
|
|
from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp
|
|
|
|
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
|
|
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
|
|
|
|
|
|
from minimateplus.protocol import TimeoutError as mmp_TimeoutError # noqa: E402
|
|
|
|
|
|
class _Base:
|
|
def __init__(self, fail=None, open_error=None):
|
|
self.fail = list(fail or [])
|
|
self.open_error = open_error
|
|
self.calls: list[str] = []
|
|
self.opened = 0
|
|
self.closed = 0
|
|
self._open = False
|
|
|
|
def _step(self, name):
|
|
self.calls.append(name)
|
|
if self.fail:
|
|
raise self.fail.pop(0)
|
|
|
|
def open(self):
|
|
self.opened += 1
|
|
if self.open_error is not None:
|
|
raise self.open_error
|
|
self._open = True
|
|
|
|
def close(self):
|
|
self.closed += 1
|
|
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 _iso(ev):
|
|
"""minimateplus.client._event_timestamp_iso's format; "" with no timestamp."""
|
|
ts = ev.timestamp
|
|
if ts is None:
|
|
return ""
|
|
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour or 0, ts.minute or 0,
|
|
ts.second or 0).isoformat()
|
|
|
|
|
|
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)),
|
|
]
|
|
|
|
|
|
class FakeMiniMateClient(_Base):
|
|
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
|
|
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None,
|
|
bare_requests_ignored=False, **kw):
|
|
super().__init__(**kw)
|
|
self.serial = serial
|
|
# As a monitoring MiniMate (measured 2026-04-08): on a fresh connection a
|
|
# read before SESSION_RESET + POLL goes unanswered. Off unless a test asks.
|
|
self.bare_requests_ignored = bare_requests_ignored
|
|
self._woken = False
|
|
# read_serial()'s answer (connect() keeps answering `serial`), and errors
|
|
# raised by wake() once a write has gone out -- the read-back's wakes.
|
|
self.serial_reported = serial if serial_reported is None else serial_reported
|
|
self.wake_errors = list(wake_errors or [])
|
|
self.monitoring = monitoring
|
|
self.monitor_states = list(monitor_states) if monitor_states else [monitoring]
|
|
self.write_error = write_error
|
|
self.writes: list = []
|
|
if compliance == "default":
|
|
compliance = ComplianceConfig(
|
|
recording_mode=0x01, sample_rate=1024, histogram_interval_sec=300,
|
|
record_time=3.0, trigger_level_geo=0.5, alarm_level_geo=1.0, geo_range=0,
|
|
setup_name="BRIDGE-A", project="Bridge job", client="Acme",
|
|
operator="BH", sensor_location="Loc 1", notes=None,
|
|
)
|
|
self.compliance = compliance
|
|
self.events = default_s3_events() if events is None else events
|
|
self.download_requests: list = [] # (key4, expected_timestamp) per download
|
|
self.last_download = None
|
|
|
|
def open(self):
|
|
super().open()
|
|
self._woken = False
|
|
|
|
def _bare_read(self, name):
|
|
self._step(name)
|
|
if self.bare_requests_ignored and not self._woken:
|
|
raise mmp_TimeoutError(f"{name}: no reply (the unit was not woken)")
|
|
|
|
def connect(self) -> DeviceInfo:
|
|
self._step("connect")
|
|
self._woken = True # connect() starts with the startup handshake
|
|
return DeviceInfo(
|
|
serial=self.serial, firmware_minor=17, firmware_version="S338.17",
|
|
dsp_version="10.72", manufacturer="Instantel", model="MiniMate Plus",
|
|
compliance_config=self.compliance,
|
|
)
|
|
|
|
def poll(self) -> None:
|
|
self._step("poll")
|
|
self._woken = True
|
|
|
|
def wake(self, **kw) -> None:
|
|
self._step("wake")
|
|
if self.writes and self.wake_errors:
|
|
raise self.wake_errors.pop(0)
|
|
self._woken = True
|
|
|
|
def read_serial(self) -> str:
|
|
self._bare_read("read_serial")
|
|
return self.serial_reported
|
|
|
|
def get_monitor_status(self) -> MonitorStatus:
|
|
self._bare_read("get_monitor_status")
|
|
state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0]
|
|
# A bool is a measured state; an int (or None: a short section) is the raw 0x1C flag byte.
|
|
flag = (0x10 if state else 0x00) if isinstance(state, bool) else state
|
|
return MonitorStatus(
|
|
is_monitoring=flag == 0x10, battery_v=6.8,
|
|
memory_total=983026, memory_free=900000, state_flag=flag,
|
|
)
|
|
|
|
|
|
def _write(self, name):
|
|
self._step(name)
|
|
self.writes.append(name)
|
|
if self.write_error is not None:
|
|
raise self.write_error
|
|
|
|
def start_monitoring(self) -> None:
|
|
self._write("start_monitoring")
|
|
|
|
def stop_monitoring(self) -> None:
|
|
self._write("stop_monitoring")
|
|
|
|
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, *, expected_timestamp=None):
|
|
"""As the real walk: an event whose 0C time is not the expected one comes
|
|
back without its 5A."""
|
|
self._step("download_event_by_key")
|
|
self.download_requests.append((key4, expected_timestamp))
|
|
self.last_download = None
|
|
for ev in self.events:
|
|
if ev._waveform_key == key4:
|
|
if expected_timestamp is not None and _iso(ev) != expected_timestamp:
|
|
ev = copy.copy(ev)
|
|
ev._a5_frames = None
|
|
elif ev._a5_frames and isinstance(ev._a5_frames[0], str):
|
|
_as_downloaded(ev) # placeholder frames only; a test's real ones are kept
|
|
self.last_download = ev
|
|
return ev
|
|
return None
|
|
|
|
|
|
_REAL = {}
|
|
|
|
|
|
def _as_downloaded(ev):
|
|
"""Give a fake event what a real one-event download carries: BE9441 event 1's
|
|
recorded A5 frames, their decoded waveform, and the unit's own 0C peaks for it
|
|
-- so the download check sees a whole, matching event."""
|
|
if not _REAL:
|
|
from minimateplus.framing import S3FrameParser
|
|
from minimateplus.waveform_codec import decode_a5_frames
|
|
raw = (Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26"
|
|
/ "BE9441_event1_0111646a_rx.bin").read_bytes()
|
|
_REAL["frames"] = [f for f in S3FrameParser().feed(raw) if f.sub == 0xA5]
|
|
_REAL["samples"] = decode_a5_frames(_REAL["frames"])
|
|
ev._a5_frames = _REAL["frames"]
|
|
ev.raw_samples = _REAL["samples"]
|
|
pv = ev.peak_values
|
|
ev.peak_values = PeakValues(tran=0.030, vert=0.095, long=0.020, micl=pv.micl if pv else None,
|
|
peak_vector_sum=pv.peak_vector_sum if pv else 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:
|
|
def __init__(self, owner):
|
|
self._owner = owner
|
|
|
|
def poll(self):
|
|
self._owner._step("poll")
|
|
|
|
def execute(self, plan):
|
|
self._owner._step("execute")
|
|
self._owner.executed.append(plan)
|
|
if self._owner.execute_error is not None:
|
|
raise self._owner.execute_error
|
|
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
|
|
|
|
|
|
class FakeMicromateClient(_Base):
|
|
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
|
|
unsolicited=b"", event_refs=None, run_states=None,
|
|
serial_reported=None, execute_error=None, **kw):
|
|
super().__init__(**kw)
|
|
self.unit_serial = serial # not `serial`: that is the client's method
|
|
self.run_states = list(run_states) if run_states else [0x00]
|
|
self.serial_reported = serial if serial_reported is None else serial_reported
|
|
self.execute_error = execute_error
|
|
self.executed = []
|
|
self.monitoring = monitoring
|
|
self.events = events
|
|
self.unsolicited = unsolicited
|
|
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:
|
|
return self._open
|
|
|
|
def connect(self) -> MicromateDeviceInfo:
|
|
self._step("connect")
|
|
return MicromateDeviceInfo(
|
|
serial=self.unit_serial, manufacturer="Instantel", model="MM/ISEE/S",
|
|
firmware_line="thor", monitoring=self.monitoring, active_setup="test2.MMB",
|
|
)
|
|
|
|
def serial(self, *, refresh=False):
|
|
self._step("serial")
|
|
return self.serial_reported if refresh else self.unit_serial
|
|
|
|
def read_run_state(self):
|
|
from micromate.models import MicromateRunState
|
|
self._step("read_run_state")
|
|
code = self.run_states.pop(0) if len(self.run_states) > 1 else self.run_states[0]
|
|
names = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
|
|
return MicromateRunState(code, names.get(code, f"unknown(0x{code:02X})"))
|
|
|
|
def get_state(self) -> MicromateState:
|
|
self._step("get_state")
|
|
return MicromateState(
|
|
monitoring=self.monitoring,
|
|
device_time=datetime.datetime(2026, 10, 20, 18, 7, 58),
|
|
battery_volts=3.8, memory_total_bytes=15_000_000, memory_free_bytes=14_799_296,
|
|
)
|
|
|
|
def get_event_count(self) -> int:
|
|
self._step("get_event_count")
|
|
return self.events
|
|
|
|
def get_setup(self):
|
|
self._step("get_setup")
|
|
return decode_setup(SETUP_FIXTURE.read_bytes()[11:])
|
|
|
|
def read_unsolicited(self) -> bytes:
|
|
self._step("read_unsolicited")
|
|
data, self.unsolicited = self.unsolicited, b""
|
|
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
|