feat(sfm): serial-named /device/info, /status, /settings and /hangup for both series
With serial: one contract for Series 3 and 4 through sfm.device_access. Without it: the legacy Series-3 path, unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
73b6089012
commit
e7a5a3cce1
2 files changed
+179
-4
No files matched your search
+87
-4
@@ -13,6 +13,14 @@ GET /device/info POLL + serial number + full config read
|
||||
GET /device/events Download all stored events (headers + peak values)
|
||||
POST /device/connect Explicit connect/identify (same as /device/info)
|
||||
GET /device/event/{idx} Single event by index (header + waveform record)
|
||||
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.
|
||||
|
||||
Transport query params (supply one set):
|
||||
Serial (direct RS-232 cable):
|
||||
@@ -74,6 +82,8 @@ from sfm.database import SeismoDb
|
||||
from sfm.live_cache import LiveCache as _LiveCache
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm import db_snapshot
|
||||
import dataclasses
|
||||
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -340,6 +350,38 @@ def _run_with_retry(fn, *, is_tcp: bool):
|
||||
return fn() # let any second failure propagate normally
|
||||
|
||||
|
||||
# ── 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."
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _backfill_events(events: list, info: "DeviceInfo") -> None:
|
||||
@@ -404,10 +446,11 @@ def event_browser():
|
||||
@app.get("/device/info")
|
||||
def device_info(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5, /dev/ttyUSB0)"),
|
||||
baud: int = Query(38400, description="Serial baud rate (default 38400)"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay (e.g. 203.0.113.5)"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
force: bool = Query(False, description="Bypass cache and re-read from device"),
|
||||
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
|
||||
) -> dict:
|
||||
"""
|
||||
Connect to the device, perform the POLL startup handshake, and return
|
||||
@@ -421,6 +464,10 @@ def device_info(
|
||||
and re-read directly from the device (e.g. after a config push).
|
||||
The cache is also automatically invalidated after POST /device/config.
|
||||
"""
|
||||
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
|
||||
log.info("GET /device/info port=%s host=%s tcp_port=%d force=%s", port, host, tcp_port, force)
|
||||
|
||||
cache = get_cache()
|
||||
@@ -459,15 +506,20 @@ def device_info(
|
||||
@app.post("/device/connect")
|
||||
def device_connect(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: int = Query(38400, description="Serial baud rate"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
|
||||
) -> dict:
|
||||
"""
|
||||
Connect to the device and return identity. POST variant for terra-view
|
||||
compatibility with the SLMM proxy pattern.
|
||||
"""
|
||||
return device_info(port=port, baud=baud, host=host, tcp_port=tcp_port)
|
||||
# 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)
|
||||
|
||||
|
||||
@app.get("/device/events")
|
||||
@@ -1099,10 +1151,11 @@ def device_config_project(
|
||||
@app.get("/device/monitor/status")
|
||||
def device_monitor_status(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: int = Query(38400, description="Serial baud rate"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
force: bool = Query(False, description="Bypass cache and re-read from device"),
|
||||
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
|
||||
) -> dict:
|
||||
"""
|
||||
Read monitoring status from the device.
|
||||
@@ -1118,6 +1171,10 @@ def device_monitor_status(
|
||||
**Caching**: status is cached for 30 seconds to reduce cellular polling overhead.
|
||||
Pass *force=true* to bypass the cache for an immediate fresh read.
|
||||
"""
|
||||
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
|
||||
cache = get_cache()
|
||||
conn_key = SFMCache.make_conn_key(host, tcp_port, port, baud)
|
||||
|
||||
@@ -1160,6 +1217,32 @@ def device_monitor_status(
|
||||
return result
|
||||
|
||||
|
||||
@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))})
|
||||
|
||||
|
||||
@app.get("/device/events/storage_range")
|
||||
def device_events_storage_range(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""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}
|
||||
Reference in new issue
Block a user