feat(sfm): POST /device/settings/change; retire the legacy config write

DeviceAccess.change_settings refuses before any I/O a request with no
changes, a live change without its preview's revision, or no audit log,
then dispatches the series' change (never retried).  The route returns
the preview (fields old -> new, warnings, blocked, revision) or the
result (fields old/new/now), statuses as the other changes, and marks
the cached by-host config dirty after a live change.

/device/config and /device/config/project now answer 410 with a pointer.
Deleted with them: MiniMateClient.apply_config / set_project_info and
the raw-offset _encode_compliance_config (#46 found it wrong), the
lab script poc_set_project.py and experiments.py's EXP6, both of which
wrote a live unit through it.  Git keeps them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-03 21:51:20 -05:00
1 parent 66bb29b9d4
commit e8eabee4a2
10 files changed
+316 -749

No files matched your search

+33 -1
View File
@@ -9,7 +9,7 @@ import threading
import time
from typing import Any, Callable, Dict, Optional
from .errors import ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
from .errors import BadRequest, ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
from .events import parse_event_id
from .locks import UnitLocks
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo,
@@ -17,6 +17,7 @@ from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, Un
from .s3 import Series3Adapter, default_s3_client_factory
from .s4 import (
Series4Session, default_s4_client_factory, s4_call_home_state, s4_change_call_home, s4_change_monitoring,
s4_change_settings,
s4_download_event, s4_identify, s4_list_events, s4_settings, s4_status,
)
from .series import normalise_serial, series_for_serial
@@ -27,6 +28,9 @@ log = logging.getLogger("sfm.device_access")
# reads, a second apart -- not the start/stop window.
_CALL_HOME_VERIFY_TIMEOUT_S = 3.0
_CALL_HOME_VERIFY_INTERVAL_S = 1.0
# A settings read-back is one block read (seconds over cellular): two tries, a second apart.
_SETTINGS_VERIFY_TIMEOUT_S = 2.0
_SETTINGS_VERIFY_INTERVAL_S = 1.0
class DeviceAccess:
@@ -140,6 +144,34 @@ class DeviceAccess:
lambda c, s: s4_change_call_home(c, s, address=address, **kw),
change=True)
def change_settings(self, address: UnitAddress, serial: str, *, changes: dict,
revision: Optional[str], dry_run: bool = False,
caller: str = "api") -> ChangeResult:
"""Change the unit's settings (spec row 10, phase 5). A dry run is the
preview: old -> new per field and a `revision`. A live change needs that
revision; it is audited, identity-checked, sent once, never retried, and
read back. Refused before any I/O: no changes, a live call without a
revision, no audit log."""
serial = normalise_serial(serial)
series_for_serial(serial) # BadRequest (422) before anything else
if not isinstance(changes, dict) or not changes:
raise BadRequest("no settings to change -- nothing sent")
if not dry_run and not revision:
raise BadRequest("preview first: a live change needs the revision from its preview "
"-- nothing sent")
if not dry_run and self._audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
kw = dict(changes=changes, revision=revision, dry_run=dry_run, audit=self._audit,
caller=caller, sleep=self._sleep,
verify_timeout_s=_SETTINGS_VERIFY_TIMEOUT_S,
verify_interval_s=_SETTINGS_VERIFY_INTERVAL_S)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_settings(a, s, **kw),
lambda c, s: s4_change_settings(c, s, address=address, **kw),
change=True)
def held_serial(self, address: UnitAddress) -> Optional[str]:
"""Serial of the OPEN held Series-4 line at this address, else None. No I/O."""
with self._sessions_guard:
+50 -133
View File
@@ -50,7 +50,7 @@ import tempfile
import threading
import time
from pathlib import Path
from typing import Mapping, Optional
from typing import Any, Dict, Mapping, Optional
# FastAPI / Pydantic
try:
@@ -426,6 +426,7 @@ _SERIAL_AWARE_PATHS = frozenset({
"/device/events", "/device/events/download",
"/device/monitor/start", "/device/monitor/stop",
"/device/call_home/state", "/device/call_home/enable", "/device/call_home/disable",
"/device/settings/change",
})
@@ -1112,145 +1113,61 @@ def device_event_blastware_file(
# ── Write endpoints ───────────────────────────────────────────────────────────
class DeviceConfigBody(BaseModel):
"""
Request body for POST /device/config.
All fields are optional — only supplied (non-null) fields are written to
the device. All other config bytes are round-tripped verbatim.
Recording parameters
--------------------
recording_mode : Recording mode enum. Values: 0=Single Shot, 1=Continuous, 3=Histogram, 4=Histogram+Continuous.
sample_rate : Samples per second. Valid values: 1024, 2048, 4096.
record_time : Record duration in seconds (e.g. 1.0, 2.0, 3.0).
Trigger / alarm thresholds and range (geo channels)
----------------------------------------------------
trigger_level_geo : Trigger threshold in in/s (e.g. 0.5).
alarm_level_geo : Alarm threshold in in/s (e.g. 1.0).
geo_range : Geophone range/sensitivity. 0=Normal 10.000 in/s, 1=Sensitive 1.250 in/s.
Project / operator strings (max 41 ASCII characters each)
----------------------------
project : Project description.
client_name : Client / company name.
operator : Operator / technician name.
seis_loc : Sensor location description.
notes : Extended notes.
"""
# Recording parameters
recording_mode: Optional[int] = None
sample_rate: Optional[int] = None
record_time: Optional[float] = None
histogram_interval_sec: Optional[int] = None # seconds: 2, 5, 15, 60, 300, 900 (mode-gated)
# Threshold parameters / geo range
trigger_level_geo: Optional[float] = None
alarm_level_geo: Optional[float] = None
geo_range: Optional[int] = None # 0=Normal 10.000 in/s, 1=Sensitive 1.250 in/s
# Project / operator strings
project: Optional[str] = None
client_name: Optional[str] = None
operator: Optional[str] = None
seis_loc: Optional[str] = None
notes: Optional[str] = None
_CONFIG_RETIRED = ("retired: change a unit's settings by serial with POST /device/settings/change "
"(audited, previewed, read back)")
@app.post("/device/config")
def device_config(
body: DeviceConfigBody,
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: int = Query(38400, description="Serial baud rate"),
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_CHECK_DOC),
) -> dict:
"""
Read the current device config, apply any supplied changes to the compliance
block, and write the full config back.
Only non-null fields in the JSON body are modified. All other config bytes
are round-tripped verbatim from the device.
Supply either *port* (serial) or *host* (TCP/modem).
Example body (all fields optional — include only what you want to change):
{
"recording_mode": 1,
"sample_rate": 1024,
"record_time": 3.0,
"trigger_level_geo": 0.5,
"alarm_level_geo": 1.0,
"project": "Bridge Inspection 2026",
"client_name": "City of Portland",
"operator": "Brian Harrison",
"seis_loc": "South Abutment",
"notes": "Pre-blast baseline"
}
Returns:
{"status": "ok", "updated_fields": {...}} on success.
Raises:
502 on protocol errors (timeout, bad ack, etc.).
422 if neither port nor host is provided.
"""
changed = body.model_dump(exclude_none=True)
conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud)
log.info("POST /device/config port=%s host=%s fields=%s", port, host, list(changed.keys()))
try:
def _do():
with _build_client(port, baud, host, tcp_port) as client:
info = client.connect()
_require_series3(info.serial, serial)
client.apply_config(
recording_mode=body.recording_mode,
sample_rate=body.sample_rate,
record_time=body.record_time,
histogram_interval_sec=body.histogram_interval_sec,
trigger_level_geo=body.trigger_level_geo,
alarm_level_geo=body.alarm_level_geo,
geo_range=body.geo_range,
project=body.project,
client_name=body.client_name,
operator=body.operator,
seis_loc=body.seis_loc,
notes=body.notes,
)
_run_with_retry(_do, is_tcp=_is_tcp(host))
except HTTPException:
raise
except ProtocolError as exc:
raise HTTPException(status_code=502, detail=f"Protocol error: {exc}") from exc
except OSError as exc:
raise HTTPException(status_code=502, detail=f"Connection error: {exc}") from exc
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Device error: {exc}") from exc
# Config was written to the device — the cached compliance config is now stale.
conn_key = SFMCache.make_conn_key(host, tcp_port, port, baud)
get_cache().mark_config_dirty(conn_key)
return {
"status": "ok",
"updated_fields": changed,
}
def device_config() -> JSONResponse:
"""Retired (phase 5, 2026-11-03). It wrote a MiniMate's settings through an
encoder #46 found wrong, unaudited, with no read-back, retrying the whole
write on a TCP error. Use POST /device/settings/change."""
return JSONResponse(status_code=410, content={"detail": _CONFIG_RETIRED})
# Keep the old endpoint alive under its old URL for anything already calling it
@app.post("/device/config/project")
def device_config_project(
body: DeviceConfigBody,
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: int = Query(38400, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
def device_config_project() -> JSONResponse:
"""Retired with POST /device/config -- use POST /device/settings/change."""
return JSONResponse(status_code=410, content={"detail": _CONFIG_RETIRED})
class SettingsChangeBody(BaseModel):
"""POST /device/settings/change. `changes` maps field -> new value, using
the field names in GET /device/settings' `detail.editable`. `revision` is the
one a dry run (the preview) returned; a live change without it is refused."""
changes: Dict[str, Any]
revision: Optional[str] = None
@app.post("/device/settings/change")
def device_settings_change(
body: SettingsChangeBody,
serial: str = Query(..., description=_SERIAL_DOC),
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})"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""Deprecated alias for POST /device/config — use that instead."""
return device_config(body=body, port=port, baud=baud, host=host, tcp_port=tcp_port, serial=serial)
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
dry_run: bool = Query(False, description="Preview: old -> new and a revision; send nothing"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
"""Change a unit's settings by serial, both series (spec row 10, phase 5).
Preview first (`dry_run=true`): it reads the unit and returns, per field, the
value it holds and the value it would get, any warnings, anything that blocks
the change, and a `revision`. Then send the same body live with that
revision: identity read first, refused if the unit is monitoring or its
settings changed since the preview (409), sent once, never retried, read back.
Statuses as /device/monitor/start; a change that went out but was not
confirmed carries `sent` and `audit_id`."""
resp = _change_response(lambda: _device_access().change_settings(
_unit_address(port, baud, host, tcp_port), serial, changes=body.changes,
revision=body.revision, dry_run=dry_run, caller=caller or "api"))
if not dry_run:
try: # a by-host read must not serve stale settings
get_cache().mark_config_dirty(_live_cache.make_conn_key(host, tcp_port, port, baud))
except Exception as exc: # noqa: BLE001 -- the change's answer stands
log.warning("could not mark the cached config dirty: %s", exc)
return resp
# ── Monitoring endpoints ───────────────────────────────────────────────────────