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)"
|
||||
)
|
||||
Reference in new issue
Block a user