"""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, # Series 3 status reads no serial, so the serial shown is the one requested, not one the unit reported. detail={"serial_verified": False}, ) 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)