"""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 # ── operations ──────────────────────────────────────────────────────────────── from sfm.device_access.s4 import s4_identify, s4_settings, s4_status # noqa: E402 def test_s4_identify(): info = s4_identify(FakeMicromateClient(monitoring=True), "UM20147") assert (info.serial, info.series, info.model, info.monitoring) == ("UM20147", 4, "MM/ISEE/S", True) assert info.active_setup == "test2.MMB" assert info.firmware is None and info.detail["firmware_line"] == "thor" def test_s4_status_includes_the_cheap_event_count(): st = s4_status(FakeMicromateClient(events=5), "UM20147") assert (st.series, st.monitoring, st.battery_volts, st.event_count) == (4, False, 3.8, 5) assert (st.memory_total_bytes, st.memory_free_bytes) == (15_000_000, 14_799_296) assert st.device_time == "2026-10-20T18:07:58" def test_s4_settings_maps_the_decoded_setup(): s = s4_settings(FakeMicromateClient(), "UM20147") assert (s.series, s.setup_name, s.record_mode) == (4, "test2.MMB", "Histogram Combo") assert (s.sample_rate, s.record_time_s, s.histogram_interval_s) == (1024, 10.0, 2) assert s.geo_trigger_ips == pytest.approx(0.5, abs=1e-6) assert list(s.notes) == ["Location", "Client", "Company", "General Notes"] assert s.detail["pretrigger_s"] == 1.0 assert s.detail["mic_type"] == "linear" assert s.detail["mic_trigger_db"] == pytest.approx(131.0, abs=0.01) assert s.detail["geo_trigger_ips_per_channel"] == pytest.approx([0.5, 0.5, 0.5], abs=1e-6)