GET /device/monitor/status?serial=UM...&run_state=true adds
detail.run_state = {code, name}. For the ring-path bench test: the code
during and after a call-home (0x01 for ~18 s after a stop, inferred to be
call-home attempts; 0x03 = calling home) is what the test watches. Opt-in
because it is one more round trip (~0.65 s on cellular); a plain status read
is unchanged. Series 3 has no 0x49 and ignores it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
332 lines
12 KiB
Python
332 lines
12 KiB
Python
"""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 _real_frame(payload_data: bytes, sub: int = 0xA4) -> bytes:
|
|
from micromate.framing import ETX, STX, checksum, stuff
|
|
payload = bytes([0x00, 0xC5, sub, 0x00, 0x00]) + payload_data
|
|
return bytes([STX]) + stuff(payload + bytes([checksum(payload)])) + bytes([ETX])
|
|
|
|
|
|
def test_a_ring_inside_a_frame_is_data_not_a_call_home():
|
|
# The 0x2C call-home config block's dial string is literally "RADIO RING".
|
|
wire = _real_frame(b"\x00" * 6 + b"RADIO RING" + b"\x00" * 4)
|
|
t = RingWatchTransport(ScriptedInner([wire]))
|
|
assert t.read(4096) == wire
|
|
|
|
|
|
def test_a_ring_inside_a_frame_split_across_reads_is_still_data():
|
|
wire = _real_frame(b"xxRADIO RINGyy")
|
|
cut = wire.index(b"RADIO R") + 7
|
|
t = RingWatchTransport(ScriptedInner([wire[:cut], wire[cut:]]))
|
|
assert t.read(4096) == wire[:cut]
|
|
assert t.read(4096) == wire[cut:]
|
|
|
|
|
|
def test_a_ring_between_frames_still_raises():
|
|
t = RingWatchTransport(ScriptedInner([_real_frame(b"abc") + b"\r\nRADIO RING\r\n"]))
|
|
with pytest.raises(RingDetected):
|
|
t.read(4096)
|
|
|
|
|
|
def test_a_ring_split_across_reads_after_a_frame_still_raises():
|
|
t = RingWatchTransport(ScriptedInner([_real_frame(b"abc") + b"\r\nRADIO R", b"ING\r\n"]))
|
|
t.read(4096)
|
|
with pytest.raises(RingDetected):
|
|
t.read(4096)
|
|
|
|
|
|
def test_a_ring_arriving_right_after_a_frame_ends_still_raises():
|
|
t = RingWatchTransport(ScriptedInner([_real_frame(b"abc"), b"RADIO RING"]))
|
|
t.read(4096)
|
|
with pytest.raises(RingDetected):
|
|
t.read(4096)
|
|
|
|
|
|
def test_an_escaped_etx_inside_a_frame_does_not_end_it():
|
|
# DLE ETX inside the payload is literal data; the ring after it is still inside.
|
|
wire = b"\x02" + b"ab\x10\x03RADIO RINGcd" + b"\x03"
|
|
t = RingWatchTransport(ScriptedInner([wire]))
|
|
assert t.read(4096) == wire
|
|
|
|
|
|
def test_a_ring_that_follows_a_frame_with_an_escaped_etx_still_raises():
|
|
wire = b"\x02" + b"ab\x10\x03cd" + b"\x03" + b"RADIO RING"
|
|
t = RingWatchTransport(ScriptedInner([wire]))
|
|
with pytest.raises(RingDetected):
|
|
t.read(4096)
|
|
|
|
|
|
def _real_chain_client(chunks):
|
|
from micromate.client import MicromateClient
|
|
inner = ScriptedInner(chunks)
|
|
return MicromateClient(RingWatchTransport(inner), recv_timeout=0.5), inner
|
|
|
|
|
|
def test_real_chain_a_response_carrying_a_ring_in_its_payload_succeeds():
|
|
client, _ = _real_chain_client([_real_frame(b"\x30" + b"\x00" * 8 + b"RADIO RING")])
|
|
client.open()
|
|
frame = client.protocol.poll()
|
|
assert b"RADIO RING" in frame.data
|
|
|
|
|
|
def test_real_chain_an_unsolicited_ring_before_the_response_hangs_up():
|
|
from types import SimpleNamespace
|
|
|
|
client, inner = _real_chain_client([b"\r\nRADIO RING\r\n", _real_frame(b"\x30" + b"\x00" * 8)])
|
|
# Only the identity read is stubbed; open/close/protocol/transport are the real chain.
|
|
client.connect = lambda: SimpleNamespace(serial="UM20147")
|
|
s = Series4Session(ADDR, "UM20147", lambda address: client, clock=Clock())
|
|
with pytest.raises(CallHomeInProgress):
|
|
s.run(lambda c: c.protocol.poll())
|
|
assert not s.is_open and not inner.is_connected
|
|
|
|
|
|
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_status_reads_0x49_only_when_asked():
|
|
# speed: 0x49 is one more round trip, so a plain status never reads it
|
|
fake = FakeMicromateClient(run_states=[0x01])
|
|
assert "run_state" not in s4_status(fake, "UM20147").detail
|
|
assert "read_run_state" not in fake.calls
|
|
st = s4_status(fake, "UM20147", run_state=True)
|
|
assert st.detail["run_state"] == {"code": 1, "name": "unknown(0x01)"}
|
|
|
|
|
|
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)
|
|
|
|
|
|
def test_a_new_request_clears_frame_state_left_by_a_stray_stx():
|
|
# A stray STX on an idle line would otherwise hide the ring that answers the
|
|
# next request. MicromateProtocol resets its own parser at every request too.
|
|
t = RingWatchTransport(ScriptedInner([b"\x02stray", b"\r\nRADIO RING\r\n"]))
|
|
t.connect()
|
|
t.read(64)
|
|
t.write(b"x")
|
|
with pytest.raises(RingDetected):
|
|
t.read(64)
|
|
|
|
|
|
def test_is_open_survives_a_hang_up_between_its_two_reads():
|
|
# held_serial() calls is_open without the unit lock; a concurrent hang-up can
|
|
# clear _client between the None check and the method call.
|
|
class Racy(Series4Session):
|
|
_reads = 0
|
|
|
|
@property
|
|
def _client(self):
|
|
Racy._reads += 1
|
|
return object.__new__(type("C", (), {"is_open": lambda s: True})) if Racy._reads == 1 else None
|
|
|
|
@_client.setter
|
|
def _client(self, value):
|
|
pass
|
|
|
|
s = Racy(ADDR, "UM20147", client_factory=lambda a: None)
|
|
assert s.is_open in (True, False)
|