With the decode checker's fixes merged (histogram vector sum625bc39, mic psi5644dbd, the file's geophone range4844135), the event file reads everything Blastware reports. So a live download's row and samples are now the file's: peaks, vector sum, mic -- and the geophone range from the file's own setup block, the setting when the event was recorded. The live 1A is the unit's setting now, which may have changed since; it is the fallback only when the file's range does not read. Measured: K557J1KB.RQ0W (Sensitive waveform) downloaded with its settings unread -- e.g. while monitoring -- stores 0.019 / 0.055 / 0.019 and PVS 0.061, Blastware's report; its .h5 read 0.155 / 0.44 (8x) before. M010HR6K.OA0H (Sensitive histogram) likewise. K441LTON.900 (Normal) stores Blastware's values whatever the unit's current settings say, and its mic is 5.80e-4 psi (Blastware: 106.0 dB(L)). The unit's 0C summary stays the download check, and fills in the channel peaks and vector sum only when the file's range does not read (never seen in DL2) and the unit is not confirmed Normal -- the impossible-vector-sum guard kept there. The mic is the file's always. Closes the range part of open finding #17. Store consequence: new live downloads only; no backfill, no migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
190 lines
8.7 KiB
Python
190 lines
8.7 KiB
Python
"""Store an event SFM downloaded from a unit -- the SDM side of
|
|
POST /device/events/download.
|
|
|
|
Both series end in the two writes every other ingest path makes: the waveform
|
|
store (file + sidecar + .h5) and SeismoDb.insert_events().
|
|
|
|
An event already stored -- by an earlier download, or by THOR's watcher or
|
|
Blastware's ACH -- is returned as it is and NOTHING is written. The watcher's
|
|
copy is the richer one (its paired report carries PVS, project strings and ZC
|
|
frequencies a bare download does not), so a download never merges into it or
|
|
replaces it.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
from pathlib import Path
|
|
from typing import Any, Optional
|
|
|
|
from sfm.device_access.models import DownloadedEvent, EventDownload
|
|
|
|
|
|
class IngestError(Exception):
|
|
"""Downloaded from the unit, but could not be stored."""
|
|
|
|
|
|
def backfill_series3_event(ev: Any, cc: Any) -> None:
|
|
"""Compliance-config values that supersede what the 5A stream decoded.
|
|
|
|
Some STRT fields have ambiguous semantics (STRT[20] is rectime, but
|
|
STRT[8:10] / STRT[16:18] are device-specific scratch, not reliable sample or
|
|
pre-trigger counts). Shared with GET /device/event/{i}/blastware_file.
|
|
"""
|
|
if not cc:
|
|
return
|
|
if ev.sample_rate is None and cc.sample_rate:
|
|
ev.sample_rate = cc.sample_rate
|
|
if cc.record_time:
|
|
# Authoritative: the user-set value the unit followed when recording.
|
|
ev.rectime_seconds = cc.record_time
|
|
# Derive total_samples from sample_rate x rectime when we can; the
|
|
# STRT-derived value can land at a buffer offset rather than a count.
|
|
if ev.sample_rate and ev.rectime_seconds:
|
|
derived = int(round(ev.sample_rate * ev.rectime_seconds))
|
|
if (ev.total_samples is None
|
|
or ev.total_samples > derived * 2
|
|
or ev.total_samples < derived // 4):
|
|
ev.total_samples = derived
|
|
|
|
|
|
def _event_dt(ev: Any) -> Optional[datetime.datetime]:
|
|
ts = getattr(ev, "timestamp", None)
|
|
try:
|
|
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
|
|
except Exception: # noqa: BLE001
|
|
return None
|
|
|
|
|
|
def _already_stored(dl: DownloadedEvent, row: dict) -> EventDownload:
|
|
return EventDownload(
|
|
event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row["id"],
|
|
stored_filename=row.get("blastware_filename") or "",
|
|
filesize=row.get("blastware_filesize"),
|
|
sha256=None, # the events table does not keep one
|
|
inserted=False, verified=dl.verified,
|
|
detail={**dl.detail, "already_stored": True},
|
|
)
|
|
|
|
|
|
def _file_geo_range(bw_bytes: bytes) -> Any:
|
|
"""The geophone range a Blastware file was recorded at (0 Normal, 1 Sensitive),
|
|
or None when it does not read -- or the file does not decode at all."""
|
|
from minimateplus import event_file_io
|
|
try:
|
|
return event_file_io.decode_blastware_bytes(bw_bytes).geo_range
|
|
except Exception: # noqa: BLE001 -- the store reports it
|
|
return None
|
|
|
|
|
|
def _overlay_s3_record(ev: Any, unit_peaks: Any, unit_range: Any) -> None:
|
|
"""The unit's own 0C peaks over the file's -- only where the file cannot be trusted.
|
|
|
|
The file reads everything Blastware reports (checked on 70,042 events): the
|
|
channel peaks and the vector sum, scaled by the geophone range in its own
|
|
setup block (4844135), and the mic (5644dbd). The 0C summary is read at
|
|
fixed offsets and can shift -- BE9441's read 0 and -0.0 for vector sums
|
|
(bench #4) -- so the file's values stand.
|
|
|
|
Except when the file's range does not read (`ev.geo_range` None; never seen
|
|
in DL2): the decoder then assumes Normal, 8x off for a Sensitive unit. Then
|
|
the unit's settings decide: Normal confirmed (`unit_range` 0) keeps the
|
|
file's peaks; Sensitive or unread keeps the unit's own, as before -- a vector
|
|
sum below the largest channel peak is impossible and is not kept. The mic
|
|
is the file's either way: its scale does not depend on the geophone range.
|
|
"""
|
|
if unit_peaks is None or getattr(ev, "geo_range", None) is not None:
|
|
return
|
|
if unit_range in (0, "normal"):
|
|
return
|
|
from minimateplus.models import PeakValues
|
|
|
|
if ev.peak_values is None:
|
|
ev.peak_values = PeakValues()
|
|
pv = ev.peak_values
|
|
for name in ("tran", "vert", "long"):
|
|
value = getattr(unit_peaks, name, None)
|
|
if value is not None:
|
|
setattr(pv, name, value)
|
|
pvs = getattr(unit_peaks, "peak_vector_sum", None)
|
|
largest = max((getattr(unit_peaks, n, None) or 0.0) for n in ("tran", "vert", "long"))
|
|
if pvs is not None and pvs > 0 and pvs >= largest - 0.005:
|
|
pv.peak_vector_sum = pvs
|
|
|
|
|
|
def _overlay_s4_record(ev: Any, record: dict) -> None:
|
|
"""Fill, where the file left them empty, what the unit's 0x0C said.
|
|
|
|
Without Thor's TXT report the IDF file gives only the three PPVs. The
|
|
vector sum matters beyond display: find_twins matches on it. Not the mic:
|
|
its 0x0C decode reads a denormal (parked).
|
|
"""
|
|
from minimateplus.models import PeakValues, ProjectInfo
|
|
|
|
pvs = record.get("peak_vector_sum_ips")
|
|
if pvs is not None:
|
|
if ev.peak_values is None:
|
|
ev.peak_values = PeakValues()
|
|
if ev.peak_values.peak_vector_sum is None:
|
|
ev.peak_values.peak_vector_sum = pvs
|
|
location = record.get("sensor_location")
|
|
if location is not None:
|
|
if ev.project_info is None:
|
|
ev.project_info = ProjectInfo()
|
|
if ev.project_info.sensor_location is None:
|
|
ev.project_info.sensor_location = location
|
|
|
|
|
|
def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload:
|
|
# Never merge: a row for (serial, timestamp) means the event is stored, and
|
|
# whoever stored it first keeps it. No store call, no insert, no sidecar.
|
|
if dl.timestamp is not None:
|
|
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1)
|
|
if rows:
|
|
return _already_stored(dl, rows[0])
|
|
# A histogram's row is stored at its file's time, a second before the unit's
|
|
# on most (#51), so the time above misses it; its Blastware name does not.
|
|
row = db.find_event_by_blastware_name(dl.serial, dl.filename)
|
|
if row is not None:
|
|
return _already_stored(dl, row)
|
|
if dl.series == 4:
|
|
ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename),
|
|
serial_hint=dl.serial)
|
|
if ev is not None:
|
|
_overlay_s4_record(ev, dl.record)
|
|
family = "series4"
|
|
else:
|
|
# The same path production's watcher uses for Blastware's own files: the
|
|
# event is decoded from the file -- samples, histogram, peaks, vector sum,
|
|
# mic, sample rate, record time and the geophone range it was recorded
|
|
# at -- not from the live 5A decode. The unit's 0C summary is the
|
|
# download check (verify_s3_download); it fills in only when the file's
|
|
# range does not read (_overlay_s3_record).
|
|
if not dl.bw_bytes:
|
|
raise IngestError(f"{dl.filename}: the download carried no event file; nothing was stored")
|
|
unit_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None
|
|
# The file's range is the setting when it recorded; the live 1A is the
|
|
# unit's setting now, which may have changed since -- the fallback only.
|
|
# None lets the store scale by the file's own range.
|
|
ev, rec = store.save_imported_bw(dl.bw_bytes, source_path=Path(dl.filename),
|
|
serial_hint=dl.serial, source_kind="sfm-live",
|
|
geo_range=None if _file_geo_range(dl.bw_bytes) is not None
|
|
else unit_range)
|
|
if ev is not None and dl.event is not None:
|
|
_overlay_s3_record(ev, getattr(dl.event, "peak_values", None), unit_range)
|
|
family = "series3"
|
|
if ev is None or ev._waveform_key is None:
|
|
raise IngestError(f"{dl.filename}: stored the file but could not build a database row")
|
|
inserted, _skipped = db.insert_events(
|
|
[ev], serial=dl.serial,
|
|
waveform_records={ev._waveform_key.hex(): rec}, device_family=family)
|
|
row_id = None
|
|
dt = _event_dt(ev)
|
|
if dt is not None:
|
|
rows = db.query_events(serial=dl.serial, from_dt=dt, to_dt=dt, limit=1)
|
|
row_id = rows[0]["id"] if rows else None
|
|
return EventDownload(
|
|
event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row_id,
|
|
stored_filename=rec["filename"], filesize=rec["filesize"], sha256=rec.get("sha256"),
|
|
inserted=inserted > 0, verified=dl.verified, detail=dict(dl.detail),
|
|
)
|