diff --git a/CLAUDE.md b/CLAUDE.md index 335fc6c..1a5c2c5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2307,7 +2307,7 @@ body) because writing a dial string may require DLE escaping for embedded contro - **Database** — SQLite store for events + monitor log entries; dedup by key; queryable - **Histograms** — decode histogram-mode A5 data (noise floor tracking) -- **Blastware-compatible file output** — `write_blastware_file()` and `write_mlg()` implemented. `blastware_filename()` generates correct Blastware filenames (AB0 for direct, AB0W/AB0H for ACH). **Confirmed BYTE-PERFECT against BW reference (v0.14.3, 2026-05-05):** when fed the BW 5-1-26 3-sec capture's A5 frames, the SFM-built file matches BW's saved `M529LKIQ.G10` byte-for-byte (8708 bytes, 0 differences). Live SFM downloads of event 0 (3-sec) and event 1 (3-sec continuation) both open cleanly in Blastware with full Event Reports, frequency analysis, and waveform plots. Body assembly is just contiguous concatenation of frame contributions in stream order (probe → meta@0x1002 → meta@0x1004 → samples → TERM); no stripping, no overlay, no special handling. Histogram+Continuous mode deferred (5A stream for those events embeds histogram interval records that may need different handling — untested under v0.14.x). Extension mapping: extensions encode timestamp (AB0T for ACH, AB0 for direct), NOT recording mode. Filename format: `<4-char-base36-stem>` +- **Blastware-compatible file output** — `write_blastware_file()` and `write_mlg()` implemented. `blastware_filename()` generates correct Blastware filenames (AB0 for direct, AB0W/AB0H for ACH). **SFM's own MiniMate downloads carry the W/H letter (2026-10-30):** `with_type_letter()` reads it from the file's STRT[18] (#41) on all three naming paths (device-access download, `WaveformStore.save`, the legacy `/device/event/{i}/blastware_file`); Blastware's direct downloads leave it off. **Confirmed BYTE-PERFECT against BW reference (v0.14.3, 2026-05-05):** when fed the BW 5-1-26 3-sec capture's A5 frames, the SFM-built file matches BW's saved `M529LKIQ.G10` byte-for-byte (8708 bytes, 0 differences). Live SFM downloads of event 0 (3-sec) and event 1 (3-sec continuation) both open cleanly in Blastware with full Event Reports, frequency analysis, and waveform plots. Body assembly is just contiguous concatenation of frame contributions in stream order (probe → meta@0x1002 → meta@0x1004 → samples → TERM); no stripping, no overlay, no special handling. Histogram+Continuous mode deferred (5A stream for those events embeds histogram interval records that may need different handling — untested under v0.14.x). Extension mapping: extensions encode timestamp (AB0T for ACH, AB0 for direct), NOT recording mode. Filename format: `<4-char-base36-stem>` **Serial encoding (CONFIRMED 2026-04-22):** `prefix_letter = chr(ord('B') + floor(serial_numeric / 1000))`, `serial3 = f"{serial_numeric % 1000:03d}"`. Examples: BE6907→H907, BE11529→M529, BE14036→P036, BE17353→S353, BE18003→T003. The prefix letter encodes the production generation (batch of 1000 units). diff --git a/minimateplus/blastware_file.py b/minimateplus/blastware_file.py index 12e269c..9dcbcb4 100644 --- a/minimateplus/blastware_file.py +++ b/minimateplus/blastware_file.py @@ -467,6 +467,9 @@ def blastware_filename(event: Event, serial: str, ach: bool = False) -> str: 0 = always literal digit zero T = 'W' or 'H' — ONLY appended for call-home (ACH) downloads (ach=True). + ⚠ ach=True guesses the letter from the recording mode, which is wrong for + a waveform recorded in Histogram+Continuous; for a file in hand use + `with_type_letter(name, bw_bytes)`, which reads the file's own type byte. Manual / direct downloads produce a 3-char extension (AB0) with no type char. Call-home downloads produce a 4-char extension (AB0W or AB0H). @@ -531,6 +534,32 @@ def blastware_filename(event: Event, serial: str, ach: bool = False) -> str: return prefix + stem + ext +_TYPE_LETTER = {"Waveform": "W", "Histogram": "H"} + + +def with_type_letter(name: str, bw_bytes: bytes) -> str: + """`name` with the W/H type letter, for a Blastware file SFM built itself. + + Blastware's own direct downloads leave the letter off (`K441LTON.900`) and + only its call-in copies carry it (`K441LTON.900H`), which makes events hard + to sort; SFM's files carry it (2026-10-30). The letter is read from the + file's own record-type byte -- STRT[18], as `decode_blastware_bytes` reads it + (#41) -- not from the recording mode, which in Histogram+Continuous records + both kinds. A file whose type does not read keeps the plain name: a name is + never a reason to fail a download. A name already carrying a letter, or + not of the `.0` form, is returned unchanged. + """ + if blastware_filename_time(name) is None or len(name.rsplit(".", 1)[-1]) != 3: + return name + try: + from .event_file_io import decode_blastware_bytes # lazy: event_file_io imports this module + letter = _TYPE_LETTER.get(decode_blastware_bytes(bw_bytes).record_type) + except Exception as exc: # noqa: BLE001 + log.warning("with_type_letter: %s: the record type did not read (%s) -- plain name kept", name, exc) + letter = None + return name + letter if letter else name + + # ── A5 frame classifier ─────────────────────────────────────────────────────────── # ASCII markers that identify a compliance-config / metadata frame. diff --git a/sfm/database.py b/sfm/database.py index 9ac430a..d2ad16c 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -813,20 +813,25 @@ class SeismoDb: A Blastware name encodes the serial and the event's second (`blastware_filename_time`), so the same name is the same event -- the - rule `_restamp_by_file` uses. A direct download is `.0` and - Blastware's call-in copy of the same event `.0W` / `H`; all - three forms match. Any other name ("imported.bw") matches nothing. + rule `_restamp_by_file` uses. Blastware's direct download is + `.0`, its call-in copy and SFM's own files `.0W` / `H`. + A name without the letter matches all three forms; one with it matches + itself and the letterless form -- not the other letter, since in + Histogram+Continuous a waveform can trigger in the second a histogram + starts. Any other name ("imported.bw") matches nothing. """ if blastware_filename_time(filename) is None: return None - base = filename.upper() - if len(base.rsplit(".", 1)[-1]) == 4: - base = base[:-1] + name = filename.upper() + if len(name.rsplit(".", 1)[-1]) == 4: + forms = (name[:-1], name) + else: + forms = (name, name + "W", name + "H") with self._connect() as conn: row = conn.execute( - "SELECT * FROM events WHERE serial = ? AND UPPER(blastware_filename) IN (?, ?, ?) " - "ORDER BY rowid LIMIT 1", - (serial, base, base + "W", base + "H"), + f"SELECT * FROM events WHERE serial = ? AND UPPER(blastware_filename) IN " + f"({', '.join('?' * len(forms))}) ORDER BY rowid LIMIT 1", + (serial, *forms), ).fetchone() return dict(row) if row else None diff --git a/sfm/device_access/s3.py b/sfm/device_access/s3.py index 38563a8..32f77b8 100644 --- a/sfm/device_access/s3.py +++ b/sfm/device_access/s3.py @@ -8,7 +8,7 @@ import struct from typing import Any, Callable, Optional from minimateplus import MiniMateClient -from minimateplus.blastware_file import blastware_file_bytes, blastware_filename +from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter from minimateplus.event_file_io import _GEO_INT16_FS from minimateplus.framing import build_bw_write_frame from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING @@ -408,6 +408,7 @@ class Series3Adapter: raise MalformedReply( f"event {key.hex()}: its Blastware file could not be assembled ({exc}); not saved" ) from exc + filename = with_type_letter(filename, bw_bytes) # ...900 -> ...900H, from the file's own bytes return DownloadedEvent( event_id=make_event_id(serial, key, found), serial=serial, series=3, filename=filename, verified=verified, event=ev, a5_frames=ev._a5_frames, diff --git a/sfm/server.py b/sfm/server.py index 58b06e8..e277948 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -71,7 +71,7 @@ from minimateplus import MiniMateClient from minimateplus.protocol import ProtocolError from minimateplus.models import CallHomeConfig, ComplianceConfig, DeviceInfo, Event, PeakValues, ProjectInfo, Timestamp from minimateplus.transport import TcpTransport, DEFAULT_TCP_PORT -from minimateplus.blastware_file import write_blastware_file, blastware_filename +from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter from minimateplus.client import _decode_a5_metadata_into, _decode_a5_waveform, _decode_event_count from minimateplus.framing import build_bw_write_frame, SESSION_RESET, POLL_PROBE, POLL_DATA from minimateplus.protocol import SUB_STOP_MONITORING @@ -1025,8 +1025,10 @@ def device_event_blastware_file( # Determine serial number from device info serial = getattr(info, "serial", None) or "UNKNOWN" - # Build filename using the same algorithm Blastware uses - filename = blastware_filename(ev, serial) + # Build filename using the same algorithm Blastware uses, plus the W/H type + # letter its direct downloads leave off (read from the file's own bytes). + bw_bytes = blastware_file_bytes(ev, a5_frames) + filename = with_type_letter(blastware_filename(ev, serial), bw_bytes) # Write to OS temp dir (cross-platform: /tmp on Linux/macOS, # %TEMP% on Windows) so FastAPI can stream it back via FileResponse. @@ -1040,7 +1042,7 @@ def device_event_blastware_file( out_path.unlink() except FileNotFoundError: pass - write_blastware_file(ev, a5_frames, out_path) + out_path.write_bytes(bw_bytes) log.info( "blastware_file: wrote %s (%d A5 frames, serial=%s)", out_path, len(a5_frames), serial, diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index 6408b1e..69314dd 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -38,7 +38,7 @@ from pathlib import Path from typing import Optional, Union from minimateplus import event_file_io -from minimateplus.blastware_file import blastware_filename, write_blastware_file +from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter from minimateplus.framing import S3Frame from minimateplus.models import Event from sfm import event_hdf5 @@ -75,7 +75,7 @@ class WaveformStore: """ Persistent store for Blastware-format waveform files + their A5 source frames. - Thread safety: write_blastware_file is single-shot; concurrent saves of the + Thread safety: the event file is written single-shot; concurrent saves of the *same* filename would race, but the filename encodes second-resolution timestamps + serial, so collisions across threads/processes are vanishingly unlikely in practice. @@ -184,7 +184,8 @@ class WaveformStore: if not serial: raise ValueError("WaveformStore.save: serial is required") - filename = blastware_filename(ev, serial) + bw_bytes = blastware_file_bytes(ev, a5_frames) + filename = with_type_letter(blastware_filename(ev, serial), bw_bytes) # ...900 -> ...900H bw_path, a5_path = self.paths_for(serial, filename) sidecar_path = self.sidecar_path_for(serial, filename) hdf5_path = self.hdf5_path_for(serial, filename) @@ -195,7 +196,7 @@ class WaveformStore: bw_path.unlink() except FileNotFoundError: pass - write_blastware_file(ev, a5_frames, bw_path) + bw_path.write_bytes(bw_bytes) filesize = bw_path.stat().st_size sha256 = event_file_io.file_sha256(bw_path) diff --git a/tests/device_access_fakes.py b/tests/device_access_fakes.py index 6418e2b..3cf84b4 100644 --- a/tests/device_access_fakes.py +++ b/tests/device_access_fakes.py @@ -181,8 +181,8 @@ class FakeMiniMateClient(_Base): if expected_timestamp is not None and _iso(ev) != expected_timestamp: ev = copy.copy(ev) ev._a5_frames = None - elif ev._a5_frames: - _as_downloaded(ev) + elif ev._a5_frames and isinstance(ev._a5_frames[0], str): + _as_downloaded(ev) # placeholder frames only; a test's real ones are kept self.last_download = ev return ev return None diff --git a/tests/test_5a_blastware_walk_histogram.py b/tests/test_5a_blastware_walk_histogram.py index d9492fd..e7b2e45 100644 --- a/tests/test_5a_blastware_walk_histogram.py +++ b/tests/test_5a_blastware_walk_histogram.py @@ -133,3 +133,78 @@ def test_blastware_file_bytes_is_blastwares_file(key, bw): ev = Event(index=0) ev.timestamp = None assert blastware_file_bytes(ev, frames) == (FIX / "blastware" / bw).read_bytes() + + + +# SFM's own downloads are named with the W/H letter (2026-10-30), on every path +# that builds the file: the device-access download, the store's save, and the +# legacy per-index route. BE9441's walk gives one of each: 0111f210 is the +# histogram K441LTON.900, 011106a0 the waveform K441LTOK.R10. + +import datetime # noqa: E402 + +from device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402 +from minimateplus.models import DeviceInfo # noqa: E402 +from minimateplus.waveform_codec import decode_a5_frames # noqa: E402 + +LIVE = [("0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36), "K441LTON.900H"), + ("011106a0", datetime.datetime(2026, 10, 26, 16, 6, 37), "K441LTOK.R10W")] + + +def _walked_event(key, when): + frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream( + bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, + strict=True, max_chunks=128) + ev = s3_event(0, key, when, frames=False) + ev._a5_frames = frames + ev.raw_samples = decode_a5_frames(frames) # as the real client's download decodes them + return ev + + +@pytest.mark.parametrize("key,when,name", LIVE) +def test_a_live_download_is_named_with_its_type_letter(key, when, name): + from sfm.device_access.models import UnitAddress + from sfm.device_access.s3 import Series3Adapter + # Range unread (no settings): the check then does not compare peaks, which + # these events have no Blastware report for -- only the name is under test. + fake = FakeMiniMateClient(serial="BE9441", events=[_walked_event(key, when)], compliance=None) + dl = Series3Adapter(client_factory=lambda address, **kw: fake).download_event( + UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None), "BE9441", + bytes.fromhex(key), None) + assert dl.filename == name + + +@pytest.mark.parametrize("key,when,name", LIVE) +def test_the_store_names_a_saved_download_with_its_type_letter(key, when, name, tmp_path): + from sfm.waveform_store import WaveformStore + ev = _walked_event(key, when) + rec = WaveformStore(tmp_path).save(ev, serial="BE9441", a5_frames=ev._a5_frames) + assert rec["filename"] == name + assert (tmp_path / "BE9441" / name).read_bytes() == (FIX / "blastware" / name[:-1]).read_bytes() + + +@pytest.mark.parametrize("key,when,name", LIVE) +def test_the_legacy_file_route_names_its_file_with_the_type_letter(key, when, name, tmp_path, monkeypatch): + import sfm.server as srv + from sfm.database import SeismoDb + from sfm.waveform_store import WaveformStore + ev = _walked_event(key, when) + + class Unit: + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def connect(self): + return DeviceInfo(serial="BE9441", firmware_minor=17) + + def get_events(self, **kw): + return [ev] + monkeypatch.setattr(srv, "_build_client", lambda *a, **kw: Unit()) + monkeypatch.setattr(srv, "_get_store", lambda: WaveformStore(tmp_path / "w")) + monkeypatch.setattr(srv, "_get_db", lambda: SeismoDb(tmp_path / "s.db")) + resp = srv.device_event_blastware_file(index=0, port=None, baud=38400, host="10.0.0.5", + tcp_port=9034, force=False) + assert resp.filename == name diff --git a/tests/test_blastware_type_letter.py b/tests/test_blastware_type_letter.py new file mode 100644 index 0000000..7e09b01 --- /dev/null +++ b/tests/test_blastware_type_letter.py @@ -0,0 +1,41 @@ +"""SFM names the Blastware files it builds with the W/H type letter (2026-10-30). + +Blastware's own direct downloads leave the letter off (`K441LTON.900`); only its +call-in copies carry it (`...900H`), which makes events hard to sort. The letter +comes from the file's own record-type byte (STRT[18], #41) -- not the recording +mode, which in Histogram+Continuous records both kinds. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from minimateplus.blastware_file import blastware_filename_time, with_type_letter # noqa: E402 + +HIST = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram" / "blastware" +WAVE = Path(__file__).parent / "fixtures" / "5-11-26" + + +@pytest.mark.parametrize("path, want", [ + (HIST / "K441LTON.900", "K441LTON.900H"), + (HIST / "K441LTOK.QZ0", "K441LTOK.QZ0H"), + (HIST / "K441LTOK.R10", "K441LTOK.R10W"), # a waveform, 2 s into QZ0 (Histogram+Continuous) + (WAVE / "M529LL1L.V70", "M529LL1L.V70W"), +]) +def test_a_file_is_named_with_the_type_its_bytes_say(path, want): + got = with_type_letter(path.name, path.read_bytes()) + assert got == want + assert blastware_filename_time(got) == blastware_filename_time(path.name) # same second + + +def test_a_file_whose_type_does_not_read_keeps_the_plain_name(): + assert with_type_letter("K441LTON.900", b"not a blastware file") == "K441LTON.900" + + +def test_a_name_that_already_has_its_letter_is_left_alone(): + assert with_type_letter("K441LTON.900H", (HIST / "K441LTON.900").read_bytes()) == "K441LTON.900H" diff --git a/tests/test_event_ingest.py b/tests/test_event_ingest.py index 1d4a5d3..271fefc 100644 --- a/tests/test_event_ingest.py +++ b/tests/test_event_ingest.py @@ -384,3 +384,28 @@ def test_a_live_histogram_is_labelled_a_histogram(sdm): out = persist_download(_hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)), store=store, db=db) assert db.get_event(out.db_event_id)["record_type"] == "Histogram" + + +def _stored_as(store, db, name, fixture="K441LTOK.QZ0"): + ev, rec = store.save_imported_bw((HIST_FIX / fixture).read_bytes(), source_path=Path(name), + serial_hint=None) + db.insert_events([ev], serial="BE9441", waveform_records={ev._waveform_key.hex(): rec}, + device_family="series3") + + +def test_a_lettered_name_does_not_match_the_other_type_in_the_same_second(sdm): + # SFM's own names now carry W/H (2026-10-30). In Histogram+Continuous a + # waveform can trigger in the second a histogram starts; with both letters + # known they are different events. + store, db = sdm + _stored_as(store, db, "K441LTOK.QZ0H") + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0W") is None + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0H")["blastware_filename"] == "K441LTOK.QZ0H" + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0") is not None # a letterless name: no opinion + + +def test_a_letterless_stored_name_still_matches_a_lettered_download(sdm): + # Rows stored before 2026-10-30, and Blastware's own direct downloads, have no letter. + store, db = sdm + _stored_as(store, db, "K441LTOK.QZ0") + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0H")["blastware_filename"] == "K441LTOK.QZ0"