Ten tasks, test-first: the is_open fix, two client reads, core types, the per-unit lock, both adapters, Series-4 sessions with ring safety, DeviceAccess with the reaper and the contract tests, the endpoints, and a read-only bench check on UM20147. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2401 lines
88 KiB
Markdown
2401 lines
88 KiB
Markdown
# SFM device access, phase 1a — Implementation Plan
|
||
|
||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||
|
||
**Goal:** SFM can identify a unit, read its status and read its settings
|
||
through one series-neutral contract. The unit is named by serial + address
|
||
and works the same for a Series 3 (`BE…`/`BA…`) or Series 4 (`UM…`) unit.
|
||
Micromates get a held session ("stay on the line").
|
||
|
||
**Architecture:** A new package `sfm/device_access/` sits between the
|
||
`/device/*` handlers and the two device libraries:
|
||
- The serial prefix picks a series adapter.
|
||
- A per-unit lock gives one connection per unit.
|
||
- Series-4 sessions stay open, with keep-alive, idle hang-up and ring safety.
|
||
- Every library exception becomes one of a few typed errors with a fixed HTTP
|
||
status.
|
||
|
||
Handlers take an optional `serial`. With it they return the shared models;
|
||
without it they run exactly as today.
|
||
|
||
**Tech Stack:** Python ≥ 3.10, FastAPI 0.135 (already used), pyserial (already
|
||
a dependency), pytest. No new dependencies.
|
||
|
||
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`.
|
||
This plan is phase **1a**. Event list/download (1b) and the webapp (1c) are
|
||
separate plans.
|
||
|
||
## Global Constraints
|
||
|
||
- **Reads only.** The Series-4 path may call only `connect()`, `get_state()`,
|
||
`get_setup()`, `get_event_count()`, `read_unsolicited()` and
|
||
`protocol.poll()`. The Series-3 path may call only `connect()`, `poll()` and
|
||
`get_monitor_status()`. Nothing that changes a unit is sent in this phase.
|
||
- **Never put Series-3 bytes on a Micromate's wire.** Nothing under
|
||
`sfm/device_access/s4.py` may import `minimateplus.protocol`,
|
||
`minimateplus.framing` or `minimateplus.client`. `SESSION_RESET` (`41 03`)
|
||
has never been sent to a Micromate. Only `minimateplus.transport` is shared.
|
||
- **Requests without `serial` behave exactly as today.** The legacy Series-3
|
||
code path in each handler is left untouched.
|
||
- Serial prefixes: `UM` → Series 4; `BE`, `BA` → Series 3; anything else →
|
||
422. Serials are compared after `.strip().upper()`.
|
||
- Timings (spec): lock wait **20 s**, keep-alive **60 s**, idle hang-up
|
||
**300 s**, reaper tick **5 s**.
|
||
- Error statuses (spec):
|
||
|
||
| status | when |
|
||
|---|---|
|
||
| 503 | could not connect / connection lost / unit started calling home |
|
||
| 504 | connected, the unit did not answer |
|
||
| 423 | unit busy |
|
||
| 409 | wrong unit |
|
||
| 422 | bad input |
|
||
| 502 | malformed reply |
|
||
| 501 | not supported yet |
|
||
|
||
- Default serial baud when the caller gives none: Series 3 **38400**, Series 4
|
||
**115200**.
|
||
- ⚠ **Handlers are called directly in tests.** Their FastAPI `Query(...)`
|
||
defaults are `FieldInfo` objects, not values, so every test call must pass
|
||
every parameter explicitly. The same applies to one handler calling
|
||
another. `httpx` is not installed, so `TestClient` tests are skipped
|
||
silently; do not use them.
|
||
- Feature branch: do **not** edit `CHANGELOG.md` (it is written on `dev` at
|
||
merge).
|
||
- Every commit message ends with:
|
||
```
|
||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
|
||
```
|
||
- Run tests with `.venv/bin/python -m pytest`. The full suite currently
|
||
reports **16 failed, 541 passed, 46 skipped**: the 16 failures are
|
||
pre-existing, in `test_bw_ascii_report.py` (15) and `test_event_file_io.py`
|
||
(1). That baseline must not change except by new passing tests.
|
||
|
||
## Review Focus
|
||
|
||
1. **A serial typed in lower case or with spaces** (`" um20147"`) is accepted
|
||
and treated as `UM20147`, never rejected → Task 3.
|
||
2. **Two requests for the same unit at once** (the webapp fires three): the
|
||
second waits, then gets 423. A second connection is never opened → Tasks 4
|
||
and 8.
|
||
3. **The modem dropped an idle line** (2-minute TCP idle timeout): the next
|
||
request calls up again quietly instead of failing → Task 8.
|
||
4. **A different unit answers at the address** (moved modem, stale IP): 409,
|
||
the connection is closed, and nothing further is sent → Tasks 5 and 6.
|
||
5. **`RADIO RING` arrives mid-request or while idle**: the line is released at
|
||
once, the caller gets a clear 503, and the next request calls up fresh →
|
||
Tasks 6 and 8.
|
||
|
||
---
|
||
|
||
## File Structure
|
||
|
||
| path | responsibility |
|
||
|---|---|
|
||
| `micromate/client.py` (modify) | fix `is_open()`; add `get_event_count()` and `read_unsolicited()` |
|
||
| `sfm/device_access/__init__.py` | public exports |
|
||
| `sfm/device_access/errors.py` | typed errors with HTTP statuses; `translate()` |
|
||
| `sfm/device_access/series.py` | serial normalisation; prefix → series |
|
||
| `sfm/device_access/models.py` | `UnitAddress`, `UnitInfo`, `UnitStatus`, `UnitSettings` |
|
||
| `sfm/device_access/locks.py` | per-unit lock with timeout |
|
||
| `sfm/device_access/s3.py` | Series-3 adapter (connect-per-request) |
|
||
| `sfm/device_access/s4.py` | `RingWatchTransport`, `Series4Session`, Series-4 operations |
|
||
| `sfm/device_access/access.py` | `DeviceAccess`: dispatch, sessions, hang-up, reaper |
|
||
| `sfm/server.py` (modify) | `serial` on `/device/info`, `/device/connect`, `/device/monitor/status`; new `GET /device/settings`, `POST /device/hangup` |
|
||
| `tests/device_access_fakes.py` | test-only fakes of both clients |
|
||
| `tests/test_device_access_core.py` | errors, series, models, locks |
|
||
| `tests/test_device_access_s3.py` | Series-3 adapter |
|
||
| `tests/test_device_access_s4.py` | ring watch, session, Series-4 operations |
|
||
| `tests/test_device_access.py` | `DeviceAccess` + contract tests |
|
||
| `tests/test_server_device_access.py` | handlers |
|
||
|
||
---
|
||
|
||
### Task 1: Fix `MicromateClient.is_open()`
|
||
|
||
`is_connected` is a **property** on `BaseTransport` (`minimateplus/transport.py:59`).
|
||
`MicromateClient.is_open()` *calls* it, so on every real transport it raises
|
||
`TypeError: 'bool' object is not callable`. The test double in
|
||
`tests/test_micromate_client.py` defines `is_connected` as a **method**,
|
||
which is why no test caught it. Sessions depend on `is_open()`.
|
||
|
||
**Files:**
|
||
- Modify: `micromate/client.py` (`is_open`, around line 130)
|
||
- Modify: `tests/test_micromate_client.py` (`ScriptedTransport`, around line 112; the test around line 406)
|
||
|
||
**Interfaces:**
|
||
- Produces: `MicromateClient.is_open() -> bool`, now correct on real transports.
|
||
|
||
- [ ] **Step 1: Make the test double match the real interface, and add a real-transport test**
|
||
|
||
In `tests/test_micromate_client.py`, change `ScriptedTransport.is_connected` to a property:
|
||
|
||
```python
|
||
@property
|
||
def is_connected(self) -> bool:
|
||
return self._connected
|
||
```
|
||
|
||
In `test_the_client_owns_the_transport` (around line 406), change
|
||
`t.is_connected()` to `t.is_connected`.
|
||
|
||
Then run `grep -n "is_connected" tests/test_micromate_*.py` and convert any
|
||
other method-style `is_connected` in those test doubles the same way.
|
||
|
||
Append this test:
|
||
|
||
```python
|
||
def test_is_open_works_on_a_real_transport():
|
||
"""`is_connected` is a PROPERTY on BaseTransport. is_open() used to call
|
||
it, which raised TypeError on every real transport -- hidden because the
|
||
test double defined it as a method."""
|
||
from minimateplus.transport import TcpTransport
|
||
|
||
mm = MicromateClient(TcpTransport("127.0.0.1", port=9)) # never connected
|
||
assert mm.is_open() is False
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_client.py -q`
|
||
Expected: `test_is_open_works_on_a_real_transport` and
|
||
`test_the_client_owns_the_transport` FAIL with
|
||
`TypeError: 'bool' object is not callable`.
|
||
|
||
- [ ] **Step 3: Fix `is_open`**
|
||
|
||
In `micromate/client.py`:
|
||
|
||
```python
|
||
def is_open(self) -> bool:
|
||
# `is_connected` is a PROPERTY on BaseTransport. Calling it raised
|
||
# TypeError on every real transport; only a test double that defined
|
||
# it as a method hid that.
|
||
return bool(self._transport.is_connected)
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_*.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
git add micromate/client.py tests/test_micromate_client.py
|
||
git commit -m "fix(micromate): is_open() called a property -- TypeError on every real transport" -m "Hidden because the test double defined is_connected as a method; it is now a property, matching BaseTransport." -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 2: Client additions for status and sessions
|
||
|
||
Two reads move into the client:
|
||
- `get_event_count()`. `0x06` content[0:4] is the event count: 3/3 against
|
||
the chain walk, and THOR's own `ReadEventRecordCount` agrees. Until now it
|
||
was decoded only in `bridges/mm_client_check.py`.
|
||
- `read_unsolicited()`. It reads whatever the unit sent unprompted, **sending
|
||
nothing**. The session uses it to notice `RADIO RING` while idle.
|
||
|
||
**Files:**
|
||
- Modify: `micromate/client.py` (constants near the other `_MS_*` constants; methods next to `get_state`)
|
||
- Test: `tests/test_micromate_client.py`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `MicromateClient.get_event_count() -> int`; raises `ProtocolError` if the content is under 4 bytes.
|
||
- `MicromateClient.read_unsolicited() -> bytes`; one transport read, nothing written.
|
||
|
||
- [ ] **Step 1: Capture a real `0x06` read from UM20147 (read-only)**
|
||
|
||
The bench unit is on `/dev/ttyACM0`; `dialout` needs `sg`. This sends only
|
||
reads.
|
||
|
||
```bash
|
||
cat > /tmp/mm_capture_0x06.py <<'EOF'
|
||
import sys
|
||
sys.path.insert(0, ".")
|
||
from minimateplus.transport import SerialTransport
|
||
from micromate.client import MicromateClient
|
||
|
||
with MicromateClient(SerialTransport("/dev/ttyACM0", 115200)) as mm:
|
||
mm.connect()
|
||
data = mm.protocol.read_storage_range()
|
||
refs = mm.list_events(with_records=False)
|
||
print("DATA_HEX =", data.hex())
|
||
print("CHAIN_WALK_COUNT =", len(refs))
|
||
EOF
|
||
sg dialout -c ".venv/bin/python /tmp/mm_capture_0x06.py"
|
||
```
|
||
|
||
Record both printed values. The expected count in the test is
|
||
`CHAIN_WALK_COUNT`: the chain walk is an independent count, never this
|
||
method's own output.
|
||
|
||
- [ ] **Step 2: Write the failing tests**
|
||
|
||
Append to `tests/test_micromate_client.py`. Paste the captured hex and count
|
||
where marked; both are values from Step 1, not choices.
|
||
|
||
```python
|
||
# ── get_event_count() / read_unsolicited() ────────────────────────────────────
|
||
|
||
# 0x06 response data captured from UM20147 (11.0BD) by Task 2, Step 1. The
|
||
# expected count is that session's independent chain-walk count.
|
||
SR_UM20147 = bytes.fromhex("PASTE DATA_HEX FROM STEP 1")
|
||
SR_UM20147_CHAIN_WALK_COUNT = 0 # replace 0 with CHAIN_WALK_COUNT from Step 1
|
||
|
||
|
||
def test_event_count_is_content_0_4_and_matches_the_chain_walk():
|
||
mm, t = client([frame(0xF9, SR_UM20147, flags=FLAGS_THOR)])
|
||
assert mm.get_event_count() == SR_UM20147_CHAIN_WALK_COUNT
|
||
assert [w[5] for w in t.written] == [0x06]
|
||
|
||
|
||
def test_a_truncated_storage_range_raises():
|
||
mm, _ = client([frame(0xF9, bytes(CONTENT) + b"\x00\x05", flags=FLAGS_THOR)])
|
||
with pytest.raises(ProtocolError, match="storage range"):
|
||
mm.get_event_count()
|
||
|
||
|
||
def test_read_unsolicited_sends_nothing_and_returns_what_arrived():
|
||
"""Used to spot RADIO RING on an idle session. It must never write."""
|
||
mm, t = client([b"\r\nRADIO RING\r\n"])
|
||
assert mm.read_unsolicited() == b"\r\nRADIO RING\r\n"
|
||
assert t.written == []
|
||
```
|
||
|
||
- [ ] **Step 3: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_client.py -q -k "event_count or storage_range or unsolicited"`
|
||
Expected: FAIL with `AttributeError: 'MicromateClient' object has no attribute 'get_event_count'`
|
||
(and the same for `read_unsolicited`).
|
||
|
||
- [ ] **Step 4: Implement**
|
||
|
||
In `micromate/client.py`, next to the `_MS_*` constants:
|
||
|
||
```python
|
||
# 0x06 storage range. content[0:4] is the event count: 3/3 against the chain
|
||
# walk, and THOR's ReadEventRecordCount agrees. content[4:8] is very likely
|
||
# the monitor-log count -- graded a strong candidate, not settled, so not exposed.
|
||
_SR_EVENT_COUNT = slice(0, 4)
|
||
```
|
||
|
||
And these methods, after `get_state`:
|
||
|
||
```python
|
||
def get_event_count(self) -> int:
|
||
"""`SUB 0x06` -- events stored. One read; no chain walk."""
|
||
c = _content(self._proto.read_storage_range())
|
||
if len(c) < 4:
|
||
raise ProtocolError(f"storage range content is {len(c)} B, need at least 4")
|
||
return int.from_bytes(c[_SR_EVENT_COUNT], "big")
|
||
|
||
def read_unsolicited(self) -> bytes:
|
||
"""Whatever the unit sent unprompted. **Sends nothing.**
|
||
|
||
One transport read. Bytes between commands are noise to the protocol
|
||
(every request resets the parser), so reading them here takes nothing
|
||
the protocol needs. A session calls this while idle to notice
|
||
RADIO RING without waiting for its next keep-alive.
|
||
"""
|
||
return self._transport.read(4096)
|
||
```
|
||
|
||
- [ ] **Step 5: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_*.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add micromate/client.py tests/test_micromate_client.py
|
||
git commit -m "feat(micromate): get_event_count() and read_unsolicited()" -m "0x06 content[0:4] moves from the bench tool into the client, tested against a real UM20147 read and its chain-walk count. read_unsolicited() reads without sending, for spotting RADIO RING on an idle session." -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 3: Core types — errors, series, models
|
||
|
||
**Files:**
|
||
- Create: `sfm/device_access/__init__.py`, `sfm/device_access/errors.py`, `sfm/device_access/series.py`, `sfm/device_access/models.py`
|
||
- Test: `tests/test_device_access_core.py`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `errors.py`: `DeviceError` (base, `.http_status`); subclasses `BadRequest` 422, `NotSupported` 501, `WrongUnit` 409, `UnitBusy` 423, `ConnectFailed` 503, `CallHomeInProgress` 503, `NoAnswer` 504, `MalformedReply` 502; and `translate(exc: BaseException, *, connecting: bool) -> DeviceError`.
|
||
- `series.py`: `normalise_serial(serial: str) -> str`; `series_for_serial(serial: str) -> int` (raises `BadRequest`).
|
||
- `models.py`: `UnitAddress(host: Optional[str], tcp_port: Optional[int], port: Optional[str], baud: Optional[int])` (frozen; `.key -> str`; raises `BadRequest` if neither host nor port); dataclasses `UnitInfo`, `UnitStatus`, `UnitSettings` (fields below).
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
Create `tests/test_device_access_core.py`:
|
||
|
||
```python
|
||
"""Core types of sfm.device_access: errors, series selection, 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 micromate.protocol as mm_proto # noqa: E402
|
||
import minimateplus.protocol as mmp_proto # noqa: E402
|
||
from sfm.device_access.errors import ( # noqa: E402
|
||
BadRequest, ConnectFailed, DeviceError, MalformedReply, NoAnswer, translate,
|
||
)
|
||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||
from sfm.device_access.series import normalise_serial, series_for_serial # noqa: E402
|
||
|
||
|
||
# ── series ────────────────────────────────────────────────────────────────────
|
||
|
||
@pytest.mark.parametrize(
|
||
"serial, series",
|
||
[("UM20147", 4), ("BE18193", 3), ("BA4521", 3), (" um20147 ", 4), ("be11529", 3)],
|
||
)
|
||
def test_the_prefix_picks_the_series(serial, series):
|
||
assert series_for_serial(serial) == series
|
||
|
||
|
||
def test_serials_are_normalised():
|
||
assert normalise_serial(" um20147\n") == "UM20147"
|
||
|
||
|
||
@pytest.mark.parametrize("serial", ["", "UM", "XX12345", "12345", "MP1234"])
|
||
def test_an_unknown_or_bare_prefix_is_a_bad_request(serial):
|
||
with pytest.raises(BadRequest, match="UM"):
|
||
series_for_serial(serial)
|
||
|
||
|
||
# ── errors ────────────────────────────────────────────────────────────────────
|
||
|
||
@pytest.mark.parametrize(
|
||
"exc, connecting, cls, status",
|
||
[
|
||
(mm_proto.TimeoutError("no frame"), False, NoAnswer, 504),
|
||
(mmp_proto.TimeoutError("no frame"), False, NoAnswer, 504),
|
||
(mm_proto.ChecksumError("bad"), False, MalformedReply, 502),
|
||
(mmp_proto.ProtocolError("bad"), False, MalformedReply, 502),
|
||
(ConnectionRefusedError("refused"), True, ConnectFailed, 503),
|
||
(OSError("reset"), False, ConnectFailed, 503),
|
||
],
|
||
)
|
||
def test_library_exceptions_translate_to_typed_errors(exc, connecting, cls, status):
|
||
out = translate(exc, connecting=connecting)
|
||
assert isinstance(out, cls)
|
||
assert out.http_status == status
|
||
|
||
|
||
def test_connect_and_mid_session_failures_read_differently():
|
||
assert "could not connect" in str(translate(OSError("x"), connecting=True))
|
||
assert "connection lost" in str(translate(OSError("x"), connecting=False))
|
||
|
||
|
||
def test_a_device_error_passes_through_unchanged():
|
||
e = NoAnswer("quiet")
|
||
assert translate(e, connecting=False) is e
|
||
|
||
|
||
def test_anything_else_becomes_a_plain_device_error():
|
||
out = translate(ValueError("boom"), connecting=False)
|
||
assert type(out) is DeviceError and out.http_status == 500
|
||
|
||
|
||
# ── models ────────────────────────────────────────────────────────────────────
|
||
|
||
def test_an_address_needs_a_host_or_a_port():
|
||
with pytest.raises(BadRequest):
|
||
UnitAddress(host=None, tcp_port=None, port=None, baud=None)
|
||
|
||
|
||
def test_the_lock_key_names_the_physical_link():
|
||
assert UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None).key == "tcp:10.0.0.5:9034"
|
||
assert UnitAddress(host=None, tcp_port=None, port="/dev/ttyACM0", baud=115200).key == "serial:/dev/ttyACM0"
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q`
|
||
Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access'`.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
`sfm/device_access/errors.py`:
|
||
|
||
```python
|
||
"""Typed device errors, each with the HTTP status the endpoints return."""
|
||
from __future__ import annotations
|
||
|
||
import micromate.protocol as _mm_proto
|
||
import minimateplus.protocol as _mmp_proto
|
||
|
||
|
||
class DeviceError(Exception):
|
||
http_status = 500
|
||
|
||
|
||
class BadRequest(DeviceError):
|
||
http_status = 422
|
||
|
||
|
||
class NotSupported(DeviceError):
|
||
http_status = 501
|
||
|
||
|
||
class WrongUnit(DeviceError):
|
||
http_status = 409
|
||
|
||
|
||
class UnitBusy(DeviceError):
|
||
http_status = 423
|
||
|
||
|
||
class ConnectFailed(DeviceError):
|
||
http_status = 503
|
||
|
||
|
||
class CallHomeInProgress(DeviceError):
|
||
http_status = 503
|
||
|
||
|
||
class NoAnswer(DeviceError):
|
||
http_status = 504
|
||
|
||
|
||
class MalformedReply(DeviceError):
|
||
http_status = 502
|
||
|
||
|
||
_TIMEOUTS = (_mm_proto.TimeoutError, _mmp_proto.TimeoutError)
|
||
_PROTOCOL = (_mm_proto.ProtocolError, _mmp_proto.ProtocolError)
|
||
|
||
|
||
def translate(exc: BaseException, *, connecting: bool) -> DeviceError:
|
||
"""Map a library exception to a typed error.
|
||
|
||
Order matters: each library's TimeoutError is a ProtocolError subclass, and
|
||
the builtin TimeoutError (a failed TCP connect) is an OSError.
|
||
"""
|
||
if isinstance(exc, DeviceError):
|
||
return exc
|
||
if isinstance(exc, _TIMEOUTS):
|
||
return NoAnswer(f"the unit did not answer: {exc}")
|
||
if isinstance(exc, _PROTOCOL):
|
||
return MalformedReply(f"bad reply from the unit: {exc}")
|
||
if isinstance(exc, OSError):
|
||
what = "could not connect" if connecting else "connection lost"
|
||
return ConnectFailed(f"{what}: {exc}")
|
||
return DeviceError(f"device error: {exc}")
|
||
```
|
||
|
||
`sfm/device_access/series.py`:
|
||
|
||
```python
|
||
"""Which series a unit is, from its serial prefix (decided with Brian, 2026-10-20)."""
|
||
from __future__ import annotations
|
||
|
||
from .errors import BadRequest
|
||
|
||
SERIES_BY_PREFIX = {"UM": 4, "BE": 3, "BA": 3}
|
||
|
||
|
||
def normalise_serial(serial: str) -> str:
|
||
return (serial or "").strip().upper()
|
||
|
||
|
||
def series_for_serial(serial: str) -> int:
|
||
s = normalise_serial(serial)
|
||
for prefix, series in SERIES_BY_PREFIX.items():
|
||
if s.startswith(prefix) and len(s) > len(prefix):
|
||
return series
|
||
raise BadRequest(
|
||
f"unknown serial {serial!r}: expected UM... (Series 4) or BE.../BA... (Series 3)"
|
||
)
|
||
```
|
||
|
||
`sfm/device_access/models.py`:
|
||
|
||
```python
|
||
"""Series-neutral models. Every operation returns the same shape for both
|
||
series; anything only one series has goes under `detail`."""
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Dict, Optional
|
||
|
||
from .errors import BadRequest
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class UnitAddress:
|
||
host: Optional[str]
|
||
tcp_port: Optional[int]
|
||
port: Optional[str]
|
||
baud: Optional[int]
|
||
|
||
def __post_init__(self) -> None:
|
||
if not self.host and not self.port:
|
||
raise BadRequest(
|
||
"specify 'host' (TCP, e.g. ?host=10.0.0.5&tcp_port=9034) "
|
||
"or 'port' (serial, e.g. ?port=/dev/ttyACM0)"
|
||
)
|
||
|
||
@property
|
||
def key(self) -> str:
|
||
"""One key per physical link -- what the per-unit lock is keyed on."""
|
||
if self.host:
|
||
return f"tcp:{self.host}:{self.tcp_port}"
|
||
return f"serial:{self.port}"
|
||
|
||
|
||
@dataclass
|
||
class UnitInfo:
|
||
serial: str
|
||
series: int
|
||
model: Optional[str]
|
||
firmware: Optional[str]
|
||
monitoring: Optional[bool]
|
||
active_setup: Optional[str]
|
||
detail: Dict[str, Any] = field(default_factory=dict)
|
||
|
||
|
||
@dataclass
|
||
class UnitStatus:
|
||
serial: str
|
||
series: int
|
||
monitoring: bool
|
||
battery_volts: Optional[float]
|
||
memory_total_bytes: Optional[int]
|
||
memory_free_bytes: Optional[int]
|
||
device_time: Optional[str] # ISO, the unit's own local time
|
||
event_count: Optional[int] # None where it is not cheap (Series 3)
|
||
detail: Dict[str, Any] = field(default_factory=dict)
|
||
|
||
|
||
@dataclass
|
||
class UnitSettings:
|
||
serial: str
|
||
series: int
|
||
setup_name: Optional[str]
|
||
record_mode: Optional[str] # the unit's own name for its mode
|
||
sample_rate: Optional[int]
|
||
record_time_s: Optional[float]
|
||
histogram_interval_s: Optional[int]
|
||
geo_trigger_ips: Optional[float]
|
||
notes: Dict[str, str] = field(default_factory=dict)
|
||
detail: Dict[str, Any] = field(default_factory=dict)
|
||
```
|
||
|
||
`sfm/device_access/__init__.py`:
|
||
|
||
```python
|
||
"""One door for every device request -- see the 2026-10-20 parity spec."""
|
||
from .errors import (
|
||
BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, MalformedReply,
|
||
NoAnswer, NotSupported, UnitBusy, WrongUnit, translate,
|
||
)
|
||
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||
from .series import normalise_serial, series_for_serial
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
git add sfm/device_access/ tests/test_device_access_core.py
|
||
git commit -m "feat(sfm): device_access core -- typed errors, series by serial prefix, shared models" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 4: One connection per unit — the per-unit lock
|
||
|
||
**Files:**
|
||
- Create: `sfm/device_access/locks.py`
|
||
- Test: `tests/test_device_access_core.py` (append)
|
||
|
||
**Interfaces:**
|
||
- Consumes: `UnitBusy` (Task 3).
|
||
- Produces: `UnitLocks(timeout: float = 20.0)` with
|
||
- `hold(key: str, timeout: Optional[float] = None)`, a context manager that raises `UnitBusy` on timeout;
|
||
- `try_hold(key: str)`, a non-blocking context manager that yields `bool`.
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
Append to `tests/test_device_access_core.py`:
|
||
|
||
```python
|
||
# ── per-unit lock ─────────────────────────────────────────────────────────────
|
||
|
||
import threading # noqa: E402
|
||
|
||
from sfm.device_access.errors import UnitBusy # noqa: E402
|
||
from sfm.device_access.locks import UnitLocks # noqa: E402
|
||
|
||
|
||
def test_a_second_request_for_a_busy_unit_gets_unit_busy():
|
||
locks = UnitLocks(timeout=0.2)
|
||
entered = threading.Event()
|
||
release = threading.Event()
|
||
|
||
def holder():
|
||
with locks.hold("tcp:10.0.0.5:9034"):
|
||
entered.set()
|
||
release.wait(2)
|
||
|
||
t = threading.Thread(target=holder)
|
||
t.start()
|
||
entered.wait(2)
|
||
try:
|
||
with pytest.raises(UnitBusy, match="busy"):
|
||
with locks.hold("tcp:10.0.0.5:9034"):
|
||
pass
|
||
finally:
|
||
release.set()
|
||
t.join()
|
||
|
||
|
||
def test_different_units_do_not_block_each_other():
|
||
locks = UnitLocks(timeout=0.2)
|
||
with locks.hold("tcp:10.0.0.5:9034"):
|
||
with locks.hold("tcp:10.0.0.6:9034"):
|
||
pass
|
||
|
||
|
||
def test_try_hold_never_waits():
|
||
locks = UnitLocks(timeout=5)
|
||
with locks.hold("k"):
|
||
with locks.try_hold("k") as got:
|
||
assert got is False
|
||
with locks.try_hold("k") as got:
|
||
assert got is True
|
||
|
||
|
||
def test_the_lock_is_released_after_an_exception():
|
||
locks = UnitLocks(timeout=0.2)
|
||
with pytest.raises(RuntimeError):
|
||
with locks.hold("k"):
|
||
raise RuntimeError("boom")
|
||
with locks.hold("k"):
|
||
pass
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q`
|
||
Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.locks'`.
|
||
|
||
- [ ] **Step 3: Implement** `sfm/device_access/locks.py`:
|
||
|
||
```python
|
||
"""One connection per unit. A modem allows a single TCP session, so two
|
||
requests must take turns instead of opening a second connection."""
|
||
from __future__ import annotations
|
||
|
||
import threading
|
||
from contextlib import contextmanager
|
||
from typing import Dict, Iterator, Optional
|
||
|
||
from .errors import UnitBusy
|
||
|
||
|
||
class UnitLocks:
|
||
def __init__(self, timeout: float = 20.0) -> None:
|
||
self._timeout = timeout
|
||
self._guard = threading.Lock()
|
||
self._locks: Dict[str, threading.Lock] = {}
|
||
|
||
def _lock_for(self, key: str) -> threading.Lock:
|
||
with self._guard:
|
||
return self._locks.setdefault(key, threading.Lock())
|
||
|
||
@contextmanager
|
||
def hold(self, key: str, timeout: Optional[float] = None) -> Iterator[None]:
|
||
lock = self._lock_for(key)
|
||
wait = self._timeout if timeout is None else timeout
|
||
if not lock.acquire(timeout=wait):
|
||
raise UnitBusy(f"the unit at {key} is busy with another request; try again shortly")
|
||
try:
|
||
yield
|
||
finally:
|
||
lock.release()
|
||
|
||
@contextmanager
|
||
def try_hold(self, key: str) -> Iterator[bool]:
|
||
lock = self._lock_for(key)
|
||
got = lock.acquire(blocking=False)
|
||
try:
|
||
yield got
|
||
finally:
|
||
if got:
|
||
lock.release()
|
||
```
|
||
|
||
Add to `sfm/device_access/__init__.py`: `from .locks import UnitLocks`
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
git add sfm/device_access/locks.py sfm/device_access/__init__.py tests/test_device_access_core.py
|
||
git commit -m "feat(sfm): per-unit lock -- one connection per unit, 423 when busy" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 5: The Series-3 adapter
|
||
|
||
Connect-per-request, as today. The TCP cold-boot retry-once from
|
||
`server._run_with_retry` is kept, but **narrowed to "no answer"**, the
|
||
cold-boot symptom. The legacy path retries any protocol error, which here
|
||
would also retry the adapter's own "no settings block" error. When the serial is already in
|
||
hand (`connect()` reads it), a mismatch is refused with 409. No extra round
|
||
trip is added just to check it.
|
||
|
||
**Files:**
|
||
- Create: `sfm/device_access/s3.py`, `tests/device_access_fakes.py`
|
||
- Test: `tests/test_device_access_s3.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `UnitAddress`, `UnitInfo`, `UnitStatus`, `UnitSettings`, the errors and `translate` (Task 3).
|
||
- Produces:
|
||
- `Series3Adapter(client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory)` with `identify(address, serial) -> UnitInfo`, `status(address, serial) -> UnitStatus` and `settings(address, serial) -> UnitSettings`. `serial` is already normalised.
|
||
- `default_s3_client_factory(address, timeout=10.0) -> MiniMateClient`.
|
||
- `tests/device_access_fakes.py`: `FakeMiniMateClient`, `FakeMicromateClient` (the latter is used from Task 6).
|
||
|
||
- [ ] **Step 1: Write the test fakes**
|
||
|
||
Create `tests/device_access_fakes.py`. These are test utilities, never
|
||
imported by production code. They return the **real** model dataclasses, and
|
||
the Micromate fake's setup comes from a real fixture read:
|
||
|
||
```python
|
||
"""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
|
||
```
|
||
|
||
- [ ] **Step 2: Write the failing tests**
|
||
|
||
Create `tests/test_device_access_s3.py`:
|
||
|
||
```python
|
||
"""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")
|
||
```
|
||
|
||
- [ ] **Step 3: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_s3.py -q`
|
||
Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.s3'`.
|
||
|
||
- [ ] **Step 4: Implement** `sfm/device_access/s3.py`:
|
||
|
||
```python
|
||
"""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 BaseException as exc:
|
||
_close(client)
|
||
raise translate(exc, connecting=True) from exc
|
||
try:
|
||
return fn(client)
|
||
except DeviceError:
|
||
raise
|
||
except BaseException 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)
|
||
```
|
||
|
||
- [ ] **Step 5: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_s3.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add sfm/device_access/s3.py tests/device_access_fakes.py tests/test_device_access_s3.py
|
||
git commit -m "feat(sfm): Series-3 adapter -- identify, status, settings into the shared models" -m "Connect-per-request with the TCP cold-boot retry kept; a different unit answering is refused (409) whenever the serial is already in hand." -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 6: Series-4 session — stay on the line, ring safety
|
||
|
||
**Files:**
|
||
- Create: `sfm/device_access/s4.py` (session part)
|
||
- Test: `tests/test_device_access_s4.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: errors and `translate`, `normalise_serial`, `UnitAddress` (Task 3); `MicromateClient.is_open()` (Task 1); `read_unsolicited()` (Task 2); `FakeMicromateClient` (Task 5).
|
||
- Produces:
|
||
- `RingDetected(Exception)`.
|
||
- `RingWatchTransport(inner: BaseTransport)`, a `BaseTransport` whose `read()` raises `RingDetected` on `b"RADIO RING"`, including when it is split across reads.
|
||
- `Series4Session(address, serial, client_factory, clock=time.monotonic)` with:
|
||
- `call_up() -> MicromateDeviceInfo` (raises `WrongUnit` and `CallHomeInProgress`);
|
||
- `run(op: Callable[[client], T]) -> T` (a user request; calls up first if needed);
|
||
- `keepalive()`, which is a POLL and does not count as use;
|
||
- `listen()`, which reads only and does not count as use;
|
||
- `hang_up()`;
|
||
- properties `is_open`, `last_used`, `last_traffic`.
|
||
- `default_s4_client_factory(address, recv_timeout=10.0) -> MicromateClient`, with its transport wrapped in `RingWatchTransport`.
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
Create `tests/test_device_access_s4.py`:
|
||
|
||
```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 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
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q`
|
||
Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.s4'`.
|
||
|
||
- [ ] **Step 3: Implement** `sfm/device_access/s4.py` (session part):
|
||
|
||
```python
|
||
"""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 BaseException 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 BaseException 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)
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
git add sfm/device_access/s4.py tests/test_device_access_s4.py
|
||
git commit -m "feat(sfm): Series-4 session -- call up once, stay on the line, release on RADIO RING" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 7: Series-4 operations — identify, status, settings
|
||
|
||
**Files:**
|
||
- Modify: `sfm/device_access/s4.py` (append)
|
||
- Test: `tests/test_device_access_s4.py` (append)
|
||
|
||
**Interfaces:**
|
||
- Consumes: `UnitInfo`, `UnitStatus`, `UnitSettings` (Task 3); client methods from Tasks 1 and 2 and `get_setup()`.
|
||
- Produces, each run inside `Series4Session.run`:
|
||
- `s4_identify(client, serial: str) -> UnitInfo`
|
||
- `s4_status(client, serial: str) -> UnitStatus`
|
||
- `s4_settings(client, serial: str) -> UnitSettings`
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
Append to `tests/test_device_access_s4.py`. The settings values are what the
|
||
operator read off UM20147's screen for `um20147_baseline` (see
|
||
`tests/test_micromate_setup.py`):
|
||
|
||
```python
|
||
# ── 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)
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q`
|
||
Expected: collection ERROR, `ImportError: cannot import name 's4_identify'`.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
Append to `sfm/device_access/s4.py`, and add `UnitInfo, UnitSettings, UnitStatus`
|
||
to its `.models` import:
|
||
|
||
```python
|
||
# ── Operations (each runs inside Series4Session.run) ──────────────────────────
|
||
|
||
def s4_identify(client: Any, serial: str) -> UnitInfo:
|
||
info = client.connect()
|
||
return UnitInfo(
|
||
serial=info.serial, series=4, model=info.model,
|
||
firmware=None, # the version string lives in 0x01, undecoded
|
||
monitoring=info.monitoring, active_setup=info.active_setup,
|
||
detail={"manufacturer": info.manufacturer, "firmware_line": info.firmware_line},
|
||
)
|
||
|
||
|
||
def s4_status(client: Any, serial: str) -> UnitStatus:
|
||
st = client.get_state()
|
||
count = client.get_event_count()
|
||
return UnitStatus(
|
||
serial=serial, series=4, monitoring=st.monitoring, battery_volts=st.battery_volts,
|
||
memory_total_bytes=st.memory_total_bytes, memory_free_bytes=st.memory_free_bytes,
|
||
device_time=st.device_time.isoformat() if st.device_time else None,
|
||
event_count=count,
|
||
)
|
||
|
||
|
||
def s4_settings(client: Any, serial: str) -> UnitSettings:
|
||
s = client.get_setup()
|
||
return UnitSettings(
|
||
serial=serial, series=4, setup_name=s.name, record_mode=s.record_mode_name,
|
||
sample_rate=s.sample_rate, record_time_s=s.record_time_s,
|
||
histogram_interval_s=s.histogram_interval_s,
|
||
geo_trigger_ips=s.geo_trigger_ips[0], # the keypad writes all three the same
|
||
notes=dict(s.notes),
|
||
detail={
|
||
"pretrigger_s": s.pretrigger_s,
|
||
"auto_record_stop": s.auto_record_stop,
|
||
"auto_stop_after_s": s.auto_stop_after_s,
|
||
"geophones_active": s.geophones_active,
|
||
"mic_active": s.mic_active,
|
||
"trigger_on_geophones": s.trigger_on_geophones,
|
||
"trigger_on_mic": s.trigger_on_mic,
|
||
"geo_trigger_ips_per_channel": list(s.geo_trigger_ips),
|
||
"mic_type": s.mic_type,
|
||
"mic_trigger_psi": s.mic_trigger_psi,
|
||
"mic_trigger_db": s.mic_trigger_db,
|
||
"job_number_enabled": s.job_number_enabled,
|
||
"job_number": s.job_number,
|
||
"scaled_distance_enabled": s.scaled_distance_enabled,
|
||
"distance_ft": s.distance_ft,
|
||
"charge_weight_lb": s.charge_weight_lb,
|
||
"scaled_distance": s.scaled_distance,
|
||
},
|
||
)
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
git add sfm/device_access/s4.py tests/test_device_access_s4.py
|
||
git commit -m "feat(sfm): Series-4 identify, status and settings into the shared models" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 8: `DeviceAccess` — one door, sessions, the reaper
|
||
|
||
**Files:**
|
||
- Create: `sfm/device_access/access.py`
|
||
- Test: `tests/test_device_access.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: everything from Tasks 3–7.
|
||
- Produces: `DeviceAccess(*, s3_client_factory=default_s3_client_factory, s4_client_factory=default_s4_client_factory, clock=time.monotonic, lock_timeout=20.0, keepalive_s=60.0, idle_hangup_s=300.0, reaper_interval_s=5.0, start_reaper=True)` with:
|
||
- `identify(address: UnitAddress, serial: str) -> UnitInfo`
|
||
- `status(address, serial) -> UnitStatus`
|
||
- `settings(address, serial) -> UnitSettings`
|
||
- `hang_up(address) -> bool`, True if a held line was closed
|
||
- `tick(now: Optional[float] = None) -> None`, for tests; the reaper thread calls it.
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
Create `tests/test_device_access.py`:
|
||
|
||
```python
|
||
"""DeviceAccess: dispatch by serial, sessions, the lock, the reaper -- and the
|
||
contract that both series answer in the same shape."""
|
||
from __future__ import annotations
|
||
|
||
import dataclasses
|
||
import os
|
||
import sys
|
||
import threading
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402
|
||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||
from sfm.device_access.errors import BadRequest, CallHomeInProgress, UnitBusy # noqa: E402
|
||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||
from sfm.device_access.s4 import RingDetected # noqa: E402
|
||
|
||
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
|
||
|
||
|
||
class Clock:
|
||
def __init__(self, t=1000.0):
|
||
self.t = t
|
||
|
||
def __call__(self):
|
||
return self.t
|
||
|
||
|
||
def access(s3=(), s4=(), clock=None, lock_timeout=0.2):
|
||
s3q, s4q = list(s3), list(s4)
|
||
return DeviceAccess(
|
||
s3_client_factory=lambda a: s3q.pop(0),
|
||
s4_client_factory=lambda a: s4q.pop(0),
|
||
clock=clock or Clock(), lock_timeout=lock_timeout, start_reaper=False,
|
||
)
|
||
|
||
|
||
def test_the_serial_prefix_picks_the_adapter():
|
||
da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()])
|
||
assert da.identify(ADDR, "be18193").series == 3
|
||
assert da.identify(ADDR, " um20147").series == 4
|
||
|
||
|
||
def test_an_unknown_prefix_never_touches_a_unit():
|
||
da = access()
|
||
with pytest.raises(BadRequest):
|
||
da.identify(ADDR, "XX123")
|
||
|
||
|
||
def test_a_micromate_stays_on_the_line_between_requests():
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake])
|
||
da.identify(ADDR, "UM20147")
|
||
da.status(ADDR, "UM20147")
|
||
da.settings(ADDR, "UM20147")
|
||
assert fake.opened == 1 # one call-up, three requests
|
||
assert fake.calls[0] == "connect"
|
||
|
||
|
||
def test_a_minimate_reconnects_per_request():
|
||
a, b = FakeMiniMateClient(), FakeMiniMateClient()
|
||
da = access(s3=[a, b])
|
||
da.status(ADDR, "BE18193")
|
||
da.status(ADDR, "BE18193")
|
||
assert a.closed == 1 and b.closed == 1
|
||
|
||
|
||
def test_a_dropped_line_is_called_up_again_quietly():
|
||
first, second = FakeMicromateClient(), FakeMicromateClient()
|
||
da = access(s4=[first, second])
|
||
da.status(ADDR, "UM20147")
|
||
first._open = False # the modem dropped the idle line
|
||
st = da.status(ADDR, "UM20147")
|
||
assert st.series == 4 and second.opened == 1
|
||
|
||
|
||
def test_a_different_serial_at_the_same_address_hangs_up_the_old_line():
|
||
first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947")
|
||
da = access(s4=[first, second])
|
||
da.status(ADDR, "UM20147")
|
||
da.status(ADDR, "UM12947")
|
||
assert first.closed == 1 and second.opened == 1
|
||
|
||
|
||
def test_a_busy_unit_answers_423_without_a_second_connection():
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake], lock_timeout=0.2)
|
||
entered, release = threading.Event(), threading.Event()
|
||
|
||
def slow_request():
|
||
with da._locks.hold(ADDR.key): # simulate a request in flight
|
||
entered.set()
|
||
release.wait(2)
|
||
|
||
t = threading.Thread(target=slow_request)
|
||
t.start()
|
||
entered.wait(2)
|
||
try:
|
||
with pytest.raises(UnitBusy):
|
||
da.status(ADDR, "UM20147")
|
||
assert fake.opened == 0 # no second connection was opened
|
||
finally:
|
||
release.set()
|
||
t.join()
|
||
|
||
|
||
def test_hang_up_closes_a_held_line():
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake])
|
||
da.status(ADDR, "UM20147")
|
||
assert da.hang_up(ADDR) is True
|
||
assert fake.closed == 1
|
||
assert da.hang_up(ADDR) is False # nothing left to hang up
|
||
|
||
|
||
# ── the reaper ────────────────────────────────────────────────────────────────
|
||
|
||
def test_tick_listens_then_keeps_alive_then_hangs_up_when_idle():
|
||
clock = Clock(1000.0)
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake], clock=clock)
|
||
da.status(ADDR, "UM20147")
|
||
fake.calls.clear()
|
||
|
||
clock.t = 1030.0
|
||
da.tick() # quiet: listen only
|
||
assert fake.calls == ["read_unsolicited"]
|
||
|
||
clock.t = 1061.0
|
||
da.tick() # 60 s since traffic: keep-alive
|
||
assert fake.calls[-1] == "poll"
|
||
|
||
clock.t = 1301.0
|
||
da.tick() # 300 s since last USE: hang up
|
||
assert fake.closed == 1
|
||
assert da.hang_up(ADDR) is False
|
||
|
||
|
||
def test_tick_releases_the_line_on_a_ring_while_idle():
|
||
clock = Clock(1000.0)
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake], clock=clock)
|
||
da.status(ADDR, "UM20147")
|
||
fake.fail = [RingDetected("RADIO RING")]
|
||
clock.t = 1010.0
|
||
da.tick()
|
||
assert fake.closed == 1
|
||
|
||
|
||
def test_tick_skips_a_unit_that_is_busy():
|
||
clock = Clock(1000.0)
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake], clock=clock)
|
||
da.status(ADDR, "UM20147")
|
||
fake.calls.clear()
|
||
clock.t = 1400.0
|
||
with da._locks.hold(ADDR.key):
|
||
da.tick() # must not block or hang up mid-request
|
||
assert fake.calls == [] and fake.closed == 0
|
||
|
||
|
||
def test_a_ring_mid_request_is_a_clear_error():
|
||
fake = FakeMicromateClient()
|
||
da = access(s4=[fake])
|
||
da.status(ADDR, "UM20147")
|
||
fake.fail = [RingDetected("RADIO RING")]
|
||
with pytest.raises(CallHomeInProgress):
|
||
da.status(ADDR, "UM20147")
|
||
|
||
|
||
# ── the contract: both series answer in the same shape ────────────────────────
|
||
|
||
@pytest.mark.parametrize("op", ["identify", "status", "settings"])
|
||
def test_both_series_return_the_same_model_with_the_same_fields(op):
|
||
da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()])
|
||
s3 = getattr(da, op)(ADDR, "BE18193")
|
||
s4 = getattr(da, op)(ADDR, "UM20147")
|
||
assert type(s3) is type(s4)
|
||
assert [f.name for f in dataclasses.fields(s3)] == [f.name for f in dataclasses.fields(s4)]
|
||
assert (s3.series, s4.series) == (3, 4)
|
||
for name in (f.name for f in dataclasses.fields(s3)):
|
||
a, b = getattr(s3, name), getattr(s4, name)
|
||
if a is not None and b is not None and name != "detail":
|
||
assert type(a) is type(b) or {type(a), type(b)} <= {int, float}, name
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access.py -q`
|
||
Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.access'`.
|
||
|
||
- [ ] **Step 3: Implement** `sfm/device_access/access.py`:
|
||
|
||
```python
|
||
"""DeviceAccess -- the one door every device request passes through.
|
||
|
||
The control surface does not care which series it is talking to; this does.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import threading
|
||
import time
|
||
from typing import Any, Callable, Dict, Optional
|
||
|
||
from .errors import DeviceError
|
||
from .locks import UnitLocks
|
||
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||
from .s3 import Series3Adapter, default_s3_client_factory
|
||
from .s4 import (
|
||
Series4Session, default_s4_client_factory, s4_identify, s4_settings, s4_status,
|
||
)
|
||
from .series import normalise_serial, series_for_serial
|
||
|
||
log = logging.getLogger("sfm.device_access")
|
||
|
||
|
||
class DeviceAccess:
|
||
def __init__(
|
||
self, *,
|
||
s3_client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory,
|
||
s4_client_factory: Callable[[UnitAddress], Any] = default_s4_client_factory,
|
||
clock: Callable[[], float] = time.monotonic,
|
||
lock_timeout: float = 20.0,
|
||
keepalive_s: float = 60.0,
|
||
idle_hangup_s: float = 300.0,
|
||
reaper_interval_s: float = 5.0,
|
||
start_reaper: bool = True,
|
||
) -> None:
|
||
self._locks = UnitLocks(lock_timeout)
|
||
self._s3 = Series3Adapter(s3_client_factory)
|
||
self._s4_factory = s4_client_factory
|
||
self._clock = clock
|
||
self._keepalive_s = keepalive_s
|
||
self._idle_hangup_s = idle_hangup_s
|
||
self._reaper_interval_s = reaper_interval_s
|
||
self._start_reaper = start_reaper
|
||
self._reaper: Optional[threading.Thread] = None
|
||
self._sessions: Dict[str, Series4Session] = {}
|
||
self._sessions_guard = threading.Lock()
|
||
|
||
# ── public operations ─────────────────────────────────────────────────────
|
||
|
||
def identify(self, address: UnitAddress, serial: str) -> UnitInfo:
|
||
return self._dispatch(address, serial, self._s3.identify, s4_identify)
|
||
|
||
def status(self, address: UnitAddress, serial: str) -> UnitStatus:
|
||
return self._dispatch(address, serial, self._s3.status, s4_status)
|
||
|
||
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
|
||
return self._dispatch(address, serial, self._s3.settings, s4_settings)
|
||
|
||
def hang_up(self, address: UnitAddress) -> bool:
|
||
with self._locks.hold(address.key):
|
||
with self._sessions_guard:
|
||
session = self._sessions.pop(address.key, None)
|
||
if session is None:
|
||
return False
|
||
was_open = session.is_open
|
||
session.hang_up()
|
||
return was_open
|
||
|
||
# ── dispatch ──────────────────────────────────────────────────────────────
|
||
|
||
def _dispatch(self, address: UnitAddress, serial: str,
|
||
s3_op: Callable[[UnitAddress, str], Any],
|
||
s4_op: Callable[[Any, str], Any]) -> Any:
|
||
serial = normalise_serial(serial)
|
||
series = series_for_serial(serial) # raises BadRequest before any I/O
|
||
with self._locks.hold(address.key):
|
||
if series == 3:
|
||
return s3_op(address, serial)
|
||
session = self._session_for(address, serial)
|
||
try:
|
||
return session.run(lambda client: s4_op(client, serial))
|
||
except DeviceError:
|
||
if not session.is_open:
|
||
with self._sessions_guard:
|
||
if self._sessions.get(address.key) is session:
|
||
del self._sessions[address.key]
|
||
raise
|
||
|
||
def _session_for(self, address: UnitAddress, serial: str) -> Series4Session:
|
||
with self._sessions_guard:
|
||
session = self._sessions.get(address.key)
|
||
if session is not None and session.serial != serial:
|
||
session.hang_up()
|
||
session = None
|
||
if session is None:
|
||
session = Series4Session(address, serial, self._s4_factory, clock=self._clock)
|
||
self._sessions[address.key] = session
|
||
self._ensure_reaper()
|
||
return session
|
||
|
||
# ── the reaper ────────────────────────────────────────────────────────────
|
||
|
||
def tick(self, now: Optional[float] = None) -> None:
|
||
"""Per held line: hang up if idle, else keep alive, else listen for a ring."""
|
||
now = self._clock() if now is None else now
|
||
with self._sessions_guard:
|
||
items = list(self._sessions.items())
|
||
for key, session in items:
|
||
with self._locks.try_hold(key) as held:
|
||
if not held:
|
||
continue # mid-request: not idle
|
||
if not session.is_open:
|
||
self._drop(key, session)
|
||
continue
|
||
try:
|
||
if now - session.last_used >= self._idle_hangup_s:
|
||
session.hang_up()
|
||
self._drop(key, session)
|
||
elif now - session.last_traffic >= self._keepalive_s:
|
||
session.keepalive()
|
||
else:
|
||
session.listen()
|
||
except DeviceError as exc:
|
||
log.warning("held line %s closed: %s", key, exc)
|
||
self._drop(key, session)
|
||
|
||
def _drop(self, key: str, session: Series4Session) -> None:
|
||
with self._sessions_guard:
|
||
if self._sessions.get(key) is session:
|
||
del self._sessions[key]
|
||
|
||
def _ensure_reaper(self) -> None:
|
||
if not self._start_reaper or self._reaper is not None:
|
||
return
|
||
self._reaper = threading.Thread(target=self._reaper_loop, name="sfm-held-lines", daemon=True)
|
||
self._reaper.start()
|
||
|
||
def _reaper_loop(self) -> None:
|
||
while True:
|
||
time.sleep(self._reaper_interval_s)
|
||
try:
|
||
self.tick()
|
||
except Exception: # noqa: BLE001
|
||
log.exception("held-line reaper tick failed")
|
||
```
|
||
|
||
Add to `sfm/device_access/__init__.py`: `from .access import DeviceAccess`
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_device_access*.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
git add sfm/device_access/access.py sfm/device_access/__init__.py tests/test_device_access.py
|
||
git commit -m "feat(sfm): DeviceAccess -- one door, held Series-4 lines, a reaper, and the same answer shape for both series" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 9: The endpoints
|
||
|
||
`serial` routes a request through `DeviceAccess`. Without it, every handler
|
||
runs exactly as today.
|
||
|
||
**Files:**
|
||
- Modify: `sfm/server.py`:
|
||
- imports;
|
||
- module docstring;
|
||
- `device_info` (~line 405), `device_connect` (~line 460) and `device_monitor_status` (~line 1100);
|
||
- two new handlers after `device_monitor_status`.
|
||
- Test: `tests/test_server_device_access.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `DeviceAccess`, `UnitAddress`, `DeviceError` (Tasks 3, 8).
|
||
- Produces:
|
||
- query parameter `serial` on `GET /device/info`, `POST /device/connect` and `GET /device/monitor/status`;
|
||
- `GET /device/settings` (`serial` required);
|
||
- `POST /device/hangup`;
|
||
- module-level `_device_access() -> DeviceAccess` and the `_device_access_instance` singleton, so tests can monkeypatch them.
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
Create `tests/test_server_device_access.py`:
|
||
|
||
```python
|
||
"""Handlers called directly -- every parameter passed explicitly, because
|
||
FastAPI Query() defaults are FieldInfo objects, not values."""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import sys
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from fastapi import HTTPException # noqa: E402
|
||
|
||
import sfm.server as srv # noqa: E402
|
||
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402
|
||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||
from sfm.device_access.errors import ( # noqa: E402
|
||
BadRequest, CallHomeInProgress, ConnectFailed, MalformedReply, NoAnswer,
|
||
NotSupported, UnitBusy, WrongUnit,
|
||
)
|
||
|
||
TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034)
|
||
|
||
|
||
@pytest.fixture
|
||
def da(monkeypatch):
|
||
s3q = [FakeMiniMateClient() for _ in range(5)]
|
||
s4q = [FakeMicromateClient() for _ in range(5)]
|
||
access = DeviceAccess(s3_client_factory=lambda a: s3q.pop(0),
|
||
s4_client_factory=lambda a: s4q.pop(0), start_reaper=False)
|
||
monkeypatch.setattr(srv, "_device_access_instance", access)
|
||
return access
|
||
|
||
|
||
def test_info_with_a_serial_returns_the_shared_model(da):
|
||
out = srv.device_info(force=False, serial="UM20147", **TCP)
|
||
assert out["series"] == 4 and out["serial"] == "UM20147"
|
||
assert set(out) == {"serial", "series", "model", "firmware", "monitoring", "active_setup", "detail"}
|
||
|
||
|
||
def test_connect_passes_the_serial_through(da):
|
||
out = srv.device_connect(serial="BE18193", **TCP)
|
||
assert out["series"] == 3
|
||
|
||
|
||
def test_status_and_settings_with_a_serial(da):
|
||
assert srv.device_monitor_status(force=False, serial="UM20147", **TCP)["event_count"] == 5
|
||
assert srv.device_settings(serial="UM20147", **TCP)["record_mode"] == "Histogram Combo"
|
||
|
||
|
||
def test_hangup(da):
|
||
srv.device_monitor_status(force=False, serial="UM20147", **TCP)
|
||
assert srv.device_hangup(**TCP) == {"hung_up": True}
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"exc, status",
|
||
[(BadRequest("x"), 422), (NotSupported("x"), 501), (WrongUnit("x"), 409),
|
||
(UnitBusy("x"), 423), (ConnectFailed("x"), 503), (CallHomeInProgress("x"), 503),
|
||
(NoAnswer("x"), 504), (MalformedReply("x"), 502)],
|
||
)
|
||
def test_typed_errors_become_their_http_status(monkeypatch, exc, status):
|
||
class Raising:
|
||
def identify(self, address, serial):
|
||
raise exc
|
||
monkeypatch.setattr(srv, "_device_access_instance", Raising())
|
||
with pytest.raises(HTTPException) as ei:
|
||
srv.device_info(force=False, serial="UM20147", **TCP)
|
||
assert ei.value.status_code == status
|
||
|
||
|
||
def test_a_missing_address_is_a_422(da):
|
||
with pytest.raises(HTTPException) as ei:
|
||
srv.device_settings(serial="UM20147", port=None, baud=None, host=None, tcp_port=9034)
|
||
assert ei.value.status_code == 422
|
||
|
||
|
||
def test_without_a_serial_the_legacy_path_runs_unchanged(monkeypatch):
|
||
"""No serial: today's Series-3 code path, today's response shape.
|
||
DeviceAccess must not be touched."""
|
||
class Untouchable:
|
||
def __getattr__(self, name):
|
||
raise AssertionError("DeviceAccess used on the legacy path")
|
||
|
||
class Cache:
|
||
def get_device_info(self, key):
|
||
return {"serial": "BE18193", "firmware_version": "S338.17"}
|
||
|
||
monkeypatch.setattr(srv, "_device_access_instance", Untouchable())
|
||
monkeypatch.setattr(srv, "get_cache", lambda: Cache())
|
||
out = srv.device_info(force=False, serial=None, **TCP)
|
||
assert out == {"serial": "BE18193", "firmware_version": "S338.17", "_cached": True}
|
||
```
|
||
|
||
- [ ] **Step 2: Run the tests and watch them fail**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q`
|
||
Expected: FAIL. `device_info() got an unexpected keyword argument 'serial'`,
|
||
and `module 'sfm.server' has no attribute 'device_settings'`.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
In `sfm/server.py`, after the existing `from sfm import db_snapshot` import:
|
||
|
||
```python
|
||
import dataclasses
|
||
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
|
||
```
|
||
|
||
After `_run_with_retry` (the "Transport factory" section):
|
||
|
||
```python
|
||
# ── Device access (serial-named requests) ─────────────────────────────────────
|
||
# A request that names the unit by `serial` goes through sfm.device_access:
|
||
# same contract for Series 3 and 4. Without `serial`, handlers run their
|
||
# legacy Series-3 path unchanged (spec 2026-10-20).
|
||
|
||
_device_access_instance: Optional[DeviceAccess] = None
|
||
|
||
|
||
def _device_access() -> DeviceAccess:
|
||
global _device_access_instance
|
||
if _device_access_instance is None:
|
||
_device_access_instance = DeviceAccess()
|
||
return _device_access_instance
|
||
|
||
|
||
def _unit_address(port: Optional[str], baud: Optional[int], host: Optional[str],
|
||
tcp_port: int) -> UnitAddress:
|
||
return UnitAddress(host=host, tcp_port=tcp_port if host else None,
|
||
port=None if host else port, baud=baud)
|
||
|
||
|
||
def _via_device_access(fn) -> dict:
|
||
try:
|
||
result = fn()
|
||
except DeviceError as exc:
|
||
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
|
||
return dataclasses.asdict(result) if dataclasses.is_dataclass(result) else result
|
||
|
||
|
||
_SERIAL_DOC = "Unit serial -- UM... (Series 4) or BE.../BA... (Series 3). Returns the shared model."
|
||
```
|
||
|
||
`device_info`:
|
||
- change `baud: int = Query(38400, ...)` to
|
||
`baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)")`;
|
||
- add `serial: Optional[str] = Query(None, description=_SERIAL_DOC)` as the last parameter;
|
||
- make these the first lines of the body, before the existing `log.info`:
|
||
|
||
```python
|
||
if serial:
|
||
return _via_device_access(
|
||
lambda: _device_access().identify(_unit_address(port, baud, host, tcp_port), serial))
|
||
baud = 38400 if baud is None else baud
|
||
```
|
||
|
||
`device_connect`: the same `baud` change, add the same `serial` parameter, and
|
||
replace its body with:
|
||
|
||
```python
|
||
# force=True PRESERVES today's behaviour: the old call omitted `force`, so it
|
||
# received FastAPI's Query(False) object, which is truthy -- /device/connect
|
||
# has always bypassed the cache. Passing False here would quietly change that.
|
||
return device_info(port=port, baud=baud, host=host, tcp_port=tcp_port,
|
||
force=True, serial=serial)
|
||
```
|
||
|
||
`device_monitor_status`: the same `baud` change, add `serial` as the last
|
||
parameter, and make these the first lines of the body:
|
||
|
||
```python
|
||
if serial:
|
||
return _via_device_access(
|
||
lambda: _device_access().status(_unit_address(port, baud, host, tcp_port), serial))
|
||
baud = 38400 if baud is None else baud
|
||
```
|
||
|
||
Add after `device_monitor_status`:
|
||
|
||
```python
|
||
@app.get("/device/settings")
|
||
def device_settings(
|
||
serial: str = Query(..., description=_SERIAL_DOC),
|
||
port: Optional[str] = Query(None, description="Serial port (e.g. /dev/ttyACM0)"),
|
||
baud: Optional[int] = Query(None, description="Serial baud (default by series)"),
|
||
host: Optional[str] = Query(None, description="TCP host -- modem IP"),
|
||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||
) -> dict:
|
||
"""The unit's recording settings, in the shared shape for either series."""
|
||
return _via_device_access(
|
||
lambda: _device_access().settings(_unit_address(port, baud, host, tcp_port), serial))
|
||
|
||
|
||
@app.post("/device/hangup")
|
||
def device_hangup(
|
||
port: Optional[str] = Query(None, description="Serial port"),
|
||
baud: Optional[int] = Query(None, description="Serial baud"),
|
||
host: Optional[str] = Query(None, description="TCP host -- modem IP"),
|
||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||
) -> dict:
|
||
"""Hang up a held line now instead of waiting for the idle timeout.
|
||
`hung_up` is false if nothing was being held."""
|
||
return _via_device_access(
|
||
lambda: {"hung_up": _device_access().hang_up(_unit_address(port, baud, host, tcp_port))})
|
||
```
|
||
|
||
In the module docstring's endpoint list, add:
|
||
|
||
```
|
||
GET /device/settings Recording settings (requires serial)
|
||
POST /device/hangup Hang up a held Series-4 line
|
||
|
||
`serial` on /device/info, /device/connect, /device/monitor/status and
|
||
/device/settings names the unit (UM... = Series 4, BE.../BA... = Series 3) and
|
||
returns the shared model. Without it, the legacy Series-3 behaviour is
|
||
unchanged. Series-4 lines are held open between requests and hung up after
|
||
5 idle minutes, on POST /device/hangup, or the moment the unit calls home.
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass**
|
||
|
||
Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Run the full suite**
|
||
|
||
Run: `.venv/bin/python -m pytest tests -q`
|
||
Expected: the baseline plus the new tests. Still exactly **16 failed**, the
|
||
same two files (`test_bw_ascii_report.py` 15, `test_event_file_io.py` 1).
|
||
More passed.
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add sfm/server.py tests/test_server_device_access.py
|
||
git commit -m "feat(sfm): serial-named /device/info, /status, /settings and /hangup for both series" -m "With serial: one contract for Series 3 and 4 through sfm.device_access. Without it: the legacy Series-3 path, unchanged." -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 10: Bench check on UM20147, and the record
|
||
|
||
Read-only, on the real unit, through the real server.
|
||
|
||
**Files:**
|
||
- Modify: `CLAUDE.md` (the Series-4 config bullet in "Where things stand")
|
||
|
||
- [ ] **Step 1: Start SFM with access to the unit's port**
|
||
|
||
```bash
|
||
sg dialout -c ".venv/bin/python -m uvicorn sfm.server:app --port 8299" &
|
||
sleep 3
|
||
```
|
||
|
||
- [ ] **Step 2: Identify, status, settings by serial, then hang up**
|
||
|
||
```bash
|
||
Q="port=/dev/ttyACM0&serial=UM20147"
|
||
curl -s "localhost:8299/device/info?$Q" | python3 -m json.tool
|
||
curl -s "localhost:8299/device/monitor/status?$Q" | python3 -m json.tool
|
||
curl -s "localhost:8299/device/settings?$Q" | python3 -m json.tool
|
||
curl -s -X POST "localhost:8299/device/hangup?port=/dev/ttyACM0" ; echo
|
||
```
|
||
|
||
Expected:
|
||
- `series: 4`, `serial: "UM20147"`.
|
||
- The settings match `bridges/mm_client_check.py`'s output and the unit's
|
||
screen. On 2026-10-20: Histogram Combo, 2048 sps, record time 11 s,
|
||
pre-trigger 0.25 s, geophone trigger 0.6 in/s, mic 140 dB, job number 1234
|
||
(off), Location BENCH01.
|
||
- `event_count` equals the chain-walk count from Task 2.
|
||
- The server log shows **one** call-up for the three requests, then a
|
||
hang-up.
|
||
- The hang-up response is `{"hung_up": true}`.
|
||
|
||
- [ ] **Step 3: Ask for the wrong serial**
|
||
|
||
```bash
|
||
curl -s -w "\n%{http_code}\n" "localhost:8299/device/info?port=/dev/ttyACM0&serial=UM12947"
|
||
```
|
||
|
||
Expected: `409`, with "asked for UM12947 but UM20147 answered".
|
||
|
||
- [ ] **Step 4: Stop the server**
|
||
|
||
```bash
|
||
kill %1
|
||
```
|
||
|
||
- [ ] **Step 5: Record it in CLAUDE.md**
|
||
|
||
In "Where things stand", in the Series-4 config bullet, add this after the
|
||
`get_setup()` line:
|
||
|
||
```
|
||
✅ **SFM speaks Series 4 by serial (phase 1a, 2026-10-20):** `/device/info`,
|
||
`/device/monitor/status` and `/device/settings` take `serial` and return one
|
||
shared shape for both series through `sfm/device_access/`. Micromate lines
|
||
are held open (one call-up, keep-alive 60 s, idle hang-up 5 min, released on
|
||
RADIO RING); MiniMates still reconnect per request. Without `serial` the
|
||
legacy Series-3 path is unchanged. Next: 1b (events), 1c (webapp).
|
||
```
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add CLAUDE.md
|
||
git commit -m "docs(claude): SFM speaks Series 4 by serial -- phase 1a done, bench-checked on UM20147" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44"
|
||
```
|