feat(sfm): device_access core -- typed errors, series by serial prefix, shared models
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
fa032567c2
commit
034529f498
5 files changed
+241
No files matched your search
@@ -0,0 +1,7 @@
|
||||
"""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
|
||||
@@ -0,0 +1,63 @@
|
||||
"""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}")
|
||||
@@ -0,0 +1,68 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""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)"
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""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"
|
||||
Reference in new issue
Block a user