diff --git a/sfm/device_access/s4.py b/sfm/device_access/s4.py new file mode 100644 index 0000000..3c320bf --- /dev/null +++ b/sfm/device_access/s4.py @@ -0,0 +1,164 @@ +"""Series-4 sessions: call up once, stay on the line, hang up when idle. + +⚠ Imports only minimateplus.transport from the Series-3 package. Nothing +here may build or send a Series-3 frame -- SESSION_RESET (41 03) has never +been sent to a Micromate. +""" +from __future__ import annotations + +import logging +import time +from typing import Any, Callable, Optional, TypeVar + +from micromate.client import MicromateClient +from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport + +from .errors import CallHomeInProgress, WrongUnit, translate +from .models import UnitAddress +from .series import normalise_serial + +log = logging.getLogger("sfm.device_access") + +T = TypeVar("T") +RING = b"RADIO RING" +S4_DEFAULT_BAUD = 115200 + + +class RingDetected(Exception): + """The unit sent RADIO RING: it is calling home up this connection.""" + + +class RingWatchTransport(BaseTransport): + """Passes bytes through; raises RingDetected the moment RADIO RING appears, + including when it is split across two reads.""" + + def __init__(self, inner: BaseTransport) -> None: + self._inner = inner + self._tail = b"" + + def connect(self) -> None: + self._inner.connect() + + def disconnect(self) -> None: + self._inner.disconnect() + + @property + def is_connected(self) -> bool: + return self._inner.is_connected + + def write(self, data: bytes) -> None: + self._inner.write(data) + + def read(self, n: int) -> bytes: + data = self._inner.read(n) + if data: + window = self._tail + data + if RING in window: + self._tail = b"" + raise RingDetected("RADIO RING") + self._tail = window[-(len(RING) - 1):] + return data + + +def default_s4_client_factory(address: UnitAddress, recv_timeout: float = 10.0) -> MicromateClient: + if address.host: + inner: BaseTransport = TcpTransport(address.host, port=address.tcp_port) + else: + inner = SerialTransport(address.port, address.baud or S4_DEFAULT_BAUD) + return MicromateClient(RingWatchTransport(inner), recv_timeout=recv_timeout) + + +def _close(client: Any) -> None: + try: + client.close() + except Exception: # noqa: BLE001 + log.debug("close failed", exc_info=True) + + +_RING_MESSAGE = ("the unit started calling home; SFM hung up so the call can " + "reach THOR -- try again in a few minutes") + + +class Series4Session: + """One held line to one Micromate. + + `last_used` is the last *user* request: the idle hang-up measures it. + `last_traffic` is any exchange, keep-alives included: the keep-alive + schedule measures it. If keep-alives counted as use, the line would never + go idle. + """ + + def __init__(self, address: UnitAddress, serial: str, + client_factory: Callable[[UnitAddress], Any], + clock: Callable[[], float] = time.monotonic) -> None: + self.address = address + self.serial = normalise_serial(serial) + self._factory = client_factory + self._clock = clock + self._client: Optional[Any] = None + self.info = None + self.last_used = clock() + self.last_traffic = self.last_used + + @property + def is_open(self) -> bool: + return self._client is not None and self._client.is_open() + + def call_up(self): + client = self._factory(self.address) + try: + client.open() + info = client.connect() + except RingDetected as exc: + _close(client) + log.warning("RADIO RING from %s during call-up -- released the line", self.address.key) + raise CallHomeInProgress(_RING_MESSAGE) from exc + except Exception as exc: + _close(client) + raise translate(exc, connecting=True) from exc + if normalise_serial(info.serial) != self.serial: + _close(client) + raise WrongUnit(f"asked for {self.serial} but {info.serial} answered at {self.address.key}") + self._client, self.info = client, info + self.last_used = self.last_traffic = self._clock() + log.info("call-up: %s at %s, staying on the line", self.serial, self.address.key) + return info + + def _exchange(self, op: Callable[[Any], T]) -> T: + try: + return op(self._client) + except RingDetected as exc: + self.hang_up() + log.warning("RADIO RING from %s -- released the line so the call reaches THOR", + self.address.key) + raise CallHomeInProgress(_RING_MESSAGE) from exc + except Exception as exc: + self.hang_up() + raise translate(exc, connecting=False) from exc + + def run(self, op: Callable[[Any], T]) -> T: + """A user request. Calls up first if the line is not open.""" + if not self.is_open: + self.call_up() + result = self._exchange(op) + self.last_used = self.last_traffic = self._clock() + return result + + def keepalive(self) -> None: + """A POLL so the modem's idle timer does not drop the line. Not use.""" + if not self.is_open: + return + self._exchange(lambda c: c.protocol.poll()) + self.last_traffic = self._clock() + + def listen(self) -> None: + """Read anything the unit sent unprompted; send nothing. Not use.""" + if not self.is_open: + return + self._exchange(lambda c: c.read_unsolicited()) + + def hang_up(self) -> None: + if self._client is not None: + _close(self._client) + self._client = None + log.info("hang-up: %s at %s", self.serial, self.address.key) diff --git a/tests/test_device_access_s4.py b/tests/test_device_access_s4.py new file mode 100644 index 0000000..31b7f59 --- /dev/null +++ b/tests/test_device_access_s4.py @@ -0,0 +1,181 @@ +"""Series-4 sessions: one call-up, then stay on the line; ring safety.""" +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 micromate.protocol as mm_proto # noqa: E402 +from device_access_fakes import FakeMicromateClient # noqa: E402 +from sfm.device_access.errors import ( # noqa: E402 + CallHomeInProgress, ConnectFailed, NoAnswer, WrongUnit, +) +from sfm.device_access.models import UnitAddress # noqa: E402 +from sfm.device_access.s4 import ( # noqa: E402 + RingDetected, RingWatchTransport, Series4Session, +) + +ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None) + + +class ScriptedInner: + """A minimal real-interface transport: is_connected is a PROPERTY.""" + + def __init__(self, chunks): + self.chunks = list(chunks) + self.written = [] + self._c = False + + def connect(self): + self._c = True + + def disconnect(self): + self._c = False + + @property + def is_connected(self): + return self._c + + def write(self, data): + self.written.append(data) + + def read(self, n): + return self.chunks.pop(0) if self.chunks else b"" + + +class Clock: + def __init__(self, t=1000.0): + self.t = t + + def __call__(self): + return self.t + + +def session(*clients, clock=None): + queue = list(clients) + return Series4Session(ADDR, "UM20147", lambda address: queue.pop(0), clock=clock or Clock()) + + +# ── RingWatchTransport ──────────────────────────────────────────────────────── + +def test_ordinary_bytes_pass_through(): + t = RingWatchTransport(ScriptedInner([b"\x02abc\x03"])) + assert t.read(4096) == b"\x02abc\x03" + + +def test_a_ring_raises(): + t = RingWatchTransport(ScriptedInner([b"\r\nRADIO RING\r\n"])) + with pytest.raises(RingDetected): + t.read(4096) + + +def test_a_ring_split_across_reads_still_raises(): + t = RingWatchTransport(ScriptedInner([b"\r\nRADIO R", b"ING\r\n"])) + assert t.read(4096) == b"\r\nRADIO R" + with pytest.raises(RingDetected): + t.read(4096) + + +def test_the_wrapper_keeps_is_connected_a_property(): + inner = ScriptedInner([]) + t = RingWatchTransport(inner) + t.connect() + assert t.is_connected is True + + +# ── call-up ─────────────────────────────────────────────────────────────────── + +def test_call_up_verifies_the_serial_once(): + fake = FakeMicromateClient() + s = session(fake) + s.run(lambda c: c.get_state()) + s.run(lambda c: c.get_event_count()) + assert fake.calls == ["connect", "get_state", "get_event_count"] + assert fake.opened == 1 + + +def test_a_different_unit_answering_is_refused_and_closed(): + fake = FakeMicromateClient(serial="UM12947") + s = session(fake) + with pytest.raises(WrongUnit, match="UM20147.*UM12947"): + s.run(lambda c: c.get_state()) + assert fake.closed == 1 and not s.is_open + assert fake.calls == ["connect"] # nothing after the identity check + + +def test_a_failed_connect_is_connect_failed(): + s = session(FakeMicromateClient(open_error=ConnectionRefusedError("no"))) + with pytest.raises(ConnectFailed, match="could not connect"): + s.run(lambda c: c.get_state()) + + +# ── ring safety ─────────────────────────────────────────────────────────────── + +def test_a_ring_during_a_request_releases_the_line(): + fake = FakeMicromateClient() + s = session(fake) + s.call_up() + fake.fail = [RingDetected("RADIO RING")] + with pytest.raises(CallHomeInProgress, match="calling home"): + s.run(lambda c: c.get_state()) + assert not s.is_open and fake.closed == 1 + + +def test_listen_while_idle_releases_the_line_on_a_ring_and_sends_nothing(): + fake = FakeMicromateClient() + s = session(fake) + s.call_up() + fake.fail = [RingDetected("RADIO RING")] + with pytest.raises(CallHomeInProgress): + s.listen() + assert not s.is_open + assert fake.calls == ["connect", "read_unsolicited"] + + +def test_the_next_request_after_a_ring_calls_up_fresh(): + first, second = FakeMicromateClient(), FakeMicromateClient() + s = session(first, second) + s.call_up() + first.fail = [RingDetected("RADIO RING")] + with pytest.raises(CallHomeInProgress): + s.run(lambda c: c.get_state()) + s.run(lambda c: c.get_state()) + assert second.calls == ["connect", "get_state"] + + +# ── what counts as use ──────────────────────────────────────────────────────── + +def test_keepalive_and_listen_do_not_count_as_use(): + clock = Clock(1000.0) + fake = FakeMicromateClient() + s = session(fake, clock=clock) + s.call_up() + clock.t = 1060.0 + s.keepalive() + clock.t = 1065.0 + s.listen() + assert s.last_used == 1000.0 + assert s.last_traffic == 1060.0 + assert fake.calls == ["connect", "poll", "read_unsolicited"] + + +def test_a_request_counts_as_use(): + clock = Clock(1000.0) + s = session(FakeMicromateClient(), clock=clock) + s.call_up() + clock.t = 1100.0 + s.run(lambda c: c.get_state()) + assert s.last_used == 1100.0 and s.last_traffic == 1100.0 + + +def test_a_failure_mid_request_hangs_up(): + fake = FakeMicromateClient() + s = session(fake) + s.call_up() + fake.fail = [mm_proto.TimeoutError("quiet")] + with pytest.raises(NoAnswer): + s.run(lambda c: c.get_state()) + assert not s.is_open