THOR's watcher (and Blastware's ACH) store every event through
/db/import/idf_file and /db/import/blastware_file, with the paired report.
Storing a download of the same event afterwards overwrote that richer copy:
on Series 4 the file, .h5 and sidecar were rewritten (extensions dropped);
on Series 3 the row lost PVS, project strings and ZC frequencies and was
repointed at a second, review-less file set.
persist_download now looks up (serial, timestamp) first. A row there is
returned as it stands -- inserted false, detail.already_stored true -- with
no store call, no insert_events and no sidecar write. Never merge.
- DownloadedEvent gains `timestamp` (the unit's own event time) and
`record` (Series 4's 0x0C fields); both adapters set them.
- The Series-3 `event is None` guard now runs before backfill/save, with a
message that is true there ("nothing was stored").
- Tests build the watcher's state exactly as the import endpoints do and
prove the row dict, the sidecar bytes and the file mtimes are unchanged.
No schema change, no migration, no codec change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
211 lines
9.6 KiB
Python
211 lines
9.6 KiB
Python
"""Series-3 adapter. Connect-per-request, as SFM has always done for
|
|
MiniMates -- a held session waits for the bench test in the spec."""
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import logging
|
|
import struct
|
|
from typing import Any, Callable, Optional
|
|
|
|
from minimateplus import MiniMateClient
|
|
from minimateplus.blastware_file import blastware_filename
|
|
from minimateplus.transport import TcpTransport
|
|
|
|
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate
|
|
from .events import iso_of, make_event_id, stamp_of
|
|
from .models import DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
|
|
|
log = logging.getLogger("sfm.device_access")
|
|
|
|
S3_DEFAULT_BAUD = 38400
|
|
S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "Histogram + Continuous"}
|
|
|
|
|
|
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
|
|
|
|
|
|
def default_s3_client_factory(address: UnitAddress, timeout: Optional[float] = None) -> MiniMateClient:
|
|
if address.host:
|
|
return MiniMateClient(transport=TcpTransport(address.host, port=address.tcp_port),
|
|
timeout=10.0 if timeout is None else timeout)
|
|
if timeout is None:
|
|
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD)
|
|
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD, timeout=timeout)
|
|
|
|
|
|
def _close(client: Any) -> None:
|
|
try:
|
|
client.close()
|
|
except Exception: # noqa: BLE001
|
|
log.debug("close failed", exc_info=True)
|
|
|
|
|
|
def _s3_dt(ev: Any) -> Optional[datetime.datetime]:
|
|
ts = getattr(ev, "timestamp", None)
|
|
if ts is None or ts.hour is None:
|
|
return None
|
|
try:
|
|
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _s3_filename(ev: Any, serial: str) -> Optional[str]:
|
|
try:
|
|
return blastware_filename(ev, serial)
|
|
except Exception: # noqa: BLE001
|
|
return None
|
|
|
|
|
|
def _s3_ref(ev: Any, serial: str) -> EventRef:
|
|
dt = _s3_dt(ev)
|
|
pv = ev.peak_values
|
|
peaks = {}
|
|
if pv is not None:
|
|
peaks = {k: v for k, v in (("tran", pv.tran), ("vert", pv.vert), ("long", pv.long))
|
|
if v is not None}
|
|
return EventRef(
|
|
event_id=make_event_id(serial, ev._waveform_key, stamp_of(dt)),
|
|
serial=serial, series=3, index=ev.index, timestamp=iso_of(dt),
|
|
record_type=ev.record_type.lower() if ev.record_type else None,
|
|
peak_vector_sum_ips=pv.peak_vector_sum if pv is not None else None,
|
|
peaks_ips=peaks, filename=_s3_filename(ev, serial),
|
|
detail={"mic_psi": pv.micl if pv is not None else None},
|
|
)
|
|
|
|
|
|
class Series3Adapter:
|
|
def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None:
|
|
self._factory = client_factory
|
|
|
|
def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any:
|
|
def attempt() -> Any:
|
|
client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)
|
|
try:
|
|
client.open()
|
|
except Exception as exc:
|
|
_close(client)
|
|
raise translate(exc, connecting=True) from exc
|
|
try:
|
|
return fn(client)
|
|
except DeviceError:
|
|
raise
|
|
except Exception as exc:
|
|
raise translate(exc, connecting=False) from exc
|
|
finally:
|
|
_close(client)
|
|
|
|
try:
|
|
return attempt()
|
|
except NoAnswer:
|
|
# A MiniMate that has just had its serial lines asserted can take
|
|
# 5-10 s to boot, and shows it as silence; one retry covers it. TCP
|
|
# only -- on a serial cable a silence is a real fault. Narrower than
|
|
# server._run_with_retry (any protocol error): retrying a
|
|
# MalformedReply would also retry "no settings block", which a
|
|
# reconnect cannot fix.
|
|
if not address.host:
|
|
raise
|
|
log.info("Series 3 at %s: no clean answer, retrying once (unit may be cold)", address.key)
|
|
return attempt()
|
|
|
|
@staticmethod
|
|
def _check(serial_reported: str, serial: str, address: UnitAddress) -> None:
|
|
if (serial_reported or "").strip().upper() != serial:
|
|
raise WrongUnit(f"asked for {serial} but {serial_reported} answered at {address.key}")
|
|
|
|
def identify(self, address: UnitAddress, serial: str) -> UnitInfo:
|
|
def op(client: Any) -> UnitInfo:
|
|
info = client.connect()
|
|
self._check(info.serial, serial, address)
|
|
cc = info.compliance_config
|
|
return UnitInfo(
|
|
serial=info.serial, series=3, model=info.model, firmware=info.firmware_version,
|
|
monitoring=None, active_setup=cc.setup_name if cc else None,
|
|
detail={"manufacturer": info.manufacturer, "dsp_version": info.dsp_version},
|
|
)
|
|
return self._run(address, op)
|
|
|
|
def status(self, address: UnitAddress, serial: str) -> UnitStatus:
|
|
def op(client: Any) -> UnitStatus:
|
|
client.poll()
|
|
ms = client.get_monitor_status()
|
|
return UnitStatus(
|
|
serial=serial, series=3, monitoring=ms.is_monitoring,
|
|
battery_volts=round(ms.battery_v, 2) if ms.battery_v is not None else None,
|
|
memory_total_bytes=ms.memory_total, memory_free_bytes=ms.memory_free,
|
|
device_time=None, event_count=None,
|
|
# Series 3 status reads no serial, so the serial shown is the one requested, not one the unit reported.
|
|
detail={"serial_verified": False},
|
|
)
|
|
return self._run(address, op)
|
|
|
|
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
|
|
def op(client: Any) -> UnitSettings:
|
|
info = client.connect()
|
|
self._check(info.serial, serial, address)
|
|
cc = info.compliance_config
|
|
if cc is None:
|
|
raise MalformedReply("could not read the unit's settings (SUB 0x1A)")
|
|
mode = None
|
|
if cc.recording_mode is not None:
|
|
mode = S3_MODES.get(cc.recording_mode, f"unknown (0x{cc.recording_mode:02x})")
|
|
notes = {
|
|
label: value for label, value in (
|
|
("Project", cc.project), ("Client", cc.client), ("User Name", cc.operator),
|
|
("Seis Loc", cc.sensor_location), ("Extended Notes", cc.notes),
|
|
) if value is not None
|
|
}
|
|
return UnitSettings(
|
|
serial=info.serial, series=3, setup_name=cc.setup_name, record_mode=mode,
|
|
sample_rate=cc.sample_rate, record_time_s=cc.record_time,
|
|
histogram_interval_s=cc.histogram_interval_sec, geo_trigger_ips=cc.trigger_level_geo,
|
|
notes=notes,
|
|
detail={"record_mode_code": cc.recording_mode, "alarm_level_geo": cc.alarm_level_geo,
|
|
"geo_range": cc.geo_range},
|
|
)
|
|
return self._run(address, op)
|
|
|
|
def list_events(self, address: UnitAddress, serial: str) -> EventList:
|
|
def op(client: Any) -> EventList:
|
|
info = client.connect()
|
|
self._check(info.serial, serial, address)
|
|
return EventList(serial=serial, series=3,
|
|
events=[_s3_ref(ev, serial) for ev in client.list_event_headers()])
|
|
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
|
|
|
|
def download_event(self, address: UnitAddress, serial: str, key: bytes,
|
|
stamp: Optional[str]) -> DownloadedEvent:
|
|
def op(client: Any) -> DownloadedEvent:
|
|
info = client.connect()
|
|
self._check(info.serial, serial, address)
|
|
try:
|
|
ev = client.download_event_by_key(key)
|
|
except struct.error as exc:
|
|
# Inferred, not measured here: the known 5A page bug. An event past the unit's
|
|
# first 64 KB drives TERM's offset negative, and struct.pack rejects it
|
|
# (seismo-relay CLAUDE.md, "KNOWN BUG").
|
|
raise MalformedReply(
|
|
f"event {key.hex()}: its download could not be assembled ({exc}) -- most "
|
|
"likely the known bug with events past the unit's first 64 KB; not saved"
|
|
) from exc
|
|
if ev is None:
|
|
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
|
|
found = stamp_of(_s3_dt(ev))
|
|
if stamp is not None and found != stamp:
|
|
raise StaleEvent(
|
|
f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- "
|
|
"the unit was erased or wrapped since the list was read; list again")
|
|
if not ev._a5_frames:
|
|
raise MalformedReply(f"event {key.hex()}: no waveform data received (the 5A download failed)")
|
|
filename = _s3_filename(ev, serial)
|
|
if filename is None:
|
|
raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored")
|
|
return DownloadedEvent(
|
|
event_id=make_event_id(serial, key, found), serial=serial, series=3,
|
|
filename=filename, verified=None, event=ev, a5_frames=ev._a5_frames,
|
|
compliance=info.compliance_config, timestamp=_s3_dt(ev),
|
|
detail={"a5_frames": len(ev._a5_frames)},
|
|
)
|
|
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
|