Release v0.34.0 — Series-4 parity, and most of Blastware's report from the event file alone #59
No files matched your search
@@ -0,0 +1,121 @@
|
||||
"""Series-3 adapter. Connect-per-request, as SFM has always done for
|
||||
MiniMates -- a held session waits for the bench test in the spec."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
|
||||
from minimateplus import MiniMateClient
|
||||
from minimateplus.transport import TcpTransport
|
||||
|
||||
from .errors import DeviceError, MalformedReply, NoAnswer, WrongUnit, translate
|
||||
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
|
||||
log = logging.getLogger("sfm.device_access")
|
||||
|
||||
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:
|
||||
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)
|
||||
|
||||
|
||||
def _close(client: Any) -> None:
|
||||
try:
|
||||
client.close()
|
||||
except Exception: # noqa: BLE001
|
||||
log.debug("close failed", exc_info=True)
|
||||
|
||||
|
||||
class Series3Adapter:
|
||||
def __init__(self, client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory) -> None:
|
||||
self._factory = client_factory
|
||||
|
||||
def _run(self, address: UnitAddress, fn: Callable[[Any], Any]) -> Any:
|
||||
def attempt() -> Any:
|
||||
client = self._factory(address)
|
||||
try:
|
||||
client.open()
|
||||
except Exception as exc:
|
||||
_close(client)
|
||||
raise translate(exc, connecting=True) from exc
|
||||
try:
|
||||
return fn(client)
|
||||
except DeviceError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise translate(exc, connecting=False) from exc
|
||||
finally:
|
||||
_close(client)
|
||||
|
||||
try:
|
||||
return attempt()
|
||||
except NoAnswer:
|
||||
# A MiniMate that has just had its serial lines asserted can take
|
||||
# 5-10 s to boot, and shows it as silence; one retry covers it. TCP
|
||||
# only -- on a serial cable a silence is a real fault. Narrower than
|
||||
# server._run_with_retry (any protocol error): retrying a
|
||||
# MalformedReply would also retry "no settings block", which a
|
||||
# reconnect cannot fix.
|
||||
if not address.host:
|
||||
raise
|
||||
log.info("Series 3 at %s: no clean answer, retrying once (unit may be cold)", address.key)
|
||||
return attempt()
|
||||
|
||||
@staticmethod
|
||||
def _check(serial_reported: str, serial: str, address: UnitAddress) -> None:
|
||||
if (serial_reported or "").strip().upper() != serial:
|
||||
raise WrongUnit(f"asked for {serial} but {serial_reported} answered at {address.key}")
|
||||
|
||||
def identify(self, address: UnitAddress, serial: str) -> UnitInfo:
|
||||
def op(client: Any) -> UnitInfo:
|
||||
info = client.connect()
|
||||
self._check(info.serial, serial, address)
|
||||
cc = info.compliance_config
|
||||
return UnitInfo(
|
||||
serial=info.serial, series=3, model=info.model, firmware=info.firmware_version,
|
||||
monitoring=None, active_setup=cc.setup_name if cc else None,
|
||||
detail={"manufacturer": info.manufacturer, "dsp_version": info.dsp_version},
|
||||
)
|
||||
return self._run(address, op)
|
||||
|
||||
def status(self, address: UnitAddress, serial: str) -> UnitStatus:
|
||||
def op(client: Any) -> UnitStatus:
|
||||
client.poll()
|
||||
ms = client.get_monitor_status()
|
||||
return UnitStatus(
|
||||
serial=serial, series=3, monitoring=ms.is_monitoring,
|
||||
battery_volts=round(ms.battery_v, 2) if ms.battery_v is not None else None,
|
||||
memory_total_bytes=ms.memory_total, memory_free_bytes=ms.memory_free,
|
||||
device_time=None, event_count=None,
|
||||
)
|
||||
return self._run(address, op)
|
||||
|
||||
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
|
||||
def op(client: Any) -> UnitSettings:
|
||||
info = client.connect()
|
||||
self._check(info.serial, serial, address)
|
||||
cc = info.compliance_config
|
||||
if cc is None:
|
||||
raise MalformedReply("could not read the unit's settings (SUB 0x1A)")
|
||||
mode = None
|
||||
if cc.recording_mode is not None:
|
||||
mode = S3_MODES.get(cc.recording_mode, f"unknown (0x{cc.recording_mode:02x})")
|
||||
notes = {
|
||||
label: value for label, value in (
|
||||
("Project", cc.project), ("Client", cc.client), ("User Name", cc.operator),
|
||||
("Seis Loc", cc.sensor_location), ("Extended Notes", cc.notes),
|
||||
) if value is not None
|
||||
}
|
||||
return UnitSettings(
|
||||
serial=info.serial, series=3, setup_name=cc.setup_name, record_mode=mode,
|
||||
sample_rate=cc.sample_rate, record_time_s=cc.record_time,
|
||||
histogram_interval_s=cc.histogram_interval_sec, geo_trigger_ips=cc.trigger_level_geo,
|
||||
notes=notes,
|
||||
detail={"record_mode_code": cc.recording_mode, "alarm_level_geo": cc.alarm_level_geo,
|
||||
"geo_range": cc.geo_range},
|
||||
)
|
||||
return self._run(address, op)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""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 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
|
||||
|
||||
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
class FakeMiniMateClient(_Base):
|
||||
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", **kw):
|
||||
super().__init__(**kw)
|
||||
self.serial = serial
|
||||
self.monitoring = monitoring
|
||||
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
|
||||
|
||||
def connect(self) -> DeviceInfo:
|
||||
self._step("connect")
|
||||
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")
|
||||
|
||||
def get_monitor_status(self) -> MonitorStatus:
|
||||
self._step("get_monitor_status")
|
||||
return MonitorStatus(
|
||||
is_monitoring=self.monitoring, battery_v=6.8,
|
||||
memory_total=983026, memory_free=900000,
|
||||
)
|
||||
|
||||
|
||||
class _FakeProtocol:
|
||||
def __init__(self, owner):
|
||||
self._owner = owner
|
||||
|
||||
def poll(self):
|
||||
self._owner._step("poll")
|
||||
|
||||
|
||||
class FakeMicromateClient(_Base):
|
||||
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
|
||||
unsolicited=b"", **kw):
|
||||
super().__init__(**kw)
|
||||
self.serial = serial
|
||||
self.monitoring = monitoring
|
||||
self.events = events
|
||||
self.unsolicited = unsolicited
|
||||
self.protocol = _FakeProtocol(self)
|
||||
|
||||
def is_open(self) -> bool:
|
||||
return self._open
|
||||
|
||||
def connect(self) -> MicromateDeviceInfo:
|
||||
self._step("connect")
|
||||
return MicromateDeviceInfo(
|
||||
serial=self.serial, manufacturer="Instantel", model="MM/ISEE/S",
|
||||
firmware_line="thor", monitoring=self.monitoring, active_setup="test2.MMB",
|
||||
)
|
||||
|
||||
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
|
||||
@@ -0,0 +1,86 @@
|
||||
"""The Series-3 adapter: connect-per-request, mapped into the shared models."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import minimateplus.protocol as mmp_proto # noqa: E402
|
||||
from device_access_fakes import FakeMiniMateClient # noqa: E402
|
||||
from sfm.device_access.errors import ( # noqa: E402
|
||||
ConnectFailed, MalformedReply, NoAnswer, 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)
|
||||
SERIAL_LINK = UnitAddress(host=None, tcp_port=None, port="/dev/ttyUSB0", baud=None)
|
||||
|
||||
|
||||
def adapter(*clients):
|
||||
queue = list(clients)
|
||||
return Series3Adapter(client_factory=lambda address: queue.pop(0))
|
||||
|
||||
|
||||
def test_identify_maps_device_info():
|
||||
fake = FakeMiniMateClient()
|
||||
info = adapter(fake).identify(TCP, "BE18193")
|
||||
assert (info.serial, info.series, info.model, info.firmware) == ("BE18193", 3, "MiniMate Plus", "S338.17")
|
||||
assert info.active_setup == "BRIDGE-A"
|
||||
assert info.monitoring is None # connect() does not read it on Series 3
|
||||
assert fake.closed == 1
|
||||
|
||||
|
||||
def test_a_different_unit_answering_is_refused():
|
||||
fake = FakeMiniMateClient(serial="BE11529")
|
||||
with pytest.raises(WrongUnit, match="BE18193.*BE11529"):
|
||||
adapter(fake).identify(TCP, "BE18193")
|
||||
assert fake.closed == 1
|
||||
|
||||
|
||||
def test_status_maps_monitor_status():
|
||||
fake = FakeMiniMateClient(monitoring=True)
|
||||
st = adapter(fake).status(TCP, "BE18193")
|
||||
assert (st.series, st.monitoring, st.battery_volts) == (3, True, 6.8)
|
||||
assert (st.memory_total_bytes, st.memory_free_bytes) == (983026, 900000)
|
||||
assert st.event_count is None and st.device_time is None
|
||||
assert fake.calls == ["poll", "get_monitor_status"]
|
||||
|
||||
|
||||
def test_settings_maps_the_compliance_config():
|
||||
s = adapter(FakeMiniMateClient()).settings(TCP, "BE18193")
|
||||
assert s.record_mode == "Continuous"
|
||||
assert (s.sample_rate, s.record_time_s, s.histogram_interval_s) == (1024, 3.0, 300)
|
||||
assert s.geo_trigger_ips == 0.5
|
||||
assert s.setup_name == "BRIDGE-A"
|
||||
assert s.notes == {"Project": "Bridge job", "Client": "Acme", "User Name": "BH", "Seis Loc": "Loc 1"}
|
||||
assert s.detail["record_mode_code"] == 0x01
|
||||
|
||||
|
||||
def test_settings_without_a_compliance_read_is_a_malformed_reply_and_not_retried():
|
||||
# One fake only: a retry would ask the factory for a second and fail.
|
||||
with pytest.raises(MalformedReply, match="settings"):
|
||||
adapter(FakeMiniMateClient(compliance=None)).settings(TCP, "BE18193")
|
||||
|
||||
|
||||
def test_a_cold_unit_over_tcp_gets_one_retry():
|
||||
first = FakeMiniMateClient(fail=[mmp_proto.TimeoutError("cold")])
|
||||
second = FakeMiniMateClient()
|
||||
info = adapter(first, second).identify(TCP, "BE18193")
|
||||
assert info.serial == "BE18193"
|
||||
assert first.closed == 1 and second.closed == 1
|
||||
|
||||
|
||||
def test_a_serial_link_is_not_retried():
|
||||
fake = FakeMiniMateClient(fail=[mmp_proto.TimeoutError("quiet")])
|
||||
with pytest.raises(NoAnswer):
|
||||
adapter(fake).identify(SERIAL_LINK, "BE18193")
|
||||
|
||||
|
||||
def test_a_failed_connect_is_connect_failed_and_not_retried():
|
||||
fake = FakeMiniMateClient(open_error=ConnectionRefusedError("refused"))
|
||||
with pytest.raises(ConnectFailed, match="could not connect"):
|
||||
adapter(fake).identify(TCP, "BE18193")
|
||||
Reference in new issue
Block a user