Series3Adapter.settings reads the 1A block assembled into its 2,090 logical bytes and decodes it with micromate.setup_fields (a monitoring unit's device-info answer is refused with 'stop monitoring first'). change_settings runs the shared change core: read the four settings blocks, patch the settings block's fields, send Blastware's sequence through push_config_raw with the event index, trigger and waveform blocks as read, re-read. Refused before sending: monitoring, a value the unit does not allow, a stale preview. push_config_raw's pre-check now raises ImageRefused, so a refused image is audited as nothing sent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
471 lines
19 KiB
Python
471 lines
19 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
|
|
import json
|
|
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"
|
|
PUSH_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-writes" / "setup-push-overwrite-test1.json"
|
|
|
|
|
|
def s4_push_reads() -> dict:
|
|
"""UM12947's reads (content, by SUB) just before THOR's setup push: 0x08 prefs,
|
|
0x2E trigger, 0x1A setup, 0x41 active name."""
|
|
import json
|
|
ex = json.loads(PUSH_FIXTURE.read_text())["exchanges"]
|
|
start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA)
|
|
return {e["sub"]: bytes.fromhex(e["response_data"])[11:] for e in ex[:start]}
|
|
|
|
|
|
_S3_BLOCKS = None
|
|
|
|
|
|
def s3_settings_blocks() -> dict:
|
|
"""BE9441's four settings blocks on 2026-10-26, as SFM's reads return them:
|
|
the 1A read Blastware took right after its second write (assembled, 2,090 B),
|
|
and the event index / trigger / waveform blocks that write sent back (each a
|
|
write is the read plus two bytes)."""
|
|
global _S3_BLOCKS
|
|
if _S3_BLOCKS is None:
|
|
from minimateplus.framing import S3FrameParser
|
|
from minimateplus.protocol import assemble_compliance_content
|
|
from test_minimate_write_frames import WRITES, _payload
|
|
fix = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
|
|
reads, cur = [], None
|
|
for f in S3FrameParser().feed((fix / "unit_replies.bin").read_bytes()):
|
|
if f.sub != 0xE5:
|
|
continue
|
|
if len(f.data) == 11:
|
|
cur = []
|
|
reads.append(cur)
|
|
else:
|
|
cur.append(bytes(f.data))
|
|
sent = {_payload(f)[2]: _payload(f)[16:] for f in WRITES[13:26]}
|
|
_S3_BLOCKS = {"event_index": sent[0x68][:-2], "compliance": assemble_compliance_content(reads[2]),
|
|
"trigger": sent[0x82][:-2], "waveform": sent[0x69][:-2]}
|
|
return dict(_S3_BLOCKS)
|
|
|
|
|
|
def s3_device_info_answer(serial: bytes = b"BE9441") -> bytes:
|
|
"""What a MONITORING MiniMate returns for a 1A read, assembled: its device-info
|
|
block (BE9441 10-26: reads 3-7 start 0e 'BE9441'), 2,090 bytes."""
|
|
return (b"\x0e" + serial).ljust(2090, b"\x00")
|
|
|
|
|
|
def schedule_record(time_slot: int, action: int, setup: str = "") -> bytes:
|
|
"""One 260-byte schedule.dat record (micromate.schedule's layout)."""
|
|
rec = bytearray(260)
|
|
rec[4], rec[5], rec[6], rec[7] = time_slot, 3, action, len(setup)
|
|
rec[8:8 + len(setup)] = setup.encode("ascii")
|
|
return bytes(rec)
|
|
THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
|
|
|
|
|
|
def s3_call_home_raw(byte5: int = 0x01) -> bytes:
|
|
"""A MiniMate's 0x2C reply payload as S3FrameParser returns it (125 B, the
|
|
num_retries 3 kept as 10 03), laid out as the 4-20-26 captures measured
|
|
(BE11529): header 00 7C DC, [5] the enable, [6:46] the dial string."""
|
|
raw = b"\x00\x7c\xdc\x00\x00" + bytes([byte5]) + b"RADIO RING".ljust(40, b"\x00")
|
|
raw += bytes(117 - len(raw)) + b"\x10\x03"
|
|
return raw + bytes(125 - len(raw))
|
|
|
|
|
|
def um12947_call_home(enabled: bool = True) -> bytes:
|
|
"""UM12947's own 126-byte call-home content, as THOR read it (0x05 on, 0x04 off)."""
|
|
ex = json.loads((THOR_WRITES / "call-home-enable-disable.json").read_text())["exchanges"]
|
|
reads = [bytes.fromhex(e["response_data"])[11:] for e in ex if e["sub"] == 0x2C]
|
|
return next(r for r in reads if r[5] == (0x05 if enabled else 0x04))
|
|
|
|
|
|
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, call_home_raw=None, settings_blocks=None,
|
|
monitoring_settings=False, **kw):
|
|
super().__init__(**kw)
|
|
self.serial = serial
|
|
self.settings_blocks = s3_settings_blocks() if settings_blocks is None else dict(settings_blocks)
|
|
self.monitoring_settings = monitoring_settings
|
|
self.pushed = None
|
|
# 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
|
|
self.call_home_raw = s3_call_home_raw() if call_home_raw is None else call_home_raw
|
|
# 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 read_call_home_raw(self) -> bytes:
|
|
self._bare_read("read_call_home_raw")
|
|
return self.call_home_raw
|
|
|
|
def write_call_home_image(self, image: bytes) -> None:
|
|
self._write("call_home")
|
|
self.call_home_raw = bytes(image) # read back as the unit would store it
|
|
|
|
def read_compliance_content(self) -> bytes:
|
|
self._bare_read("read_compliance_content")
|
|
return s3_device_info_answer() if self.monitoring_settings else self.settings_blocks["compliance"]
|
|
|
|
def read_settings_blocks(self) -> dict:
|
|
self._bare_read("read_settings_blocks")
|
|
blocks = dict(self.settings_blocks)
|
|
if self.monitoring_settings:
|
|
blocks["compliance"] = s3_device_info_answer()
|
|
return blocks
|
|
|
|
def push_config_raw(self, event_index, compliance, trigger, waveform) -> None:
|
|
self.pushed = (bytes(event_index), bytes(compliance), bytes(trigger), bytes(waveform))
|
|
self._write("push_config_raw")
|
|
self.settings_blocks["compliance"] = bytes(compliance)[:2090] # read back as the unit stores it
|
|
|
|
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
|
|
for st in plan.steps:
|
|
if st.sub == 0x7E: # the unit stores the block and moves [118:120] itself
|
|
old = self._owner.call_home
|
|
self._owner.call_home = bytes(st.data[:118]) + bytes(~b & 0xFF for b in old[118:120]) \
|
|
+ bytes(st.data[120:])
|
|
if st.sub == 0x71: # the unit stores the setup and computes its own CRC
|
|
from micromate.setup_block import with_crc
|
|
old = self._owner.setup
|
|
self._owner.setup = with_crc(old[:3] + bytes(st.data[3:2090]) + old[2090:2092])
|
|
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
|
|
|
|
def read_call_home_config(self):
|
|
self._owner._step("read_call_home_config")
|
|
return bytes(11) + self._owner.call_home
|
|
|
|
|
|
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, call_home=None, setup=None,
|
|
prefs=None, trigger=None, active_name=None, schedule_body=None,
|
|
schedule_error=None, **kw):
|
|
super().__init__(**kw)
|
|
self.unit_serial = serial # not `serial`: that is the client's method
|
|
self.call_home = um12947_call_home() if call_home is None else call_home
|
|
push = s4_push_reads()
|
|
self.setup = SETUP_FIXTURE.read_bytes()[11:] if setup is None else setup
|
|
self.prefs = push[0x08] if prefs is None else prefs
|
|
self.trigger = push[0x2E] if trigger is None else trigger
|
|
self.active_name = (push[0x41].split(b"\x00")[0].decode("ascii")
|
|
if active_name is None else active_name)
|
|
self.schedule_body = bytes(524) if schedule_body is None else schedule_body
|
|
self.schedule_error = schedule_error
|
|
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 get_call_home_content(self) -> bytes:
|
|
self._step("get_call_home_content")
|
|
return self.call_home
|
|
|
|
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(self.setup)
|
|
|
|
def get_setup_content(self) -> bytes:
|
|
self._step("get_setup_content")
|
|
return self.setup
|
|
|
|
def get_prefs_content(self) -> bytes:
|
|
self._step("get_prefs_content")
|
|
return self.prefs
|
|
|
|
def get_trigger_content(self) -> bytes:
|
|
self._step("get_trigger_content")
|
|
return self.trigger
|
|
|
|
def get_active_setup_raw(self) -> str:
|
|
self._step("get_active_setup_raw")
|
|
return self.active_name
|
|
|
|
def read_schedule(self) -> bytes:
|
|
self._step("read_schedule")
|
|
if self.schedule_error is not None:
|
|
raise self.schedule_error
|
|
return self.schedule_body
|
|
|
|
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
|