feat(sfm): list and download events by serial for both series
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
d84204f533
commit
39e0d312e5
2 files changed
+142
-3
No files matched your search
+43
-1
@@ -382,6 +382,7 @@ def _via_device_access(fn) -> dict:
|
||||
|
||||
_SERIAL_AWARE_PATHS = frozenset({
|
||||
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
|
||||
"/device/events", "/device/events/download",
|
||||
})
|
||||
|
||||
|
||||
@@ -571,13 +572,20 @@ def device_connect(
|
||||
@app.get("/device/events")
|
||||
def device_events(
|
||||
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})"),
|
||||
debug: bool = Query(False, description="Include raw record hex for field-layout inspection"),
|
||||
force: bool = Query(False, description="Bypass cache and re-download all events from device"),
|
||||
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
|
||||
) -> dict:
|
||||
"""
|
||||
**With `serial`** (UM... or BE.../BA...): the unit's events in the shared
|
||||
shape for either series, read from headers only -- no event is downloaded
|
||||
to list it -- and not cached. Each carries an `event_id` for
|
||||
POST /device/events/download. Without `serial`, the legacy Series-3
|
||||
behaviour below.
|
||||
|
||||
Connect to the device, read the event index, and download all stored
|
||||
events (event headers + full waveform records with peak values).
|
||||
|
||||
@@ -600,6 +608,10 @@ def device_events(
|
||||
If new events exist on the device, only the new ones are downloaded and merged.
|
||||
Pass *force=true* to bypass the cache entirely and re-download everything.
|
||||
"""
|
||||
if serial:
|
||||
return _via_device_access(
|
||||
lambda: _device_access().list_events(_unit_address(port, baud, host, tcp_port), serial))
|
||||
baud = 38400 if baud is None else baud
|
||||
log.info("GET /device/events port=%s host=%s debug=%s force=%s", port, host, debug, force)
|
||||
|
||||
cache = get_cache()
|
||||
@@ -1255,6 +1267,36 @@ def device_settings(
|
||||
lambda: _device_access().settings(_unit_address(port, baud, host, tcp_port), serial))
|
||||
|
||||
|
||||
@app.post("/device/events/download")
|
||||
def device_events_download(
|
||||
serial: str = Query(..., description=_SERIAL_DOC),
|
||||
event_id: str = Query(..., description="From GET /device/events?serial=..."),
|
||||
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:
|
||||
"""Download one event, check it, and store it in SFM's database.
|
||||
|
||||
Read-only on the unit. The stored file and waveform are then at
|
||||
/db/events/{db_event_id}/... . Storing an event that is already stored
|
||||
refreshes its row (`inserted: false`). The unit is busy for the whole
|
||||
download: other requests for it wait, then get 423.
|
||||
"""
|
||||
try:
|
||||
dl = _device_access().download_event(_unit_address(port, baud, host, tcp_port), serial, event_id)
|
||||
except DeviceError as exc:
|
||||
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
|
||||
try:
|
||||
out = persist_download(dl, store=_get_store(), db=_get_db())
|
||||
except Exception as exc:
|
||||
log.error("events/download: %s downloaded but not stored: %s", dl.event_id, exc, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"downloaded {dl.filename} from the unit but could not store it: {exc}") from exc
|
||||
return dataclasses.asdict(out)
|
||||
|
||||
|
||||
@app.post("/device/hangup")
|
||||
def device_hangup(
|
||||
port: Optional[str] = Query(None, description="Serial port"),
|
||||
|
||||
@@ -26,8 +26,8 @@ TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034)
|
||||
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)
|
||||
access = DeviceAccess(s3_client_factory=lambda a, **kw: s3q.pop(0),
|
||||
s4_client_factory=lambda a, **kw: s4q.pop(0), start_reaper=False)
|
||||
monkeypatch.setattr(srv, "_device_access_instance", access)
|
||||
return access
|
||||
|
||||
@@ -112,6 +112,7 @@ def test_guard_lets_a_series3_serial_through_on_legacy_routes():
|
||||
|
||||
@pytest.mark.parametrize("path", ["/device/info", "/device/connect",
|
||||
"/device/monitor/status", "/device/settings",
|
||||
"/device/events", "/device/events/download",
|
||||
"/device/hangup"])
|
||||
def test_guard_allows_um_serial_on_serial_aware_routes_and_hangup(path):
|
||||
assert srv._device_guard(path, {"serial": "UM20147", **Q_TCP}) is None
|
||||
@@ -157,3 +158,99 @@ def test_guard_ignores_an_unparseable_baud_when_checking_for_a_held_line(da):
|
||||
da.status(ADDR, "UM20147")
|
||||
out = srv._device_guard("/device/monitor/stop", {"baud": "38400.0", **Q_TCP})
|
||||
assert out is not None and out[0] == 409
|
||||
|
||||
|
||||
# ── events ────────────────────────────────────────────────────────────────────
|
||||
|
||||
from sfm.database import SeismoDb # noqa: E402
|
||||
from sfm.waveform_store import WaveformStore # noqa: E402
|
||||
|
||||
W_ID = "UM20147:055d4a81:20250531135901"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sdm(tmp_path, monkeypatch):
|
||||
db = SeismoDb(tmp_path / "seismo.db")
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
monkeypatch.setattr(srv, "_get_db", lambda: db)
|
||||
monkeypatch.setattr(srv, "_get_store", lambda: store)
|
||||
return store, db
|
||||
|
||||
|
||||
EV = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("serial,series", [("UM20147", 4), ("BE18193", 3)])
|
||||
def test_events_with_a_serial_return_the_shared_list(da, serial, series):
|
||||
out = srv.device_events(debug=False, force=False, serial=serial, **EV)
|
||||
assert (out["serial"], out["series"], len(out["events"])) == (serial, series, 2)
|
||||
assert set(out["events"][0]) == {"event_id", "serial", "series", "index", "timestamp",
|
||||
"record_type", "peak_vector_sum_ips", "peaks_ips",
|
||||
"filename", "detail"}
|
||||
|
||||
|
||||
def test_events_without_a_serial_run_the_legacy_path(monkeypatch):
|
||||
class Legacy(Exception):
|
||||
pass
|
||||
|
||||
def untouchable():
|
||||
raise AssertionError("DeviceAccess must not be used without a serial")
|
||||
|
||||
def legacy_cache():
|
||||
raise Legacy()
|
||||
monkeypatch.setattr(srv, "_device_access", untouchable)
|
||||
monkeypatch.setattr(srv, "get_cache", legacy_cache)
|
||||
with pytest.raises(Legacy):
|
||||
srv.device_events(debug=False, force=False, serial=None, **EV)
|
||||
|
||||
|
||||
def test_download_stores_the_event_and_says_where(da, sdm):
|
||||
out = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
assert out["inserted"] is True and out["verified"] is True
|
||||
assert out["stored_filename"] == "UM20147_20250531135901.IDFW"
|
||||
_store, db = sdm
|
||||
assert db.get_event(out["db_event_id"])["serial"] == "UM20147"
|
||||
|
||||
|
||||
def test_downloading_it_again_refreshes_the_same_row(da, sdm):
|
||||
first = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
again = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
assert again["inserted"] is False and again["db_event_id"] == first["db_event_id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_id,status", [
|
||||
("UM12947:055d4a81:20250531135901", 422), # another unit's event
|
||||
("garbage", 422),
|
||||
("UM20147:055d4a81:20240101000000", 409), # stale: erased since listed
|
||||
("UM20147:deadbeef:-", 404),
|
||||
])
|
||||
def test_download_errors_have_their_statuses(da, sdm, event_id, status):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
srv.device_events_download(serial="UM20147", event_id=event_id, **EV)
|
||||
assert ei.value.status_code == status
|
||||
assert sdm[1].query_events(serial="UM20147") == []
|
||||
|
||||
|
||||
def test_a_decode_that_disagrees_is_502_and_nothing_is_stored(da, sdm, monkeypatch):
|
||||
from micromate.client import DecodeMismatch
|
||||
|
||||
def mismatch(*a, **kw):
|
||||
raise DecodeMismatch("decoded PVS differs by +5%")
|
||||
fake = FakeMicromateClient()
|
||||
fake.fetch_event = mismatch
|
||||
monkeypatch.setattr(da, "_s4_factory", lambda a, **kw: fake)
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
assert ei.value.status_code == 502
|
||||
assert sdm[1].query_events(serial="UM20147") == []
|
||||
|
||||
|
||||
def test_a_store_failure_is_500_and_names_what_was_downloaded(da, sdm, monkeypatch):
|
||||
class BrokenStore:
|
||||
def save_imported_idf(self, *a, **kw):
|
||||
raise OSError("disk full")
|
||||
monkeypatch.setattr(srv, "_get_store", lambda: BrokenStore())
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
assert ei.value.status_code == 500
|
||||
assert "UM20147_20250531135901.IDFW" in ei.value.detail and "disk full" in ei.value.detail
|
||||
Reference in new issue
Block a user