222 Commits
Author SHA1 Message Date
serversdownandClaude Opus 5.5 621c836109 docs(changelog): Unreleased -- a Thor file's own settings, notes and time (#44, #45)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-20 15:03:38 -05:00
serversdownandClaude Opus 5.5 0c228fa258 merge: a Thor file's own settings, notes and time (#44, #45)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-20 15:02:08 -05:00
serversdownandClaude Opus 5.5 f7a02b1fee fix(idf): a Thor file's own settings, notes and time (#44, #45)
A Micromate event read without Thor's report (SFM's own downloads) came out
with sample rate, pre-trigger and record time 0, empty notes, and a
1970-01-01 time; every Micromate .h5, report or not, stored pre-trigger 0.

- The settings were found by the bytes be 80 00 00 00 00 -- a -0.25 s
  pre-trigger and Fixed stop mode, not a marker -- so any other pre-trigger
  left them unread.  The event's settings record is now found by its own
  signature 00 2a 04 00 00 (fields at the live 0x1A block's head offsets).
- The event time is read at settings record + 0x34, not two fixed offsets
  that miss a header shape.
- The four notes are read at 0x23c ([label 22][value 42] x 4).
- IdfEvent.to_minimateplus_event sets pretrig_samples.
- save_imported_idf fills the pre-trigger and notes from the file when the
  report lacks them.

Measured against Thor's own reports on 2,027 corpus files: sample rate and
notes 2,027 / 2,027; record time and pre-trigger 291 / 291 waveforms; event
time = filename on 2,384 / 2,384.  The issues' 20 UM12947 bench files now
store 4096 S/s, 4096 pre-trigger samples (1.0 s), 3 s and their notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-20 14:45:52 -05:00
serversdownandClaude Opus 5.5 c0561f9de6 docs(changelog): Unreleased -- tests and scripts cleanup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-20 14:31:18 -05:00
serversdownandClaude Opus 5.5 fbd0c60cc7 merge: tests and scripts cleanup -- a fresh checkout passes on its own
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-20 14:31:18 -05:00
serversdownandClaude Opus 5.5 e071be7ee0 docs(CLAUDE.md): a test reads only tracked files
Copy what a test needs from bridges/captures/ or example-events/ into
tests/fixtures/ (git add -f), never guard a fixture with a skip, and
check with a fresh worktree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-20 13:39:23 -05:00
serversdownandClaude Opus 5.5 a7f9f66da1 build: bridges/ leaves the production image
The bench and lab tools (MITM proxy, the old ACH servers, probes, link
simulator) were copied into the SFM image and installed as a package,
though SFM imports nothing from them (ADR 0003: lab tools leave the
image).  Dockerfile and the package list now carry minimateplus,
micromate, sfm and scripts only; the backfills still run in the
container.  Checked: the image builds, sfm.server and the backfill /
import scripts import inside it.  Tests that use bridges/ run from a
checkout, unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-20 13:39:23 -05:00
serversdownandClaude Opus 5.5 638ac58b4d chore: remove four obsolete scripts
- scripts/backfill_event_zc_freq.py copied ZC frequency from Blastware
  reports into the DB; the decoder reads it from the file since v0.35.0,
  whose backfill refreshed every row.  Its two tests go with it; the DB
  column tests in test_zc_freq_columns.py stay.
- scripts/backfill_record_type.py: a one-time fix from May; the record
  type is read from the file since v0.33.0.
- scripts/test_thor_render.py: a one-off re-import of two prod Thor files
  (May); nothing referenced it.
- scratch/next_experiment_skeleton.py: codec research scaffolding from
  before the codec was solved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-20 13:39:23 -05:00
serversdownandClaude Opus 5.5 646da046b7 test: remove test_5a_protocol.py and the retracted 5A helpers only it used
Its 19 tests pinned the May 2026 5A model -- a raw offset_hi 0x10,
11-byte params, metadata pages at 0x1002 / 0x1004 -- retracted on
2026-10-26, and the 5-1-26 capture they read no longer exists on the dev
box, so they skipped everywhere.  tests/test_5a_blastware_walk.py
replaced them: all 540 of Blastware's 5A requests rebuilt from tracked
fixtures.  Removed with them, from framing.py, the four helpers marked
'superseded, no production caller, kept for test_5a_protocol.py':
build_5a_frame, bulk_waveform_params, bulk_waveform_term_params,
bulk_waveform_term_v2.  parse_strt_end_offset stays: test_5a_blastware_
walk.py uses it to show the old misread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-20 13:39:23 -05:00
serversdownandClaude Opus 5.5 20b1581e37 build: a test dependency group -- pytest and httpx
httpx is FastAPI's TestClient transport; without it
tests/test_db_snapshot_endpoints.py skipped its 3 tests everywhere.
`pip install -e .[test]` now brings what the suite needs.  The
runtime requirements are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-19 13:33:21 -05:00
serversdownandClaude Opus 5.5 4d0984dcaf test: everything the tests read is in git -- a fresh checkout passes on its own
A fresh checkout of dev failed 10 tests, errored 3 and skipped 64: the
tests read 100 files that were only on the dev box.  Recorded with an
audit hook over a full run: 100 files, 2.3 MB, out of 1.1 GB of
bridges/captures/ and 45 MB of histogram-extension-re/.

- Force-added in place: tests/fixtures/thor-idf (14), histogram-multi-
  interval (2) and the one histogram-extension-re file read.
- Copied into tests/fixtures/example-events/ (10) and
  tests/fixtures/captures/ (73, from bridges/captures/), and the tests
  pointed there.
- The presence skips ('not on this machine', 'gitignored', 'fixture
  missing') are gone: a missing fixture now fails instead of skipping.

The worktree now runs as the dev box does: 1,787 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-19 13:32:59 -05:00
serversdownandClaude Opus 5.5 c2b8e76774 chore(release): v0.35.0 — 80 of 88 report fields from the file, and monitor logs (.MLG)
CHANGELOG: Unreleased -> v0.35.0 (2026-11-16), with the release's theme
and its Migration.  pyproject, README, CLAUDE.md -> 0.35.0.
TOOL_VERSION -> 0.35.0: the codec changed (groups D2, E, F, over range,
the mic's range), which gates the backfill's regeneration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-16 12:46:58 -05:00
serversdownandClaude Opus 5.5 ed4f3d2213 docs(changelog): Unreleased -- monitor logs (.MLG) and each unit's timeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-16 11:08:30 -05:00
serversdownandClaude Opus 5.5 03c272316f merge: monitor logs (.MLG) and each unit's monitoring timeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-16 11:06:39 -05:00
serversdownandClaude Opus 5.5 ba826dfac6 fix(mlg): final-review fixes
A fresh whole-branch review found four Important issues; three of its
Minors and one item it set aside were re-graded up.  Each has a test that
failed first.

- A windowed timeline 500'd when a file came without its modified time
  (Python 3.10 rejects the 'Z' of received_at).  received_at is now
  +00:00 and timeline times parse 'Z' too.
- On the clock-step day an event-triggered call-in moved the event into
  the next session and lost the step.  An event now joins the 'monitoring
  started' record of its own file.
- A call-in whose records came first in another file (a cable download)
  read 'nothing_new'.  Each file now keeps its own call summary
  (last_stop, no_file_stops) from when it arrived.
- Sessions and call-ins now carry record_ids / file_ids / file_id, the
  shot report's proof (spec 5).
- A non-'started' record with no stop made the unit's timeline 500 for
  good; it now opens a session whose end is unknown.
- A serial from a file's bytes (or a hint) could write outside the store;
  only plain serials are used, and records with no serial are refused, not
  dropped.
- Times with a UTC offset, an empty 'at', or a bad mtimes value gave 500s
  (or stored half a request); they are now 400s, checked first.
- A missing call-in file made the gap after its Modem Exit read 'not
  monitoring' for days.  Files are numbered <serial><counter>; a gap
  across a missing number is now 'records missing' (unknown).  A long gap
  after a call-in with no number missing is 'no restart after a call-in':
  real outages on the DL2 data (BE6907 14 days from 2026-10-07; BE8081
  over Labor Day 2019).  Real fixtures BE6907 #899-#902 added.
- Docs: BE8081 did write one empty file (BE80811.MLG).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 14:17:08 -05:00
serversdownandClaude Opus 5.5 35bac40dd5 docs: the .MLG format measured (reference D.4), and the new /db routes
Reference D.4 rewritten from the measurements: the 18-byte prefix,
length-led 292-byte records, the CRC-16/AUG-CCITT (3,329 / 3,329), the
fields, how Blastware writes the files and how a session appears, and
the cross-check against DL2's event files.  The old D.4.1-D.4.3 stay,
marked retracted.  CLAUDE.md gains the five routes and a Where things
stand entry; the spec's footer-CRC note points at dev's 8544e9c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:56:10 -05:00
serversdownandClaude Opus 5.5 4bc669df4d feat(mlg): bulk import, and a cross-check against the event files
scripts/import_mlg_dir.py imports every .MLG under a directory (files
with records first, then the empty ones, so each unit's serial is known
first; dry run writes nothing).  scratch/check_mlg_vs_events.py matches
each Event Recorded record to an event file's footer (stop, flag word,
trigger source) in both directions, inside each unit's .MLG period.

Run on the dev box against DL2's 1,273 sample files (2026-11-13):
  import: 1273 ok, 0 errors, 231 empty, 0 unresolved, 2180 records, 13 s
  BE8081:  785 matched, 0 record-only, 0 file-only
  BE6907:    6 matched, 5 record-only, 0 file-only
  BE12844:  19 matched, 37 record-only, 0 file-only
  every record-only one stops after 2026-08-25, where the DL2 copy ends;
  the 4,303 footers of those three units' event files all pass their CRC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:54:50 -05:00
serversdownandClaude Opus 5.5 c0cdf58527 feat(mlg): /db routes: import .MLG, a unit's timeline, monitoring at T
POST /db/import/mlg_file (per-file status; good files stored even when
another in the request is refused; each file's modified time as a JSON
form field), GET /db/units/{serial}/timeline (optionally windowed),
GET /db/units/{serial}/monitoring_at, GET /db/mlg_records, and
GET /db/mlg_files/{id} (the original, byte for byte, for printing).

Tested by calling the route functions directly: httpx is not in this
venv, so TestClient tests would skip silently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:50:59 -05:00
serversdownandClaude Opus 5.5 faa371a73b feat(mlg): each unit's monitoring timeline, and was it monitoring at T
sfm/mlg_timeline.py builds, from a unit's stored records: sessions (with
how each ended, its events and its trigger level as logged), the gaps
between them and what each means (call-in, scheduled off, lost power,
stopped by a person, memory full), clock steps (a session starting
before the previous one stopped, as at the end of daylight saving), and
call-ins: delivered, no_file (a Modem Exit that left no file) and
nothing_new (an empty file).  monitoring_at() answers monitoring /
not_monitoring / unknown, never claiming more than the records show.
Tested on real files, including BE8081's weekend: Battery Low Exit
Saturday 10:47, back Monday 12:47, two calls that left no file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:48:13 -05:00
serversdownandClaude Opus 5.5 f41e4be382 feat(mlg): ingest one .MLG: verify, resolve the serial, keep the original
sfm/mlg_ingest.ingest_mlg() is shared by the import route and the bulk
script.  A file that is not whole, or with any record failing its
checksum, stores nothing.  The serial comes from the file; for an empty
file (no serial inside) from the caller's hint, else the longest known
serial its <serial><counter> name starts with, else unresolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:45:21 -05:00
serversdownandClaude Opus 5.5 84d6cd05c3 feat(mlg): store .MLG files and records, each record once
Two new tables, created on first start (no migration):
mlg_files (one row per file received, deduped by name + sha256) and
mlg_records (one row per log record, unique on serial, start, stop,
flag word and trigger source; COALESCE on the stop, since an open
record's NULL stop is distinct to a UNIQUE constraint).  The text is not
part of a record's identity: Blastware writes it, and two copies of the
same records differ there.  WaveformStore.save_mlg keeps the original
file byte for byte under <serial>/mlg/.

Operational consequence: two new tables on first start; no migration,
no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:43:47 -05:00
serversdownandClaude Opus 5.5 a8adb03d23 feat(mlg): write .MLG files as Blastware does; retire the old writer
mlg_bytes()/write_mlg() rebuild all 12 fixture files byte for byte:
little-endian times, length-led records, each record's checksum.  The old
blastware_file writer (big-endian times, a zero CRC at the wrong end, 308-
byte header) and the read_mlg stub are removed; nothing called them.  No
re-export: event_file_io imports blastware_file, and mlg_file imports
event_file_io.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:41:38 -05:00
serversdownandClaude Opus 5.5 3cd95db405 feat(mlg): read Blastware .MLG files, every record's checksum verified
minimateplus/mlg_file.py parses the measured format: an 18-byte prefix,
then length-led 292-byte records, each with a CRC-16/AUG-CCITT over
[0:288] stored little-endian.  A record that fails its checksum is
returned flagged, never silently dropped.  One shared CRC function
(minimateplus/crc.py) replaces micromate/setup_block's copy.

Fixtures: 12 real .MLG files (DL2's ACH folder + 3 bench files) in
tests/fixtures/mlg-11-9-26/, force-added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:39:44 -05:00
serversdownandClaude Opus 5.5 74ce7abcc6 docs(plan): monitor logs (.MLG) and each unit's monitoring timeline
Eight tasks: reader, writer, storage, ingest, timeline, routes, bulk import
with a cross-check against the event files, and the reference's D.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 03:43:45 -05:00
serversdownandClaude Opus 5.5 6f5898fe4e docs(spec): monitor logs (.MLG) and each unit's monitoring timeline
Design for reading Blastware .MLG files into SFM and deriving each unit's
monitoring timeline (sessions, stop reasons, call-ins), for shot reports
and outage history. Includes the measured MLG format: length-led 292-byte
records with a CRC-16/AUG-CCITT tail (3,329 / 3,329 records).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 03:33:02 -05:00
serversdownandClaude Opus 5.5 77a0296496 chore: every text file LF by default, and a test that fails on CRLF
5dff54b listed file types; a Dockerfile, .jsonl, .gitignore or any type not
yet invented had no rule.  .gitattributes now defaults every file to
`text=auto eol=lf` (Terra-View's rule), marks the binaries, and keeps
tests/fixtures/** -text.  Renormalizing under it changes no file.

tests/test_line_endings.py fails if a tracked file outside the fixtures is
stored CRLF, or if the rule stops covering new text types, fixtures or
binaries.  Its CRLF detector, pointed at the fixtures, finds all 38.
Suite: 1,711 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-12 16:38:10 -05:00
serversdownandClaude Opus 5.5 5dff54b292 chore: store source and docs with LF line endings (.gitattributes)
The protocol reference, seismo_lab.py and one scratch CSV were CRLF, so a
rewrite outside the Edit tool turned them into whole-file diffs, and merges
into them had to be resolved byte by byte.  They are converted once (line
endings only: the diff ignoring CR at EOL is empty), and .gitattributes keeps
every source and doc type LF from now on, whatever writes it.

tests/fixtures/** is -text: Blastware's own reports and exports, captures and
event files stay byte for byte (38 CRLF fixtures, unchanged).

A branch that edits one of the three files merges with -X renormalize.
Suite: 1,693 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-12 15:29:36 -05:00
serversdownandClaude Opus 5.5 745aab40b1 docs(changelog): Unreleased -- an escaped checksum is the checksum, not data (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-12 15:28:00 -05:00
serversdownandClaude Opus 5.5 ff705ebf87 merge: an escaped checksum is the checksum, not data (#58)
S3FrameParser kept the 10 of a checksum sent as `10 02/03/04` as the reply's
last data byte.  It now takes the pair: 7,747 / 7,747 recorded replies check,
272 of them with an escaped checksum.  Fixes the 1C battery/memory misread
(419.84 V on 12 of 760 recorded status replies) and the 2C call-home read; the
5A file builder's own compensation is removed with it, and pre-fix .a5.pkl
frames are converted on load (A5_PICKLE_VERSION 2).  checksum_valid now sums
the unescaped payload.

Conflict: the reference's changelog table (dev's own 2026-11-06 row); #58's
row kept as 2026-11-06 (2).  Suite on the merge: 1,693 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-12 15:27:00 -05:00
serversdownandClaude Opus 5.5 b24ea33b9d docs(changelog): Unreleased -- over range, the mic's range and dB offset, a green suite
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-11 15:23:23 -05:00
serversdownandClaude Opus 5.5 750ef1f84b merge: over range, the mic's range and dB offset, and a green test suite (the last of the 88)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-11 15:23:23 -05:00
serversdownandClaude Opus 5.5 c87e677294 docs: the last 16 values are left as they are, by decision
The vector sum's last digit on 4 waveform/histogram twins (no fitted
factor on a compliance number) and the 4 accelerations (O117I1NK's fit
rests on one clipped file): left and documented, Brian 2026-11-11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-11 15:22:49 -05:00
serversdownandClaude Opus 5.5 8544e9c7e2 docs(reference): the event footer ends in a CRC-16/AUG-CCITT
Footer [24:26] is CRC-16/AUG-CCITT (poly 0x1021, init 0x1D0F), stored
big-endian, over the footer record from its length prefix 00 1a through
footer [0:22] -- 24 bytes; the zero word [22:24] is not covered.
70,041 / 70,041 DL2 files.  Found by the .MLG session, verified here.
Retracts 2026-11-08's 'no common CRC-16 fits' (D.3.3, in place, and the
footer comment in event_file_io): every attempt had started at the
footer itself and missed the length prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-11 14:55:50 -05:00
serversdownandClaude Opus 5.5 8c6cad681c test: the suite runs green -- fix the 16 long-standing 'known failures'
They were two stale tests, not broken code:
- tests/test_bw_ascii_report.py (15) read its Blastware ASCII reports
  from decode-re/5-8-26/ at the repo root, removed when the fixtures
  moved to tests/fixtures/decode-re-5-8-26/.  At the real path all 27 of
  its tests pass.  The same stale path made a report-pairing test in
  test_event_file_io.py skip silently; it now runs and passes.
- test_save_imported_bw_without_report_works_unchanged (1) expected a
  sample-less event's PPV to be 0.0.  Since fa9d3cd (2026-05-20) the
  decoder deliberately leaves peaks unknown (None) so a backfill never
  writes zeros over real peaks; the sidecar-level check now says so.
  Its main assertion -- no bw_report block without a report -- is
  unchanged and covered nowhere else.

Full suite: 1,620 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-11 14:54:16 -05:00
serversdownandClaude Opus 5.5 e2c0f26b69 docs: over range, the mic's range and dB offset, and Blastware's mic unit labels
- Reference D.6.15 (new): over range -- a peak past 2,000 units (the mic
  in counts) is OORANGE, per channel and per histogram interval; the
  vector sum is OORANGE exactly when a geophone is (43 / 43), never on
  its own (38 / 38); the <OORANGE> line marks the mic over (18 / 18).
- D.6.6: the mic's own range byte (an eighth at 1; 7 events read 8x
  high); the dB offset corrected in place to 81.938216 (every printed
  count leaves [81.9382058, 81.9382266]); the unit labels that do not
  hold, and the mixed columns.
- D.6.11, CLAUDE.md: 80 of 88 report fields match on every DL2 event
  (run 20261109-144544, 0 regressions); the two causes left (the vector
  sum's last digit on 4 twins, 4 accelerations); the 'vector sum alone'
  case retracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 15:11:43 -05:00
serversdownandClaude Opus 5.5 6818e3023e feat(checker): a histogram row printing one unit in both mic columns is the mixed-units case
The ~20 histograms with one mic interval off were Blastware printing
the same number in both mic columns of a row: I145HKWT.DY0H row 672
reads 95.92 under psi(L) and dB(L) (count 5: dB), S353K894.OE0H rows
106 and 608 read 0.000 under both (count 2: psi).  SFM's count agrees
with the neighbouring rows and with the other column.  mic-units-mixed
now covers the interval mic columns too; a column names its own unit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 14:45:41 -05:00
serversdownandClaude Opus 5.5 0b6150adb5 feat(checker): read each mic value in the unit Blastware printed; carve out mixed columns
Blastware's dB(L) / psi(L) labels do not hold for the mic on every
report (DL2, 2026-11-09):
- the mic peak carries its own <Units>, which 7 reports set to dB under
  a psi Units line and 3 the reverse: the checker now reads the peak in
  its own unit;
- a mic sample table has no unit of its own and need not follow the
  line (S353JTHU.DT0W prints dB under psi): the checker reads it from
  its cells -- a mic dB value is never under 60, psi never over 1;
- some reports mix the two inside one column: K441L9IN.OT0W prints psi
  '0.000' for counts of 1 to 3 in a dB table.  Carve-out
  mic-units-mixed accepts a mic field when every cell SFM disagrees
  with is SFM's own value in the other unit: 19 DL2 events (14 sample
  tables, 5 peaks); a cell matching neither stays a mismatch.

Not a decoder change: SFM's mic data were right.  Checker run
20261109-141808: 78 of 88 fields, 0 regressions; no mic peak or mic
sample table mismatches left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 14:44:11 -05:00
serversdownandClaude Opus 5.5 e21d23a3f2 fix(decode): the mic dB offset is 81.938216, fitted on every count Blastware printed
The 81.9384 offset came from a window fitted on histogram intervals,
[81.9383, 81.9385], which was too high.  Every count Blastware printed
in DL2 -- 1,704 in waveform sample tables, 520 in histogram intervals,
494 histogram peaks -- leaves [81.9382058, 81.9382266]: count 129
(124.2) bounds it from below, 463 (135.2; 81.9384 prints 135.3) and 677
(138.5) from above.  One offset serves all three printing paths; no
count prints two ways once range-1 mics and psi-formatted tables are
set aside.  Fixes the mic samples and peaks that sat one digit off at a
rounding edge.  The old window's comment is kept, retracted in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 14:04:55 -05:00
serversdownandClaude Opus 5.5 e25784d9db feat(decode): over range inside a histogram's intervals, as in the event
Inside an interval the rule is the event's: a peak past 2,000 units
(the mic in counts) is Blastware's OORANGE, and the interval's vector
sum is OORANGE when any geophone is.  DL2 (2026-11-09): numeric up to
1,846 (geophones) / 1,414 (mic), OORANGE from 2,001; vector sums 16 / 16
OORANGE with a geophone over, 2,862 / 2,862 numeric without.

event_file_io.over_full_scale(count, channel); the checker renders those
interval cells as OORANGE.  The saturation carve-out compares SFM's own
words properly (_differs): an OORANGE from SFM never counts as
saturation, and an OORANGE equal to Blastware's is not a difference.
Its interval tests run on the numeric values it used to see.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 13:35:08 -05:00
serversdownandClaude Opus 5.5 836c9e864b fix(decode): the mic's own range -- a range-1 mic reads an eighth
The mic's channel block carries a range byte at the geophones' offset
(label + 29, reference D.6.4).  At 1 each count is an eighth, 0.25 / 8
Pa: set on 7 DL2 events, all of them Blastware's values divided by 8,
and on none of the other 70,026 -- independently of the geophone range
(28 events have Sensitive geophones and a range-0 mic).  SFM read those
7 mics 8x high: K557J1XQ.GF0W is 79.4 dB(L), not 97.5.

Event.mic_range; the decoded mic peak (and so the .h5 mic samples, whose
scale is the peak's) and the checker's mic conversions follow it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 13:32:07 -05:00
serversdownandClaude Opus 5.5 af8dde5114 feat(decode): over range from the unit's own peaks -- Blastware's OORANGE
A channel is over range when the unit's own peak (its summary's min /
max) passes 2,000: 32,000 counts, full scale, on either geophone range;
the mic in counts.  Blastware prints OORANGE for that channel's peak,
for the vector sum when any geophone is over, and its "Out of Range"
line when the mic is (DL2, 2026-11-09): numeric up to 1,991 / 1,933,
OORANGE from 2,001; the vector sum is OORANGE on all 43 events with a
geophone over and on none of the 38 whose vector sum alone passes
10 in/s -- the open "vector sum alone" carve-out was never needed.

PeakValues gains tran/vert/long/mic/pvs_over_range.  The checker matches
OORANGE by the flag, and calls a flag against a printed number a
mismatch.  Clipped events that the saturation carve-out used to accept
now match outright; the carve-out stays as the fallback for a file
without the unit's summary, and its guards are tested that way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 12:51:57 -05:00
serversdownandClaude Opus 5.5 e542e61b68 docs(reference): an .MLG is little-endian, and its flags are the footer's flag word
D.2 and D.4.2 said MLG timestamps are big-endian; §7.5 already had the
year little-endian.  Measured on the 4 bench .MLG files: every date's
year is little-endian, and a record's [22:26] is the event footer's
flag word and trigger source (D.6.14), little-endian.  BE9441's 10-25
session lines up 20 / 20 with its event files.  write_mlg() writes
big-endian dates; nothing calls it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 12:37:37 -05:00
serversdownandClaude Opus 5.5 d740897714 docs(changelog): Unreleased -- the monitor log line from the footer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 12:36:02 -05:00
serversdownandClaude Opus 5.5 15112ef83b merge: the monitor log line from the file's footer (group F)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-09 12:36:02 -05:00
serversdownandClaude Opus 5.5 ed8712ac8e docs: the monitor log is in the footer (reference D.6.14)
- Reference D.6.14 (new): the Monitor Log line is the footer's ts1 - ts2
  plus words for its flag word [18:20]; 69,983 / 69,983 DL2 lines,
  character for character; the flag table and how common each is.
- D.3.3: footer [18:20] flags, [20:22] trigger source, [22:24] zero;
  [24:26] still unknown (no common CRC-16 or sum fits).
- D.6.11, CLAUDE.md: 72 of 88 report fields match on every DL2 event
  (run 20261108-034313, 0 regressions) and what is still open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-08 04:08:23 -05:00
serversdownandClaude Opus 5.5 b6309027b3 feat(decode): the monitor log line from the file's footer (group F)
Blastware prints one Monitor Log line per event: the footer's start and
stop, then words for the footer's flag word [18:20] -- 69,983 / 69,983
DL2 lines, character for character (2026-11-08):

  0x0001 Event Recorded       0x0010 Timer Stop
  0x0002 Keyboard Exit        0x0020 Modem Exit
  0x0004 Remote Exit          0x0200 Battery Low Exit
  0x0008 Selfcheck Passed     0x0800 Memory Full Exit

One line sets Modem and Timer and prints Modem, so the higher bit wins
(the order of the others is inferred).  Footer [20:22] is the event
record's trigger source again (69,983 / 69,983); [22:24] is zero; [24:26]
is not a common CRC-16 or sum.

Event.monitor_log: MonitorLogLine(start, stop, flags, description), read
only when the file's record chain is whole, which proves the footer.
The checker compares it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-08 03:43:05 -05:00
serversdownandClaude Opus 5.5 4402753e70 docs(changelog): Unreleased -- sensor check results, and a no-mic unit's traces
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-07 15:58:16 -05:00
serversdownandClaude Opus 5.5 3cd414b589 merge: sensor check results from the unit's own records (group E)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-07 15:58:16 -05:00
serversdownandClaude Opus 5.5 7b45647b23 docs: #58 in the reference and CLAUDE.md; unescape_reply's 748 were replies
Reference row 2026-11-06: an escaped checksum is the checksum, measured on
7,747 / 7,747 recorded replies, with what the stray byte misread.  CLAUDE.md's
phase-5 warning marked fixed, and the reply rule widened.

Corrects 89c5234's unescape_reply docstring: the 2026-10-26 recording's
748/748 was measured on its replies (it also has 748 requests); I had called
them Blastware's requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-06 14:57:39 -05:00
serversdownandClaude Opus 5.5 47da0ddef0 fix(framing): checksum_valid sums the reply's payload unescaped
S3FrameParser summed its payload with the kept `10` of each `10 02/03/04`
still in, so checksum_valid was False on about a third of good replies (the
old "S3 checksums frequently fail" belief).  SUM8 of the unescaped payload
is the unit's checksum on 7,747 of 7,747 recorded replies; the test pins it
on the 2,509 in the committed October fixtures (62 with an escaped checksum),
which also proves #58's split of data from checksum on real replies.

Nothing decides on checksum_valid; seismo_lab's display stops crying wolf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-06 14:54:45 -05:00
serversdownandClaude Opus 5.5 89c5234ac0 fix(framing): an escaped checksum no longer leaves its 0x10 in a reply's data (#58)
A MiniMate sends a checksum of 02, 03 or 04 as `10 X`.  S3FrameParser kept
both bytes and _finalise took only the last as the checksum, so the frame's
data ended in a stray 0x10.  It now takes the pair.

Measured on every recorded reply (60 captures, March to October 2026): SUM8
of the unescaped payload is the checksum on 7,747 of 7,747; 272 arrived
escaped, all valid as an escape pair.

What the stray byte did:
- 1C status: battery and memory are counted from the end; 12 of 760 recorded
  status replies read 419.84 V / 251,654,656 bytes (6.76 V / 983,026).
- 2C call-home read: one byte long, refused as "monitoring".
- 1A, 09 reads: already trimmed (bench 2026-11-04); the trims stay as guards.
- 5A file builder: compensated in _frame_body_bytes; that pairing is removed,
  else a real 0x10 ending a chunk (one in ten do) would be dropped.

Stored .a5.pkl frames: A5_PICKLE_VERSION 2; load_a5 drops the stray 0x10
from version-1 frames.  All 28 pickles on this box rebuild byte-identical
to dev's build.

Operational consequence: none for prod's stored events (S3 events arrive
through save_imported_bw, which keeps no frames); no schema change, no
TOOL_VERSION bump, no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-06 14:52:50 -05:00
serversdownandClaude Opus 5.5 a80ea759e4 docs: the record chain to the footer and the sensor check (reference D.6.13)
- Reference D.6.13 (new): the tail of an event file is one record chain
  ending exactly at the file's end (70,041 / 70,041 DL2 files); the
  sensor-check header layout and what Blastware prints from it.
- D.3.3: the footer is the chain's last record (length 00 1a, id 0e).
- D.6.12: 'before and after' retracted in place -- one record per channel.
- D.6.11, CLAUDE.md: 71 of 88 report fields match on every DL2 event
  (run 20261106-125854, 0 regressions; 59 before group E).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-06 13:23:39 -05:00
serversdownandClaude Opus 5.5 f222ea9e80 fix(sensor-check): a unit without a mic keeps its three geophone traces
The trace decoder required all four records 0x3c-0x3f, so BE16352 (no
mic: 0x3c-0x3e only, all 8 of its DL2 events) got no sensor-check traces
at all.  The three geophone records, chained by their length prefixes,
are now enough.  The .h5 writer already stores a three-channel set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-06 13:00:16 -05:00
serversdownandClaude Opus 5.5 f7b310b130 feat(decode): sensor check results from the unit's own records (group E)
The record chain that starts with the embedded event record runs to the
file's end on all 70,041 DL2 files: the event record 0x05, the unit's
summary 0x32-0x35, its sensor checks 0x3c-0x3f, then the footer 0x0e
(no 0x35 / 0x3f on a unit without a mic, 8 files).  _record_chain walks
it and refuses a chain that does not end exactly at the file's end; the
unit's summary is now read from it too.

Each sensor-check record's header holds the results (DL2, 2026-11-06):
[2] channel type (1 geophone, 2 mic, 0 disabled), [4] status (0 =
passed), [5:7] frequency x 10, [7:9] ratio x 10, [9:11] amplitude mV.
Blastware prints them as they are: 209,943 / 209,943 geophone
frequencies and ratios, 69,975 / 69,975 mic frequencies and amplitudes;
"Passed" on status 0, "Check" on every other (its bits not decoded:
a Check can sit inside every passing range), "Disabled" on type 0.

Event.sensor_check_results: channel -> SensorCheckResult (result,
status, freq_hz, ratio, amplitude_mv).  The checker compares them.
Behaviour change: an unknown id inside an intact chain now leaves only
that record unread (was: everything after it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-06 12:58:31 -05:00
serversdownandClaude Opus 5.5 d2fe675650 docs(reference): 256, 4,096 and 65,536 mean a number outgrew its box
A note at the head of Appendix D.6 listing every case so far: the
O117I1NK sample wrap, the unit's 16.16 fixed-point step, the histogram
PVS2 high word above 1.28 in/s, the old 1.275 in/s byte clip, and the
64 KB 5A page.  Brian's observation, 2026-11-05.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-06 12:35:56 -05:00
serversdownandClaude Opus 5.5 6591b09b31 docs(changelog): Unreleased -- ZC frequency, displacement and times of peak from the unit's summary
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-06 03:22:20 -05:00
serversdownandClaude Opus 5.5 8e9a3ac9cf merge: ZC frequency, peak displacement and times of peak from the unit's own event summary (group D, part 2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-06 03:22:02 -05:00
serversdownandClaude Opus 5.5 b53de5448f docs(CLAUDE.md): untangle the acceleration sentence
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-05 17:46:39 -05:00
serversdownandClaude Opus 5.5 f5feb0eabc docs: the unit stores its own largest sample step; Blastware's acceleration is still its own
The summary's unidentified [15:21] is the stored samples' largest step
plus 0 to 1 unit, x 65,536, on 19,479 geophone channels: probably the
unit's own step at full resolution (inferred).  Blastware does not print
it -- its acceleration matches the samples on 19,475 / 19,479 and this
field on 879.  Corrects 'acceleration is not stored'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-05 17:46:28 -05:00
serversdownandClaude Opus 5.5 8d5c16b03b docs: the unit's own event summary (reference D.6.12), and group D in CLAUDE.md
- Reference D.6.12 (new): the record chain after the embedded event
  record, the per-channel summary layout, what Blastware prints from it,
  why recomputing failed, and the two odd 2019 files.  Group D part 1
  (time of peak, acceleration with the fitted g) is documented there too.
- Reference §7.8.9: its "constant, meaning unknown" bytes amended in
  place (the vector-sum peak sample, then the next record's lead).
- Reference D.6.11 and CLAUDE.md: 59 of 88 report fields match on every
  DL2 event (run 20261105-140021, 0 regressions; 47 before group D).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-05 14:25:31 -05:00
serversdownandClaude Opus 5.5 9091fe75a9 feat(decode): ZC frequency, peak displacement and times of peak from the unit's own event summary
After its embedded event record, every Blastware event file carries the
unit's own per-channel summary: a chain of [length][id][payload] records,
ids 0x32 Tran .. 0x35 MicL, each with min, max, peak sample,
half-period and a displacement integral; the event record itself holds
the vector-sum peak's sample.  Blastware prints these as they are
(measured on DL2, 2026-11-05):

- ZC frequency = (rate / 2) / half-period: 15,844 / 15,844 waveform and
  104,000 / 104,000 histogram values; every word too (">100" at <= 5
  samples, "N/A" at 0, "<1.0" beyond rate / 2).  Recomputing from the
  samples had reached 46%: the unit works at full resolution.
- peak displacement = half the integral x 16 counts x in/s per count /
  rate: 19,479 / 19,479 (84% recomputed).
- times of peak and the vector-sum time now come from the unit's peak
  samples.  They equal the samples' argmax on 25,962 / 25,966 channels;
  the 4 others are O117I1NK.R70W, whose stored samples wrap at the
  trigger (Blastware's own sample table has the same wrapped values).

The event-record readers return the validated record's offset, so the
summary is read from that spot only.  No summary: nothing is set, and
times of peak stay the samples'.

The checker reports ZC frequency and displacement, and reads the mic's
above-range flag under its real name (mic_zc_above_range).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-05 14:00:13 -05:00
serversdownandClaude Opus 5.5 c9f41deadd chore(release): v0.34.0 — Series-4 parity, and most of Blastware's report from the event file alone
- CHANGELOG: Unreleased -> v0.34.0 — 2026-11-04, with the release theme
  and a Migration section (schema re-key + overnight backfill that moves
  every Series-3 histogram time by one second; rehearsed twice on a copy
  of prod's 2026-09-30 snapshot).
- pyproject.toml, CLAUDE.md, README: 0.34.0 (README gains its status
  entry).
- TOOL_VERSION 0.34.0: the codec changed, so the backfill regenerates.

Verified on dev before this commit: the full decode checker matches
pre-parity dev on every verdict of all 70,112 DL2 events (47 of 88
fields), group D part 1 ran clean on its branch, and the suite has only
the 16 known failures (1,566 passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 17:58:54 -05:00
serversdownandClaude Opus 5.5 9f3434ff2b docs(changelog): Unreleased -- time of peak, vector-sum time and peak acceleration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 17:56:58 -05:00
serversdownandClaude Opus 5.5 401d83dc2c merge: a waveform's time of peak, vector-sum time and peak acceleration (group D, part 1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 17:54:56 -05:00
serversdownandClaude Opus 5.5 75a1d135ee docs(changelog): Unreleased -- Series-4 parity in SFM (phases 1-5)
Everything by serial for both series, the audited changes (start/stop,
call-home, settings), the MiniMate wire fixes (#46, the 64 KB page, the
settings read as content), the legacy config write retired, the benches.
Operational: additive schema only (device_commands), no TOOL_VERSION bump,
no backfill from this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 16:29:07 -05:00
serversdownandClaude Opus 5.5 5b342b4d7d merge: feat/series4-sfm-parity -- Series-4 parity in SFM, phases 1-5
Everything by serial for both series (identify, status, settings, events,
download, start/stop, call-home on/off, settings change), live downloads
stored as the watcher stores them, the legacy config write retired.
Phase 4 benched 2026-11-03, phase 5 benched 2026-11-04 on BE9441 and
UM20147.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 16:26:45 -05:00
serversdownandClaude Opus 5.5 3564c4a744 docs: phase 5 benched on both series (2026-11-04)
Both protocol references, the spec's bench section and CLAUDE.md record
the bench: every settings change acknowledged, read back and confirmed on
the unit's screen, both units restored byte for byte; the escaped-
checksum stray byte (fixed); a MiniMate's open setup menu writes its
whole-block copy back on Cancel or Save, losing a remote change; the
alarm write at channel +38; [26:28] re-set by the unit while monitoring;
the first Micromate setup push with the unit's CRC equal to SFM's; the
Micromate scheduler switch in none of the blocks SFM reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 16:16:40 -05:00
serversdownandClaude Opus 5.5 c790e20116 fix: bench follow-ups -- the setup-menu warning, observed call-home values, waveform read
From the 2026-11-04 bench:
- A MiniMate settings preview warns that a change is lost if someone is in
  the unit's setup menu: a write sent with the menu open was acknowledged
  and read back, then lost on Cancel or Save -- the menu writes its own
  copy of the whole block back (measured both ways on BE9441).
- The two bytes after the MiniMate settings block went out as 00 00 and
  the unit took them; the preview note says so instead of 'unmeasured'.
- A Micromate call-home plan no longer warns about 0x00 / 0x01: UM20147
  took both, each way, on 11-03 and 11-04, matching its menu.
- read_waveform_data_raw drops the escaped-checksum's stray 0x10, as the
  settings read does (it failed closed: the write's block check refused
  203 bytes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 16:15:28 -05:00
serversdownandClaude Opus 5.5 55c7b7b5ae feat(codec): the MiniMate alarm level is writable (benched 2026-11-04)
S3_ALARM_WRITE_MEASURED = True.  At the bench on BE9441, with Brian's go,
the alarm went 1.0 -> 1.5 -> 1.0 in/s: each write acknowledged, read back
as sent, and shown in the unit's own setup menu.  The write moved exactly
channel +39 of the three geophone blocks (the f32 at +38), where the
event files put it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 16:12:58 -05:00
serversdownandClaude Opus 5.5 09f34c2c85 fix(decode): Blastware's g for peak acceleration, fitted to every DL2 value
Every printed acceleration in DL2 bounds Blastware's g; together they
leave [386.2236, 386.2240] in/s^2, and 386.2238 fits 19,475 / 19,479
values.  The other 4 are one odd file (O117I1NK.R70W, whose peak times
are also off) and one sample mismatch.  That is 9.81 m/s^2 (386.2205,
19,423) plus an unexplained offset, as with the mic's fitted dB offset.
The 59 values 9.81 left were all one last digit high.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 15:47:13 -05:00
serversdownandClaude Opus 5.5 233289d029 feat(decode): a waveform's time of peak, vector-sum time and peak acceleration
Group D, part 1, measured on 400 DL2 waveforms (2026-11-04):
- time of peak = (first peak sample - pre-trigger samples) / sample
  rate, per channel including the mic: 1,197 / 1,197 geophone values
- the vector sum's time, the same on sqrt(T^2 + V^2 + L^2): 398 / 399
- peak acceleration = the largest |v[i+1] - v[i]| x sample rate / g,
  with Blastware's g = 9.81 m/s^2: 1,190 / 1,197 (the standard 9.80665
  gives 1,073).  Blastware's manuals: 'subtracts two velocity readings
  and divides the result by the elapsed time between them'.

PeakValues gains *_time_of_peak, pvs_time and *_peak_accel_g, filled
for waveforms only.  The checker reports them.  Displacement (84% with
the manuals' half-cycle integral) and ZC frequency (46%) are not shipped
yet -- Blastware does something more there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 15:19:53 -05:00
serversdownandClaude Opus 5.5 9992b25fde fix(s3): a settings read takes exactly what each frame was asked for
Bench 2026-11-04, BE9441 live: frame B of a 1A read arrived one byte long,
ending in a lone 0x10.  When a frame's checksum byte is itself escaped
(02 / 03 / 04, about one frame in 85) the parser keeps the escape's 0x10
and strips only the byte after it.  The 12 recorded reads never hit it,
so the assembled block was 2,091 bytes and SFM refused it as 'monitoring'.
read_compliance_content now passes the lengths it asked for (1024, 1024,
42) and that one stray byte is dropped; any other leftover still fails
is_compliance_content.  The trimmed read decodes exactly as the old
decoder read the same reply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 13:11:32 -05:00
serversdownandClaude Opus 5.5 2d237be5ef fix(ingest): a live download is held to its record type (#51)
Since #51 a waveform and a histogram recorded in the same second are two
events (UNIQUE(serial, timestamp, record_type)).  persist_download's
'already stored?' checks matched any row at the second and any row under
the letterless Blastware name both twins share, so a live download of
one twin was skipped as stored.  Both checks now hold to the download's
own type, read from its file (STRT[18]; IDFW / IDFH); an untyped row at
that second, or a download whose type does not read, still counts as
stored.  find_event_by_blastware_name takes an optional record_type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 12:34:46 -05:00
serversdownandClaude Opus 5.5 f24913189b merge: dev 9b458b5 into the parity branch (group A/B, #51 histogram timing)
Brings the checker's file-only decode work onto the parity branch so the
phase-5 bench runs on the code that will ship.  One conflict, the CRLF
Series-III reference changelog: both kept, phase 5's row numbered
'2026-11-03 (5)' above dev's (4)/(3)/(2).  test_event_ingest's live-
histogram dedup test asserted the stored row sits a second off the 0C
time -- the #51 bug, fixed on dev -- so its premise now reads the event's
own second; the dedup it tests still holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 12:31:21 -05:00
serversdownandClaude Opus 5.5 9b458b5d92 docs(changelog): Unreleased -- histogram timing in the protocol reference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 12:19:52 -05:00
serversdownandClaude Opus 5.5 1f8494dbc4 merge: histogram timing in the protocol reference (D.6.10), and the unit + time + type key
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 12:19:41 -05:00
serversdownandClaude Opus 5.5 d4cfb07fce docs: histogram timing from its own event record (D.6.10), and the unit + time + type key
The reference gains D.6.10: the histogram's embedded event record (lead
00 28 05 00, source 04 00, marker fe f5, start, stop) and the interval
and peak-time rules, with 'histograms stay on ts1' retracted in place.
CLAUDE.md 'Where things stand' records the new events key -- any lookup
by event needs the type -- and 47 of 88; the README roadmap follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 12:19:38 -05:00
serversdownandClaude Opus 5.5 d75dc6f5f1 docs(changelog): Unreleased -- #51, unit + time + type and Blastware's histogram times
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 12:18:20 -05:00
serversdownandClaude Opus 5.5 074c98823f merge: events are identified by unit + time + type, and histograms take Blastware's times (#51)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-04 12:17:30 -05:00
serversdownandClaude Opus 5.5 08d0a6c0d4 fix(settings): final-review fixes -- revision, resulting limits, logical writes
From the whole-branch review of phase 5:
- The preview's revision now covers the changes asked for, so a live
  change must be exactly what was previewed (any API caller, not only the
  page).  It covers what the preview showed -- the settings block (and a
  Micromate's setup name) -- not the blocks a write only echoes, which are
  re-read at send and sent as read (a MiniMate's trigger block byte 5
  differs by session, #46).
- The units' limits hold on the block that would result: a range, rate or
  mode change alone can no longer leave a held trigger, alarm or record
  time over them.
- Every MiniMate block read is logical, so push_config_raw no longer
  unescapes again (a job number of 4098, 10 02, was refused at Send); the
  preview runs the write's own block check, so a block it would refuse is
  shown as blocked.
- A MiniMate's monitoring refusal says a stop makes it call in (spec).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 22:10:49 -05:00
serversdownandClaude Opus 5.5 385716d8e1 feat(webapp): edit a unit's settings by serial: preview, send, read back
The Config tab by serial is now the unit's edit form, headed 'On the
unit <serial> -- read HH:MM' and built from the server's editable
fields.  Preview runs a dry run and shows old -> new, notes and anything
that blocks the change; Send (confirm) sends exactly what was previewed,
with its revision, then shows what the unit now holds and re-reads it.
An edit after a preview disables Send until the next preview.  The
by-host form loses its write button; the read stays.  Logic in
device_routing.js (Node-tested), glue in sfm_webapp.js, no inline JS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 21:57:17 -05:00
serversdownandClaude Opus 5.5 e8eabee4a2 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
2026-11-03 21:51:20 -05:00
serversdownandClaude Opus 5.5 66bb29b9d4 feat(s3): change a MiniMate's settings by serial on the shared codec
Series3Adapter.settings reads the 1A block assembled into its 2,090
logical bytes and decodes it with micromate.setup_fields (a monitoring
unit's device-info answer is refused with 'stop monitoring first').
change_settings runs the shared change core: read the four settings
blocks, patch the settings block's fields, send Blastware's sequence
through push_config_raw with the event index, trigger and waveform blocks
as read, re-read.  Refused before sending: monitoring, a value the unit
does not allow, a stale preview.  push_config_raw's pre-check now raises
ImageRefused, so a refused image is audited as nothing sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 21:46:50 -05:00
serversdownandClaude Opus 5.5 c082f72d62 feat(s4): change a Micromate's settings by serial, audited, schedule-checked
s4_change_settings runs the shared change core with a read-back verdict
for its state (as asked / unchanged / differs).  It reads the active
setup's name (unstripped), the preferences, trigger and setup blocks and
the schedule; patches the setup through micromate.setup_fields; sends
THOR's setup push (0xDA 68 73 82 83 71 72, now enableable) once; reads
the setup back.  Refused before sending: a monitoring unit, a value the
unit does not allow (422), a stale preview (SettingsChanged, 409), and --
shown as 'blocked' in the preview -- the factory setup, a schedule that
loads another setup, an unreadable schedule, or a block SFM has not seen
(ChangeRefused, 409).  s4_settings carries the editable fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 21:43:03 -05:00
serversdownandClaude Opus 5.5 d0335dbbbd feat(micromate): read the schedule file (read-only)
MicromateProtocol.read_file: 0x94 + path, then 0x48 pages to an
all-zero reply -- THOR's frames byte for byte (UM12947, 2026-09-24),
including params[3] = 1 on 0x94 and params[7] = 1 on the first 0x48.
micromate.schedule parses the 260-byte records (two- and five-entry
schedules from THOR's captures) and names the scheduled starts that
would load a setup other than the active one, ignoring case.  The
client gains the raw (unstripped) active-setup name and the prefs /
trigger / setup content reads a setup push sends back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 21:37:30 -05:00
serversdownandClaude Opus 5.5 9cfa82117b feat(decode): histogram interval times and peak times (#51 group C)
With the start right, the rest of Blastware's histogram timing follows,
measured on a 2,000-histogram DL2 sample:
- each interval's printed time is its end, start + (i + 1) x interval,
  capped at the stop: 2,308,524 / 2,308,524 rows
  (event_file_io.interval_times)
- each of Tran / Vert / Long / PVS / MicL's peak date and time is that of
  the interval holding its first maximum: 2,000 / 2,000 each.
The checker compares intervals.Time and the ten peak date/time fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 21:35:54 -05:00
serversdownandClaude Opus 5.5 a9bb9f08c0 fix(decode): a histogram's start and stop come from its own event record (#51)
The footer's start runs a second early on 97% of histograms.  Each
histogram carries an event record like a waveform's -- lead 00 28 05 00,
source 04 00, marker fe f5, then start and stop -- and it holds
Blastware's Histogram Start and Stop on 63,490 / 63,490 DL2 histograms.
On all 63,500 there is exactly one, its start 0 or 1 s after the
footer's and its stop 0 or 1 s before; that is the validation rule.
Without a validated record the footer's start stands, as a decode
problem.

Ships with the unit + time + type key (ea2dfc2), without which a
waveform and its histogram at the same second would collide.  Three
tests that pinned the old footer start (one said 'for now', pointing at
#51) now pin the record's, which equals the file's Blastware name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 21:33:32 -05:00
serversdownandClaude Opus 5.5 5ba72740dd feat(codec): one settings codec for both series, on the shared layout
micromate/setup_fields.py: the fields an operator can change (record
mode, sample rate, interval, record time, geophone trigger, Series 3's
range and -- read-only until benched -- alarm, job number and its report
flag, the four notes by slot), the units' own limits from Instantel's
manuals, field-only byte patching (bit fields bit by bit; Series 3's
[26:28] as Blastware writes it; Series 4's CRC recomputed), the
read-back verdict compared by bytes, and the preview revision.

All 11 Blastware compliance writes reproduce from the block before them
(BE11529's first also shows Blastware re-rendering two mic levels
through its dB value; SFM echoes the unit's bytes); Series 4 keypad
fixtures reproduce pairwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 21:33:01 -05:00
serversdownandClaude Opus 5.5 e24e77bfd0 test: the estimate guard's neighbour is an event of the same type (#51)
Under the unit + time + type key, the test's untyped neighbour no longer
shared the imported waveform's key, so the waveform was stored as its
own row -- the neighbour untouched, which is what the test's name asks.
The guard's job is an estimate landing on another waveform's second, so
the neighbour is now a waveform.  A companion test pins the case the new
key allows: an estimate beside a histogram at its second is stored
alongside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 21:30:51 -05:00
serversdownandClaude Opus 5.5 ea2dfc21b7 feat(db): events are identified by unit + time + type (#51)
The events table was UNIQUE(serial, timestamp): one event per unit per
second.  A unit records a waveform and a histogram in the same second
legitimately -- 209 times in prod's 2026-09-30 store once histograms
carry Blastware's start -- so the key is now (serial, timestamp,
record_type).  Agreed with Brian 2026-11-03.

- Migration 3 rebuilds the table from its own current definition with
  only the key swapped, in one transaction: every column, row and id is
  kept (Terra-View reads rows by id) and the indexes are recreated.
  Migration 1's check no longer mistakes the new key for a missing one.
- The upsert, the estimate guard and the restamp match on the type too.
  The restamp also re-types a file's own row in place: before v0.33.0 a
  row's type came from the filename, and a re-import under the file's
  own type must not add a second row.
- An untyped event still refreshes the untyped row at its second (a
  UNIQUE key treats NULLs as distinct).
- scripts/repair_unknown_serials.py checks the new key.

No time changes yet: that is the next commit, and they ship together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 21:29:46 -05:00
serversdownandClaude Opus 5.5 1bb15573fc feat(s3): assemble a settings read into the 2,090-byte block
Unescape each 1A data frame, take data[11:], drop the one non-content
byte that starts every frame but the last: 2,090 bytes headed by
N = 2090, Series IV's 0x1A layout.  Measured on BE9441's 10-26
recording (12 reads, both frame patterns); the read after each
Blastware write equals the image written.  read_compliance_content is
strict (a missing frame raises) and unjudged (a monitoring unit's
device-info answer comes back for the caller to recognise).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 21:28:04 -05:00
serversdownandClaude Opus 5.5 e3a77e421d docs(spec,plan): phase 5 -- the units' own limits, from Instantel's manuals
Brian: use the actual unit limits, not what has been used in the past.
Trigger 0.005-10 in/s in 0.001 steps (capped by the range), record time
1-90 s (Micromate) or the MiniMate manual's 1 MB table by sample rate
(13 s in Histogram Combo), job number 1-9999.  The read-back reports any
value a unit does not take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 19:30:07 -05:00
serversdownandClaude Opus 5.5 71609e71ab docs(plan): phase 5 -- changing a unit's settings by serial
Seven tasks: the Series 3 read assembly, one settings codec for both
series, the Micromate schedule read, each series' audited change, the
route (and the legacy write retired), and the page.  Spans measured
from 75,958 Blastware reports.  Bench after the final review, Brian's
go per send.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 18:51:53 -05:00
serversdownandClaude Opus 5.5 dba891d504 docs(spec): phase 5 -- the Micromate schedule check; work hours is next
A scheduled start loads the setup it names, so a change to another
setup would be undone at the next start: read schedule.dat and refuse
that case.  Configurable work-hours recording, without THOR's scheduler
or setup files, is the agreed next project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 18:35:29 -05:00
serversdownandClaude Opus 5.5 e8242aaadc docs(changelog): Unreleased -- group B in the protocol reference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 18:30:08 -05:00
serversdownandClaude Opus 5.5 19719bdd96 merge: group B in the protocol reference (D.6.9), #50 retracted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 18:29:54 -05:00
serversdownandClaude Opus 5.5 2c4ae8c4ef docs: group B in the protocol reference (D.6.9), #50 retracted
Interval size (k - 40), the stop (footer ts2), frequency = (sample rate
/ 2) / half-period with Blastware's words for N/A, >100 / >200 and
<1.0, and each interval's vector sum with its OORANGE rule.  The old
fixed-512 frequency formula is retracted in place.  CLAUDE.md and the
README roadmap follow: 34 of 88.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 18:29:53 -05:00
serversdownandClaude Opus 5.5 42933f76df docs(changelog): Unreleased -- histogram interval detail, #50
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 18:29:00 -05:00
serversdownandClaude Opus 5.5 31231d7e81 merge: a histogram's interval detail -- frequencies (#50), vector sums, interval size, stop (group B)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 18:28:27 -05:00
serversdownandClaude Opus 5.5 0238e4d3f3 docs(spec): phase 5 -- changing a unit's settings by serial
Brian's intent (UM6047's trigger, notes typos, the backup unit), the
flow, the first-version fields, and what is measured: Series 3's
compliance block has Series 4's 0x1A layout; a whole 1A read assembles
to the 2,090 bytes Blastware writes back (exact on both 10-26 writes);
Blastware writes 00 00 at [26:28] and a per-unit constant after the
block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 18:12:14 -05:00
serversdownandClaude Opus 5.5 13f2769736 feat(decode_check): an OORANGE interval vector sum is saturation
Blastware prints OORANGE for an interval's vector sum when it exceeds
the range in an interval where Blastware also clamped a channel: 17 / 17
DL2 cells, SFM's sum 10.01 .. 17.33 in/s (sqrt 3 x 10.005).  The
saturation carve-out now covers intervals.Geo PVS in/s with that rule,
per interval, as it already did for PeakVectorSum.  The 4 other cells
left mismatching sit 4e-6 past a rounding boundary (Blastware's
arithmetic is a hair lower) and stay mismatches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 18:02:51 -05:00
serversdownandClaude Opus 5.5 2b698e74cf feat(decode): a histogram's interval detail -- frequencies (#50), vector sums, interval size, stop
Group B of the file-only decode, measured on DL2 2026-11-03:

- Frequency = (sample rate / 2) / half-period: 527,915 / 527,915 cells
  at 1024 sps and 1,725 / 1,725 at 2048.  #50: half_period_to_hz took a
  fixed 512 and halved every 2048-sps frequency; it now takes the rate
  (default 1024).  Blastware prints 'N/A' for a half-period of 0, '>100'
  ('>200' at 2048) at 5 samples or fewer, '<1.0' below 1 Hz.
- Each interval's vector sum, sqrt(PVS^2) at the event's range:
  771,354 / 771,354.
- Interval size: uint16 seconds at k - 40 (Series IV [8:10]).
- Stop: the footer's (2,995 / 2,999 sampled; 4 print a second earlier).

Event gains histogram_interval_sec, interval_half_periods, interval_pvs
and stop_time; the .h5 gains /intervals/half_period/<ch>,
/intervals/pvs_ips and a histogram_interval_sec attr.  The decoder walks
a histogram once (histogram_codec.channels_from_records) and takes the
event's PVS from the same records.  The checker compares each interval
column, number or Blastware's word; the test that pinned Tran Freq Hz
as blank now pins the match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:34:27 -05:00
serversdownandClaude Opus 5.5 67b3ef8d0a docs(changelog): Unreleased -- group A in the protocol reference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:24:40 -05:00
serversdownandClaude Opus 5.5 1309f93fa9 merge: group A in the protocol reference, and the three meanings of mic 'units'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:24:29 -05:00
serversdownandClaude Opus 5.5 8f75be5f72 docs: group A in the protocol reference, and the three meanings of mic 'units'
Protocol reference:
- D.6.8 (new): the identity block (SUB FE's: serial, firmware, DSP version,
  calibration date and 'by', model; battery), the trigger-source bitmask
  in the embedded event record, and the trigger settings (sources, stop
  mode, per-channel levels, mic type) with their DL2 counts.  The
  histogram 'terminal tail' 9c 06 00 42 looks like 9c 06 00 + the
  serial's B (inferred).
- D.6.6: recorded data vs report units vs unit peaks, with the
  MiniMate Plus (s3.9.7) and Blastware (s4) manual sections.  Where the
  unit stores its own Microphone Units is unmeasured; a keypad test is
  proposed.
- D.6.9 (was D.6.7): refreshed, 28 of 88.

CLAUDE.md 'Where things stand' and the README roadmap follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:24:21 -05:00
serversdownandClaude Opus 5.5 06a4be9445 docs(changelog): Unreleased -- identity, battery and trigger settings from the file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:23:07 -05:00
serversdownandClaude Opus 5.5 3ee9923f81 merge: a Blastware file's identity, battery and trigger settings (group A)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:22:34 -05:00
serversdownandClaude Opus 5.5 6c2dbf0463 docs(decode_check): the units carve-out cites Instantel's manuals
Both settings are documented: the unit's Microphone Units (MiniMate Plus
manual s3.9.7, keypad Right Arrow + Setups: psi(L) / dB(L) / Pa(L)) and
Blastware's report preference (Blastware manual s4, Preferences > Units
and Channel).  The report follows Blastware's, as DL2's fleet-wide
switches showed.  Where the unit's own setting is stored is unmeasured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 17:15:28 -05:00
serversdownandClaude Opus 5.5 cbce00f8e1 merge: dev into feat/series4-sfm-parity -- the decode checker's file-only fields (job number, codec by STRT[18], last-26-byte footer)
Brings be5bab4 and its history from the decode checker's branch: a Blastware
file's job number; decode_blastware_bytes choosing the codec by STRT[18] and the
histogram layout check by peak <= PVS <= sqrt(3) peak; the footer as the file's
last 26 bytes (no day-late histograms); docs (reference Appendix D.6, the
file-only status).

Conflicts, both kept whole:
- CLAUDE.md: this branch's 'Narrowed 2026-10-26' 5A block stays, followed by
  dev's 'Open, not blocking' line (the 8x sensitive-range item struck out --
  resolved by the file's range).
- docs/instantel_protocol_reference.md (CRLF, byte-safe): the change-log rows in
  date order -- dev's 2026-11-03 and 2026-11-02, this branch's 2026-11-03
  (call home), 2026-10-29 and 2026-10-27 (#46, this branch only).

Suite on the merged tree: 1399 passed, the 16 known failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 15:34:59 -05:00
serversdownandClaude Opus 5.5 2e1c2ba21f docs: phase 4 bench -- call-home on/off on both series, idle and monitoring
Benched 2026-11-03 on UM20147 and BE9441 (each on its own modem, one send per
go): idle, a no-op, off and on all acked, read back and confirmed on each unit's
menu; UM20147 accepts 0x00 at [5].  Monitoring, neither series takes a change: a
MiniMate answers 0x2C with its device-info block, a Micromate acks and ignores
('Feature disabled while monitoring').  Series 4 [118:120] is a function of the
block's content -- XOR 0x6D7D per bit-0 flip on two units, not a nonce.  A stop's
call-in reached THOR when the ring followed the ack.  UM20147's clock is an hour
ahead (DST).  Spec, both protocol references (Series III: a CRLF row), CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 15:32:51 -05:00
serversdownandClaude Opus 5.5 789e24be50 fix(sfm): the top bar names a Micromate's firmware line; a stale overlay comment
- The page's top bar Firmware read '—' for a Micromate: Batch 2 gave the Device
  tab's card firmwareLabel() but not populateDeviceBar.  Seen at the bench
  2026-11-03; checked in jsdom ('—' before, 'Thor line (version not read)' after).
- save_imported_bw's overlay comment said the waveform codec was undecoded and
  gave +-10 in/s; the overlay now stays because production keeps a paired
  Blastware report as the record until the file-only decode has no blanks
  (flagged by the decode-checker session).  Comment only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 15:32:02 -05:00
serversdownandClaude Opus 5.5 f35845d403 fix(sfm): a Micromate's call-home is refused while monitoring, and only a real call-home block is ever edited
Measured at the bench 2026-11-03 (UM20147): monitoring, a Micromate returns its
real call-home block and ACKS a call-home write, but does not apply it -- three
read-backs unchanged, and its own menu says 'Feature disabled while monitoring'.
SFM now refuses up front (UnitStateUnknown, 409: '... is monitoring -- a Micromate
ignores call-home changes while monitoring ...; stop monitoring first -- nothing
sent'), dry run included, instead of sending a write the unit ignores.

And the block must be the call-home block: micromate.writes.is_call_home_content
checks its header is its own length (00 7C, N = 124 -- 00 7C DC on every read,
UM12947 and UM20147).  plan_call_home_enabled refuses any other 126 bytes, the
change refuses before sending, and call_home_state says why (enabled = None).
At the bench this was checked by eye before the monitoring write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 15:32:02 -05:00
serversdownandClaude Opus 5.5 5326e99ac2 fix(sfm): a monitoring MiniMate's call-home says 'stop monitoring first', not 'unknown(0x6E)'
Measured at the bench 2026-11-03 (BE9441): while monitoring, a MiniMate answers
the 0x2C call-home read with its DEVICE-INFO block ('Instantel', 'MiniMate Plus',
its serial) -- as it answers 1A -- and idle again, minutes later, the call-home
block.  SFM writes back only a block it just read, so a monitoring MiniMate's
call-home cannot be changed; the change core already refused (byte 5 read as
'unknown(0x6E)', nothing sent), but said so cryptically.

- minimateplus.protocol.is_call_home_block(raw): the block starts with its own
  length 0x7C and is N (or N + 2) bytes unescaped; the device-info block fails it.
- The Series-3 change raises UnitStateUnknown (409) with 'did not return its
  call-home settings -- a MiniMate answers the call-home read with its
  device-info block while monitoring; stop monitoring first ... nothing sent',
  for a dry run too.  call_home_state returns enabled = None with that reason.
- The page's callHomeRows shows the reason in place of 'Unknown (byte 5 = ...)'.

A blind write while monitoring stays untested on purpose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 14:19:19 -05:00
serversdownandClaude Opus 5.5 8d5a9987c9 fix(decode_check): compare a mic level in the unit it is printed in
K441LA17.IN0W's report says Units 'in/s and psi(L)' yet prints
MicTriggerLevel '125.0 dB(L)'.  The value states its own unit, so that
is the one compared; the report's Units is the fallback.  It was the
only MicTriggerLevel mismatch in DL2 (SFM's 0.005158 psi is 125.0 dB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 14:02:27 -05:00
serversdownandClaude Opus 5.5 6c2eda5f63 feat(decode): a Blastware file's identity, battery and trigger settings
Group A of the file-only decode, every field matched against every DL2
report (2026-11-03):

- Identity block before the setup name, what the live read gets from
  SUB FE: serial k-202, firmware k-147, DSP version k-138, calibration
  date k-132 + 'by' k-128, manufacturer k-94, model k-72, firmware
  minor k-193.  Event.device_info (DeviceInfo gains calibration_date /
  calibrated_by).  Serial, Version and Calibration 69,983 / 69,983.
- Battery: uint16 hundredths of a volt at k-190 (Event.battery_volts).
  69,729 exact; the other 254 are Blastware rounding half up.
- Trigger source: the two bytes between the embedded event record's
  lead and fe 80, a bitmask (0x01 Tran 0x02 Vert 0x04 Long 0x08 MicL
  0x200 Manual): 6,493 / 6,493.  Event.triggered_by.
- Trigger settings in Series IV's 0x1A layout: sources bitmask k-19,
  stop mode k-31 (0 = Fixed), each channel's float32 level at
  label+30 (geo in/s, mic psi), mic type code at MicL+4 (2 = Linear
  Weighting).  Geo level 6,447 / 6,447, mic 4,403 / 4,403; Blastware
  prints a level when its channel is a trigger source and the event
  was not Manual.  The mic level's dB uses 6895 Pa/psi (4,272 / 4,272
  against 4,271 at 6894.757).
- .h5 attrs for all of them (additive).
- Checker: SFM's side reports the ten fields; the mic trigger level
  follows the report's dB/psi.  Carve-out
  units-is-a-display-preference: dB or psi is Blastware's PC setting
  when it wrote the report -- DL2's reports switch fleet-wide in 61
  clean runs by write time, and no byte of the file separates them.
  Two tests that pinned BatteryLevel / Calibration as blank now pin the
  match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 13:38:39 -05:00
serversdownandClaude Opus 5.5 be5bab4787 docs(changelog): Unreleased -- where file-only decoding stands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 13:06:19 -05:00
serversdownandClaude Opus 5.5 fc7ce5df02 merge: where file-only decoding stands, and that prod's ASCII overlay is scaffolding
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 13:06:07 -05:00
serversdownandClaude Opus 5.5 5a089671e8 docs: where file-only decoding stands, and that prod's ASCII overlay is scaffolding
CLAUDE.md 'Where things stand' now says plainly how prod uses a paired
Blastware ASCII report (save_imported_bw overlays its peaks, notes,
sample rate and record time onto SFM's decode), that only report-less
events run on the decoder alone, and that the overlay is scaffolding to
retire at step 3 of the plan.  The checker status is brought up to dev:
18 of 88 fields, the remaining groups A-F in the proposed order.

README roadmap: the same framing and progress.

Protocol reference:
- D.3.3: the footer is the file's last 26 bytes; footer[18:24] is not
  fixed (retracted).
- D.6.1: STRT[18] picks the codec.
- D.6.3: the job number.
- D.6.5: the PVS^2 high word is non-zero above 1.28 in/s (retracted
  'reads 0000'); the peak/PVS consistency check; Blastware's Number of
  Intervals is the monitoring time / the interval.
- D.6.7: refreshed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 13:05:58 -05:00
serversdownandClaude Opus 5.5 fcacc8f28c docs(changelog): Unreleased -- the footer is the file's last 26 bytes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 13:04:13 -05:00
serversdownandClaude Opus 5.5 e227448483 merge: a Blastware file's footer is its last 26 bytes -- no more day-late histograms
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 13:03:29 -05:00
serversdownandClaude Opus 5.5 e1e8a851c8 docs: where the 1995 default-clock events come from
Brian's account: units come back from calibration with the internal
battery unplugged, so a comms-test trigger before the date is set
carries the default.  DL2 holds 17 such events on 6 units, all within
1995-09-01 12:02 .. 09-03 11:24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 12:12:02 -05:00
serversdownandClaude Opus 5.5 8a40eb638a fix(decode): a Blastware file's footer is its last 26 bytes -- no more day-late histograms
Every DL2 file ends in a valid footer: 0e 08 and two valid times on
70,041 / 70,041.  The decoder took the first '0e 08 + plausible year'
instead, and 14 files also hold an earlier record, ~1.1 KB before the
end, with the stop time followed by zeros:
- a histogram started at its own stop -- a day late on BE9558's daily
  histograms (K558L9XP.FK0H: 2025-10-08 19:10:01 for Blastware's
  2025-10-07 19:14:08); T003LCYV.JD0H got no time at all;
- a waveform lost its stop, so the trigger was never computed and the
  stop was stamped instead (K440I4LG.JK0W: 11:14:12 for 11:14:08).

The last 26 bytes are now taken when they are a footer; otherwise the
old search stands unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 12:10:44 -05:00
serversdownandClaude Opus 5.5 dd9f6dde7a docs(changelog): Unreleased -- histograms go to the histogram codec
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 11:32:57 -05:00
serversdownandClaude Opus 5.5 f768ec42f3 merge: histograms go to the histogram codec, and a loud interval no longer hides a short one
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 11:32:01 -05:00
serversdownandClaude Opus 5.5 9820a5389f docs(spec): phase 4's final review -- what it caught before the bench
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:24:13 -05:00
serversdownandClaude Opus 5.5 9e03b3f0ab fix(sfm): a Micromate in an unknown run state gets no call-home write, and a lost ack keeps its snapshot (phase-4 review)
- s4_change_call_home's read_state now returns an unknown(0xNN) run state as
  it is, so the change core refuses it (UnitStateUnknown, nothing sent), as
  start/stop already does; it checked only for calling_home.
- run_change records the snapshot on the lost-ack path too: after an ack is
  lost, what the unit now holds (and, on Series 4, whether [118:120] moved) is
  what tells whether the write landed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:23:59 -05:00
serversdownandClaude Opus 5.5 bdd76b8f74 fix(minimateplus): a built call-home image is framed once, never unescaped again (phase-4 review)
call_home_image returns the unescaped N + 2 image, but the send path handed it
to write_call_home_config, whose write_image unescapes again -- and unescaping
is not idempotent: a real 0x10 before 02/03/04 loses its 0x10.  A call-in time
of 16:02-16:04 (hour 0x10) is exactly that.  One such time made the send refuse
before the wire yet audited as 'sent, acknowledgement lost'; two made it send a
block shifted by two bytes from [101] (num_retries and the time fields wrong).
The Blastware-frame test could not see it: it checked the image builder, not
the bytes the protocol framed.

- MiniMateProtocol.write_call_home_image(image) frames a built image once
  (0x7E, ack 0x81, 0x7F, ack 0x80), raising ImageRefused before any byte when
  it is not a whole block; write_call_home_config (the legacy multi-field path)
  is write_image once + that.  Its stale 127-byte docstring is gone.
- MiniMateClient.write_call_home_image uses it.
- The Series-3 change passes is_refusal=ImageRefused, so a pre-wire refusal is
  audited as nothing sent (sent = 0), not as a lost ack.

Tests drive the real client -> protocol over a stub answering with BE11529's
recorded acks: the unit's own read, a 16:02 time, and 16:03 + 16:04 all go out
exactly as built; a short image is refused with nothing written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:23:59 -05:00
serversdownandClaude Opus 5.5 3e1d42e04b docs: phase 4 built -- call-home enable/disable by serial; bench questions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:07:36 -05:00
serversdownandClaude Opus 5.5 51e7dddcb3 test(micromate): corpus counts are floors, and 0x71 is the over-the-ceiling example
Two test-side breaks, found by the full suite after phase-4 task 6:
- test_micromate_framing's three whole-session tests pinned exact counts of a
  gitignored corpus (bridges/captures/9-24-26 - micromate2, a symlink into the
  main checkout).  The full copy of the BW VM's captures on 2026-11-02 added
  sessions: 287 responses / 241 reads / 287 requests, every one passing the same
  per-frame checks.  The counts are now floors (>= 251 / 218 / 251), so a lost
  file still fails and a grown corpus does not.
- test_micromate_opcodes' beyond-the-ceiling permit took 0x7E, enableable since
  the call-home commit (eeb55ef); 0x71 (the setup write, phase 5) replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:07:04 -05:00
serversdownandClaude Opus 5.5 84c142f36c feat(sfm): the page's Call Home tab by serial -- state and audited On / Off (phase 4)
device_routing.js (Node-tested): call_home_state / call_home_on / call_home_off
routes (serial required); controlsFor gains callHomeChange (by serial, a
confirmed Series 3 or 4) and callHomeRead now covers a Series 4 by serial;
serialPanes gains callHomeForm / callHomeBox; callHomeRows renders the switch
(On / Off / 'Unknown (byte 5 = 0xNN)'), dial string and series;
changeErrorText takes the whole label ('Start monitoring', 'Enable call-home').

sfm_webapp.js: by serial the Call Home tab hides the legacy multi-field form
(Series 3 by host only) and shows the unit's switch with On / Off.  Each asks
confirm(), sends one audited change, reports it with changeSummary /
changeErrorText, then re-reads quietly so the change's own result stays on
screen.  A different unit's switch is never left showing.  The new buttons are
wired with addEventListener, not onclick= (no inline JS).

Checked in jsdom against the real page: placeholder, read, Off (confirm, the
disable route, 'confirmed -- enabled -> disabled'), a serial edit clearing it,
legacy mode unchanged, no script errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:05:00 -05:00
serversdownandClaude Opus 5.5 06fa56db09 feat(sfm): call-home state and enable/disable by serial -- GET /device/call_home/state, POST /device/call_home/{enable,disable} (phase 4)
- DeviceAccess.call_home_state (a read) and set_call_home (change=True: never
  retried, audit required for a live change, dry run without one), routed by
  series like start/stop.  A config write is read back on its own window: up
  to 3 reads, 1 s apart, not the monitoring one.
- Routes, serial required (422 without), all three serial-aware: the state as
  a dict; enable / disable through _change_response, so their statuses are
  start/stop's and an unconfirmed change carries sent + audit_id.  The legacy
  GET / POST /device/call_home are unchanged (a Micromate serial is still
  refused there, 501).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:01:14 -05:00
serversdownandClaude Opus 5.5 453d42e32a test(s3): SFM's call-home write equals Blastware's, frame for frame -- opens the live send
Ground truth: Blastware changing BE11529's call-home settings on 2026-04-20
(Remote Access -> Setup Unit), paired raw files of what it sent and what the
unit answered: the read, the enable (read 0x00 -> wrote 0x01), the disable
(read 0x01 -> wrote 0x00).  From the unit's own read before each write, SFM's
0x7E frame (call_home_image + build_bw_write_frame) is Blastware's byte for
byte -- nothing but byte 5 differs from the read -- and the 0x7F confirm too.
Mutation-checked: inverting the byte SFM writes fails the test.

S3_CALL_HOME_FRAME_VERIFIED is now True; the gate stays tested shut by
monkeypatch, and a test pins that its comment names this proof.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:59:15 -05:00
serversdownandClaude Opus 5.5 8612cd9df7 feat(sfm): Series-3 call-home state and audited enable/disable, live send gated until its frame is verified (phase 4)
- minimateplus.protocol: call_home_enabled(raw) reads byte 5 of the UNESCAPED
  0x2C payload (0x01 on / 0x00 off, measured 2026-04-20; anything else None --
  bench finding #1's lesson: an escaped byte before it would move the raw
  index); call_home_image(raw, enabled) is write_image's N + 2 image with byte 5
  set and everything else as read, refusing a byte 5 never measured.
- MiniMateClient.read_call_home_raw() / write_call_home_image(image) (0x7E then
  0x7F, each ack checked, never retried).
- Series3Adapter.call_home_state (wake, then 0x2C; no serial read, like status)
  and change_call_home: the shared change core with a connect() identity check,
  state 'enabled' / 'disabled' / 'unknown(0xNN)' (unknown sends nothing), the
  plan showing both exact frames, a snapshot of both unescaped images.
- S3_CALL_HOME_FRAME_VERIFIED = False: a live change is refused (501) before any
  connection until the frame is reproduced from Blastware's (next commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:57:55 -05:00
serversdownandClaude Opus 5.5 eeb55effe9 feat(sfm): Series-4 call-home state and audited enable/disable (phase 4)
- micromate: ENABLEABLE_WRITES gains 0x7E/0x7F (the call-home write and its
  confirm; spec row 9, enable/disable only); MicromateClient.get_call_home_content()
  returns the 126-byte 0x2C content.
- sfm/device_access: CallHomeState (serial, series, enabled, dial_string, detail
  with byte5 and the whole block); s4_call_home_state reads bit 0 of [5] and the
  dial string at [6:46]; s4_change_call_home runs the shared change core with
  micromate.writes.plan_call_home_enabled -- built from the read run_change made
  just before, and that same plan is the one sent.  A unit calling home (run
  state 0x03) is refused, nothing sent.  The read-back judges the edited bit
  only; the snapshot records both blocks and every changed offset -- [118:120]
  is unit-maintained and always moves.
- The write-ceiling tests take 0x71 (the setup write, phase 5) as their
  over-the-ceiling example now that 0x7E is enableable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:56:04 -05:00
serversdownandClaude Opus 5.5 1dd5bfa464 refactor(sfm): run_change takes a ChangeKind -- start/stop unchanged, call-home next (phase 4)
run_change named its change and its target state from a start/stop bool.  A
ChangeKind (action, want, became) now says what the change is called and which
state read back means it took; monitoring_change(start) gives exactly today's
names, call_home_change(enabled) the new ones.  An optional snapshot hook
records what the unit holds after the change in the result and the audit row
(never the verdict; one that raises is recorded as its error).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:53:48 -05:00
serversdownandClaude Opus 5.5 5b37ea22cc docs(plan): phase 4 -- call-home enable/disable by serial, both series
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:47:56 -05:00
serversdownandClaude Opus 5.5 2389b4c4f6 docs: the SFM page's JavaScript lives in sfm/static/ (CLAUDE.md layout)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:22:38 -05:00
serversdownandClaude Opus 5.5 8123d75d72 fix(sfm): page polish from the 1c bench -- #6, #10, #12, #16 (Batch 2)
- #6 Config tab by serial: the empty legacy edit form stays hidden (settings
  are read-only until phase 5); the settings box shows from the start, 'Not read
  yet', and a different unit's settings are never left on screen.
- #10 A start/stop that went out but was not confirmed is no longer called
  'failed'.  The route now adds 'sent' (acknowledged / unknown) and 'audit_id'
  to a ChangeUnconfirmed -- same status, same message -- and the page says
  'Start monitoring not confirmed: <what happened, audit record>'.
- #12 Device tab by serial: the empty legacy Compliance/Project tables are
  hidden behind a pointer to the Config tab; a Micromate's Firmware card reads
  'Thor line (version not read)' (its version string is in 0x01, undecoded).
- #16 A 504 with nothing sent adds: the connection opened, so the modem is
  reachable -- another program (THOR or Blastware) may be holding the line, or
  the unit is busy.  Measured 2026-10-29: THOR polling leaves SFM a 0-byte 504.

New logic lives in sfm/static/device_routing.js (firmwareLabel,
deviceErrorText, changeErrorText, serialPanes) under Node tests; the page glue
in sfm_webapp.js only applies them.  Checked in jsdom against the real page
(served at a fake origin, /static from disk): all four, legacy mode unchanged,
no script errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:22:22 -05:00
serversdownandClaude Opus 5.5 aec4a38473 fix(decode): histograms go to the histogram codec, and a loud interval no longer hides a short one
Three causes behind the histograms the checker found decoding wrongly:

1. The file decoder tried the waveform codec first, whatever the record
   type.  It accepted BE9440 / BE9557 / BE17354's 2018 5 s histograms and
   returned ~5x too many 'samples' (K440HDXX.XH0H: SFM 44,504, Blastware
   6,976).  The codec now follows STRT[18] (0x46 / 0x0A on 70,041 /
   70,041 DL2 files); only an unknown type falls back to trial order, and a
   chosen codec that fails is a decode problem rather than a silent switch.

2. The sub-minute layout check required each record's 'zero word' to be
   0000.  It is the high word of the interval's PVS squared, non-zero above
   1.28 in/s, so a one-block histogram with a loud interval was not
   recognised (T193KR5M.X90H, K440HA3C.JM0H, R352HFZ7.530H decoded to
   nothing).  The check is now the measured relation peak <= PVS <=
   sqrt(3) * peak, which holds on 34,502,955 / 34,502,955 DL2 sub-minute
   intervals.  The no-terminal-tail trim uses the same test.  Two test
   builders wrote PVS bytes no real record has (one still in the retracted
   little-endian layout); they now write peak^2 in the measured layout, and
   the retraction test keeps a legacy builder of its own.

3. Checker carve-out interval-count-is-duration: Blastware's Number of
   Intervals is (stop - start) / interval from the footer times, and its
   own interval table lists one block fewer when the unit never wrote the
   last minute.  SFM matches the table (T193KSWP.FF0H: 2,880 vs 2,850).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 16:20:32 -05:00
serversdownandClaude Opus 5.5 2b886c4f39 refactor(sfm): move the page's JavaScript out of sfm_webapp.html into sfm/static/ (no code change)
Stack-wide rule since 2026-11-02 (terra-view docs/tmi-stack.md, Terra-View's
rule 4): no inline JavaScript, because a test cannot load it.  This page's tests
had to regex their code out of the HTML.  Batch 2 edits both of the page's
scripts, so they come out first, verbatim:

- sfm/static/device_routing.js: the tested routing rules (157 lines)
- sfm/static/sfm_webapp.js: the rest of the page (2,274 lines)

The page loads them with <script src="static/..."> where the inline scripts
were, so load order and the onclick handlers are unchanged.  Verified: putting
the files back inside those tags reproduces the old sfm_webapp.html byte for
byte, and a jsdom page check (served at http://sfm.local/, /static from disk,
no network) gives identical output before and after.

The server serves sfm/static/ at /static/, with Cache-Control: no-cache so a
browser revalidates (a cheap 304) and a new SFM never runs a cached old
script.  Opened from disk, the page needs its static/ folder beside it.

Tests: the routing tests load the file instead of regexing the HTML; new
test_webapp_static pins no inline <script> in the page and the /static route
(through the whole app, middleware included).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 16:17:44 -05:00
serversdownandClaude Opus 5.5 99b6b315d6 docs(changelog): Unreleased -- the job number from the file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 16:09:48 -05:00
serversdownandClaude Opus 5.5 fec59679e6 merge: a Blastware file's job number, and whether Blastware shows it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 16:09:16 -05:00
serversdownandClaude Opus 5.5 7a58bad28d feat(decode): a Blastware file's job number, and whether Blastware shows it
The setup block has Series IV's 0x1A layout here too: report flags at
k - 9 (bit 0x02 = job number shown) and the number, uint16 BE, at k - 8,
kept while switched off.  The flag matches Blastware's JobNumber on
2,997 / 2,997 DL2 events that print one and 66,986 / 66,986 that don't.
Every printed value is 1 and matches; hidden ones hold real numbers
(802, 1012, 1013, 622), so the value is only proven for 1.

- ProjectInfo.job_number_enabled / job_number, named as in
  micromate.setup_block.
- write_event_hdf5 stores both as .h5 attrs when read (additive).
- The checker reports the number only when shown, and scores a number
  only SFM shows as a mismatch.  The old test that pinned JobNumber as
  sfm_blank now checks only the ZC cases it also covered.

Not carried into the DB, the API or the PDF report yet (needs a column).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:31:23 -05:00
serversdownandClaude Opus 5.5 15a27d5921 docs(changelog): Unreleased -- the file's pre-trigger is the event's
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:23:49 -05:00
serversdownandClaude Opus 5.5 a30cf47825 merge: the file's pre-trigger is the event's -- corrects today's #48 note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:23:33 -05:00
serversdownandClaude Opus 5.5 5bed7d6c6f docs: the file's pre-trigger is the event's, not the setting -- corrects today's #48 note
The pre-trigger float in an event file's setup block varies from event
to event on the same unit, often on the same day (BE18193: -0.25 and
-0.248 on 2026-08-21; 253-256 samples at 1024 sps, -0.002 to -0.249 s
at 4096 sps), and Blastware reports the same per-event value as
Pre-triggerLength.  So it is the event's own pre-trigger, and the note
written earlier today overstated what the files say about #48: the live
1A holds the setting, so a missing anchor in a file says little about
whether the live read loses its anchor.  #48 stays open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:23:32 -05:00
serversdownandClaude Opus 5.5 55d74c0a7b docs(changelog): Unreleased -- the event-file fields in the protocol reference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:04:10 -05:00
serversdownandClaude Opus 5.5 9c0b608c38 merge: the event-file fields in the protocol reference (Appendix D.6) and CLAUDE.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:03:58 -05:00
serversdownandClaude Opus 5.5 b6e726f850 docs: the event-file fields SFM reads from the file alone (reference Appendix D.6)
New Appendix D.6 records the bytes and DL2 verification for every field
SFM reads from a Blastware event file: record type STRT[18], the
recording-setup block (sample rate k-42, pre-trigger k-36, record time
k-30, the four notes), the geophone range (label+29), each histogram
interval's PVS^2, and the mic scale (0.25 Pa per count, dB offset
81.9384).  None of these were written down outside code and issues.

Retracted in place:
- D.3.1's STRT[20] = record time: it is 00 on 70,041 / 70,041 DL2 files.
- the 2026-08-26 reading of sub-minute histogram records as little-
  endian: big-endian from byte 5 since v0.32.0 (#47/#49), and the
  '2-word tail' is the PVS^2.  Also in CLAUDE.md.

Measured for #48 (files only): the 1A 'stable anchor' be 80 00 00 00 00
is the setup's pre-trigger -0.25 s plus 00 00.  It is present only on
the 3,886 / 6,541 DL2 waveforms recorded at exactly -0.25 s, and on no
histogram.  The live 1A read is still unmeasured.

CLAUDE.md: Where things stand reflects the range fix on dev (6,524 /
6,524 waveforms exact); the 8x sensitive-range item and the MicL dB
item are marked resolved in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 14:03:47 -05:00
serversdownandClaude Opus 5.5 f98c4ff129 fix(sfm): a MiniMate download stores what its own file says, at the range it was recorded at (#17)
With the decode checker's fixes merged (histogram vector sum 625bc39, mic psi
5644dbd, the file's geophone range 4844135), 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
2026-11-02 13:48:59 -05:00
serversdownandClaude Opus 5.5 d0c14aaec8 merge: dev into feat/series4-sfm-parity -- the geophone range from the file, and v0.33.0
Brings 057df47 (fix 4844135, changelog be58b4f) from the decode checker's branch
-- Event.geo_range from the file's setup channel block (label+29: 0 Normal,
1 Sensitive, None not read), peaks and histogram PVS scaled by it,
write_event_hdf5(geo_range=None) using it -- and dev's v0.33.0 release commit
(6c7c6b0).

Conflicts, resolved as agreed with the decode session:
- sfm/waveform_store.py save_imported_bw: dev dropped the forced
  geo_range="normal"; this branch keeps its geo_range parameter, now
  Optional, default None -- an import uses the file's own range, an explicit
  value (a live download's) still wins.
- CLAUDE.md: dev's newer 'Where things stand (updated 2026-11-01)' date.

Measured on the merged tree: K557J1KB.RQ0W (Sensitive waveform) decodes
0.019 / 0.055 / 0.019, PVS 0.061 -- Blastware's report -- and its imported
.h5 peaks 0.0194 / 0.055 / 0.0194 (forcing 'normal' gives 8x: 0.155 / 0.44).
M010HR6K.OA0H (Sensitive histogram) likewise.  The live path still passes the
unit's 1A range or 'normal' when unread -- unchanged by this merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 12:06:35 -05:00
serversdownandClaude Opus 5.5 be58b4f8f0 docs(changelog): Unreleased -- the geophone range from the file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 12:04:15 -05:00
serversdownandClaude Opus 5.5 057df47460 merge: a Blastware file's geophone range from its setup -- Sensitive events no longer 8x
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 12:03:41 -05:00
serversdownandClaude Opus 5.5 4844135f01 fix(decode): a Blastware file's geophone range comes from its setup -- Sensitive events no longer read 8x
In the setup's channel blocks, the byte 29 after each geophone label is
the range: 0x00 Normal (10 in/s), 0x01 Sensitive (1.25 in/s).  It matches
Blastware's GeoRange on 70,042 / 70,042 DL2 events, all three channels
agreeing on every one (35 Sensitive).  SFM's live 1A has the same byte
at label+33.  SFM assumed Normal, so every Sensitive event's peaks,
vector sum and .h5 samples read 8x high.

- Event.geo_range (0 / 1, None when not read -- channels disagreeing,
  an unknown value or a missing block -- with a decode_problems entry).
- decode_blastware_bytes scales peaks and the histogram vector sum by it.
- event_hdf5.write_event_hdf5: geo_range defaults to None = the event's
  own, else Normal; an explicit argument still wins.
- waveform_store.save_imported_bw and scripts/backfill_sidecars.py stop
  forcing 'normal', so imports and the backfill store the file's range.
  The waveform_store line was agreed with the parity session, which owns
  that file; its own branch keeps a geo_range parameter, defaulting to
  None at its next dev merge.
- The checker's SFM side converts at the event's range and reports
  GeoRange; tests that pinned the old 8x gap now pin the fix, and the
  saturation carve-out is still tested against an 8x value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-01 16:26:15 -05:00
serversdownandClaude Opus 5.5 6c7c6b0a15 chore(release): v0.33.0 — SFM reads Series-3 events from the file alone, and proves it
A Blastware event that reaches SFM without its ASCII report -- every DL2
event before 2025, and every event SFM downloads itself -- now carries
its sample rate, record time, pre-trigger, notes and event type, the
histogram vector sum the unit stores, and a mic reading at one count =
0.25 Pa.  The new decode checker proves each against Blastware's own
_XML.XML reports for 70,042 DL2 events.

- CHANGELOG: Unreleased -> v0.33.0 with theme and Migration.
- TOOL_VERSION 0.33.0 (gates the backfill regeneration).
- pyproject, CLAUDE.md and README versions; README status entry and
  roadmap (the Series-III codec item was long done; the file-only goal
  added); CLAUDE.md 'Where things stand' brought up to v0.33.0.

Deploy: back up seismo_relay.db, then backfill_sidecars.py and
backfill_event_shape.py (~2 h on the NAS).  No schema change, no
migration, event times do not move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-01 14:20:15 -05:00
serversdownandClaude Opus 5.5 1141a15543 merge: dev into feat/series4-sfm-parity -- one MicL count is 0.25 Pa
Brings 30a249e (fixes 5644dbd + 1895150, changelog 287ef2a) from the decode
checker's branch: the file's mic psi was ~95x low (_MIC_PSI_PER_COUNT =
0.25 Pa / count), and Blastware's dB offset is 81.9384.  K441LTON.900's mic
reads ~5.80e-4 psi from the file, as Blastware's 106.0 dB(L).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-31 02:20:32 -04:00
serversdownandClaude Opus 5.5 287ef2a653 docs(changelog): Unreleased -- one MicL count is 0.25 Pa
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-31 02:19:49 -04:00
serversdownandClaude Opus 5.5 30a249ef57 merge: one MicL count is 0.25 Pa; Blastware's dB offset 81.9384
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-31 02:19:17 -04:00
serversdownandClaude Opus 5.5 18951505f0 fix(decode): Blastware's mic dB offset is 81.9384, a hair above exact 0.25 Pa
The checker caught 280 regressions in the first mic fix: every one a dB
value at count 129, where 20 log10(129 x 0.25 Pa / 20 uPa) = 124.149997
rounds to 124.1 and Blastware prints 124.2.  Blastware's dB offset sits in
[81.9383, 81.9385] -- any value there matches its dB(L) on 1,729,252 /
1,729,253 DL2 intervals (the last printed '0.000'); exact 81.93820 rounds
count 129 down, and the old 81.94 misses counts 119 and 132.  Single
precision does not explain it.  psi keeps 0.25 Pa per count, which
matches every interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-31 01:55:45 -04:00
serversdownandClaude Opus 5.5 5644dbd5ad fix(decode): one MicL count is 0.25 Pa -- the mic psi was ~95x low
SFM converted mic counts to psi with a '~0.5 psi full-scale' guess
(0.0125 / 32768 psi per count).  Measured against 1,729,253 DL2
histogram intervals' 'MicL Peak' columns: one count is exactly 0.25 Pa.
count x 0.25 Pa matches Blastware's psi(L) on every interval, and
20 log10(count x 0.25 Pa / 20 uPa) its dB(L) on all but 17 exact
half-way cases.

- event_file_io: _MIC_FS_PSI -> _MIC_PSI_PER_COUNT = 0.25 / 6894.757
  (3.626e-5 psi per count, was 3.81e-7).  The event's mic peak in psi,
  and with it the .h5 mic trace (event_hdf5 back-solves its scale from
  that peak), come right on events with no report.
- waveform_codec.mic_count_to_db: the offset is 20 log10(0.25 / 20e-6)
  = 81.938, not 81.94 -- the old value missed 49 of those intervals at a
  rounding edge (count 119 printed 123.4, 81.94 gave 123.451).

The decoded count was always right: count 16 on K441LTON.900 is
Blastware's 106.0 dB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-31 01:28:23 -04:00
serversdownandClaude Opus 5.5 0a87d85202 fix(sfm): a MiniMate download's peaks come from its file when the unit confirms Normal range
Since the decode checker's histogram-PVS fix (625bc39, merged 6945009) the file
reads a histogram's vector sum as the unit stored it: K441LTON.900 stores
0.200 / 0.385 / 0.255 and a vector sum of 0.3852, as Blastware's report (was
0.503).  The 0C summary, read at fixed offsets, can shift (BE9441 read 0 and
-0.0, bench #4) -- and a shifted value can look plausible and pass the
impossible-value guard.  So the row now takes the file's channel peaks and
vector sum.

Only when the unit's settings confirm Normal range: the file reader computes
every peak as if the range were Normal (_GEO_SENSITIVE_FS_INS is defined but
unused), so a Sensitive unit's file peaks are 8x off (the checker's 33
waveforms).  For Sensitive, or a range not read (a monitoring unit's 1A has no
settings), the unit's own peaks stand, as before.  The mic is always the
unit's: the file still reads it as 0.  The 0C peaks remain the download check.

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
2026-10-31 00:17:57 -04:00
serversdownandClaude Opus 5.5 69450093f6 merge: dev into feat/series4-sfm-parity -- a histogram's peak vector sum from the unit's stored value
Brings 0fc6806 (fix 625bc39, changelog dc42ae0) from the decode checker's
branch: a histogram's peak vector sum is the largest per-interval PVS the unit
stores (PVS^2 as uint32 BE), not a vector magnitude of per-channel interval
peaks.  K441LTON.900 reads 0.385, as Blastware's report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-31 00:13:15 -04:00
serversdownandClaude Opus 5.5 dc42ae041a docs(changelog): Unreleased -- a histogram's stored peak vector sum
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-30 01:54:27 -04:00
serversdownandClaude Opus 5.5 0fc68065fe merge: a histogram's peak vector sum from the stored per-interval value
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-30 01:53:54 -04:00
serversdownandClaude Opus 5.5 625bc39116 fix(decode): a histogram's peak vector sum is the one the unit stores
Every histogram interval carries its peak vector sum SQUARED, uint32 BE
in 0.005 in/s units: bytes [21:25] of a standard block (long documented
as 'constant 00 00' plus 'purpose unknown'), the last 4 bytes of a
sub-minute record (the undecoded 'meta_var').  sqrt(stored) x 0.005 is
the Geo PVS Blastware prints: 1,668,073 / 1,668,074 standard and 34.5 M
sub-minute DL2 intervals checked against the _XML.XML reports.

SFM computed the event's PVS from each channel's interval peak, which
can come from different moments, and read high on 86% of DL2's
histograms (T004JTRF.ME0H: 1.782 against Blastware's 1.358).  It now
takes the largest stored interval value.  histogram_codec.interval_pvs
returns the per-interval series; records gain 'pvs_sq'.  Waveforms are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-30 01:29:58 -04:00
serversdownandClaude Opus 5.5 b6ed5f5bd5 feat(sfm): SFM's MiniMate files carry the W/H type letter Blastware's direct downloads leave off
Blastware names a direct download K441LTON.900 and only its call-in copy
K441LTON.900H, so a folder of directly downloaded events cannot be sorted by
kind.  SFM's own files now always carry the letter.  It is read from the file's
own record-type byte (STRT[18], #41) by the new with_type_letter() -- not from
the recording mode: BE9441's K441LTOK.R10 is a waveform that triggered 2 s into
histogram K441LTOK.QZ0 (Histogram+Continuous).  A file whose type does not read
keeps the plain name; a name never fails a download.

All three paths that name a MiniMate file SFM builds: the device-access
download (the page's event list), WaveformStore.save (the legacy route's store
copy, the bench call-in server), and the legacy /device/event/{i}/blastware_file
download.  Verified on BE9441's recorded 5A walk: 0111f210 -> K441LTON.900H,
011106a0 -> K441LTOK.R10W, byte-identical to Blastware's files.

find_event_by_blastware_name tightens with it: a lettered name matches itself
and the letterless form, not the other letter (a waveform and a histogram in the
same second are different events); a letterless name still matches all three.

Store consequence: new downloads only; rows and files stored before keep their
names, and 'already stored' still finds them.  No schema change, no migration.
The event list shows the plain name until the event is downloaded (the type is
not known before the 5A).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-30 00:36:26 -04:00
serversdownandClaude Opus 5.5 50a0501147 test(sfm): a live MiniMate histogram is labelled Histogram (#8, via #41)
K441LTON.900 -- a direct download's name, with no type letter -- read
'Waveform' before #41 came in with a1d2b61 (verified failing first), and
'Histogram' from STRT[18] after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:58:52 -04:00
serversdownandClaude Opus 5.5 a1d2b61f22 merge: dev into feat/series4-sfm-parity -- #41, a Blastware event's record type from its bytes
Brings ede6292 (fix 46daea1, changelog b6fc71b) from the decode checker's
branch.  Completes #8's live S3 download path: a live histogram, whose direct
download name (K441LTON.900) carries no type letter, is now labelled from
STRT[18] instead of defaulting to Waveform.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:57:41 -04:00
serversdownandClaude Opus 5.5 1cce2fcf63 docs: Batch 1 final-review fixes -- reconnect wake, dedup by name, the write encoder's refusal
- Spec: #1, #8, #9 carry their review follow-ups (a72d3a9, 3a1d34a, dbd8a91);
  new open finding 17 (a monitoring MiniMate's 1A has no range, so a download
  then stores Normal-scaled samples; ':S338.17' setup name; no .a5.pkl kept).
- Series-III reference (CRLF kept): the 2026-10-29 row records that the write
  encoder was not moved and now refuses a patch that would not read back.
- CLAUDE.md: the three fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:57:13 -04:00
serversdownandClaude Opus 5.5 a72d3a98a9 fix(minimateplus): refuse a settings write whose four fields would not read back as asked (#1 review)
_encode_compliance_config patches the raw SUB 1A bytes at offsets measured at
1024 sps (April 2026), where the escape before 04 sits between the mode and the
anchor.  b320a53 moved the decoder to the measured layout (unescaped: mode -7,
rate -6, interval -4, record time +6), which exposed the encoder: on BE9441's
recorded 10-25 Continuous / 4096 block a mode change rewrote the byte in front
of the mode, and on the 10-26 Histogram+Continuous / 2048 block a sample-rate
change landed one byte off.  The old decoder read the same wrong bytes, so such
a write looked as if it had taken.

The encoder now decodes its own result with the decoder and raises ValueError
when mode, sample rate, interval or record time would not read back as asked
(or a field not asked for would change) -- before push_config_raw sends a byte.
No write offset is moved: rewriting the encoder on unescaped bytes is #46's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:56:44 -04:00
serversdownandClaude Opus 5.5 3a1d34ae92 fix(sfm): a download the store already holds is found by its Blastware name, not only its time (#8 review)
persist_download checked 'already stored' on the unit's 0C time only, but a
histogram's row is stored at its file's time, a second earlier on most
histograms (#51): K441LTOK.QZ0 decodes to 16:06:34, its 0C says 16:06:35.  So a
live download of an event the watcher had imported missed the check and
re-stored it -- UPSERTing over the watcher's row (Blastware's ZC frequencies and
vector sum lost) and rewriting its sidecar as sfm-live -- and every repeat live
download rewrote the files again.

New SeismoDb.find_event_by_blastware_name(): the row stored under the same
Blastware name (the event's second, per blastware_filename_time; the rule
_restamp_by_file uses), matching a direct name to the call-in copy's W/H name.
Any other name matches nothing.  Also two comments from 9492e49 that said the
opposite of the code (the unit's peaks are overlaid; source.kind is a parameter).

Store consequence: none for existing rows; no schema change, no migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:56:44 -04:00
serversdownandClaude Opus 5.5 dbd8a91661 fix(sfm): wake a MiniMate before the read-back reconnect reads its serial (#9 review)
The reconnect in ce441a0 opened a fresh connection and sent a bare 0x15 (the
identity check) before any SESSION_RESET + POLL.  It exists for a unit that has
just started -- sensor check, then monitoring -- and a monitoring MiniMate
ignores a bare request until woken (measured 2026-04-08), so the identity read
would have timed out and the start reported unconfirmed anyway.  Now: open,
wake (the same retried wake the read-back uses), read the serial, read 0x1C --
the order the status read and the legacy write routes use.  Still one
reconnect, TCP only, nothing re-sent.

The fake gains bare_requests_ignored (off unless a test asks): a fresh
connection's reads time out, with the real client's TimeoutError, until woken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:56:44 -04:00
serversdownandClaude Opus 5.5 b6fc71bd28 docs(changelog): Unreleased -- record type from the bytes (#41)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 23:32:32 -04:00
serversdownandClaude Opus 5.5 ede6292e4d merge: a Blastware event's record type from its bytes (#41)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 23:31:53 -04:00
serversdownandClaude Opus 5.5 1626e521ae docs: 1c bench Batch 1 -- #1, #8, #9 fixed; #15 retracted; the 1A layout after unescaping
- Spec (Left open by the 1c bench): #1 b320a53, #8 9492e49, #9 ce441a0, #2 via the
  dev merge 342c696; #15 retracted in place (sent NULL = unknown, by design).
- Series-III reference: a 2026-10-29 row -- the SUB 1A settings fields read after
  unescaping (mode -7, rate -6, interval -4, record time +6), the old
  'anchor-7 constant 0x10' was the escape before 04 at 1024 sps, the channel
  block stays on raw bytes (open: a float containing an escapable byte), and a
  monitoring BE9441 answers 1A with its device-info block.  CRLF kept.
- CLAUDE.md: Batch 1 status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:28:39 -04:00
serversdownandClaude Opus 5.5 9492e49400 fix(sfm): store a MiniMate download through the Blastware-file import path, as production does (#8)
A live Series-3 download was stored from the live 5A decode (store.save): a
histogram got no samples and nothing to plot (bench 2026-10-29).  The download
now carries the assembled Blastware file (DownloadedEvent.bw_bytes, built by the
new blastware_file_bytes -- byte-identical to Blastware's own K441LTON.900 and
K441LTOK.R10), and persist_download stores it through save_imported_bw, the
path the watcher uses for Blastware's files, the way Series 4 already uses
save_imported_idf.  The event is decoded from the file: histogram samples,
setup-block sample rate and record time (#44/#45).  source.kind is 'sfm-live'.

The file path does not yet read three things right (measured on BE9441): a
histogram's vector sum (0.503 where Blastware and the unit say 0.385 -- the
decode checker's open finding), the mic peak (0), and a sensitive range.  So the
unit's own 0C channel peaks, mic and vector sum are overlaid, as Series 4 does,
except an impossible vector sum (below the largest channel; BE9441's 0C read
-0.0, bench #4), and the unit's range is passed through for the stored samples.

Store consequence: new live MiniMate downloads only; existing rows and files are
untouched; no backfill, no migration.  The record type still reads 'Waveform'
for a live histogram until #41 (record type from STRT[18]) lands from the decode
checker's branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:27:44 -04:00
serversdownandClaude Opus 5.5 ce441a0911 fix(sfm): a MiniMate start's read-back reconnects once when the modem dropped the line (#9)
BE9441 over a modem, 2026-10-29: the start was acked, but the modem closed the
line during the ~30 s sensor check, so the read-back's first wake hit
'[Errno 32] Broken pipe' and the change was reported 503 'not checked' although
the unit was monitoring.  On an OSError in the read-back, a TCP unit is now
reconnected once, its serial checked against the named unit, and its state read.
Nothing is re-sent: the start still goes out exactly once.  A serial cable is
never reconnected (opening a MiniMate's port reboots it), a second failure or a
silence (a cleanly closed line) ends 'not checked' as before, and a different
unit after the reconnect is refused (409, change unconfirmed).

Store consequence: none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:21:27 -04:00
serversdownandClaude Opus 5.5 b320a534bc fix(minimateplus): read a MiniMate's mode, sample rate, interval and record time after removing escapes (#1)
The unit escapes 02/03/04/10 in every reply and S3FrameParser keeps the 10 of
10 02/03/04, so on the raw SUB 1A bytes an escaped mode, rate or interval
shifted every field after it: BE9441 at Histogram / 4096 sps / 2 s read back as
0 sps and a 4098 s interval (bench 2026-10-29), and a Continuous unit read as
Single Shot.  The four anchor fields are now read from unescape_reply(data):
mode anchor-7, sample rate anchor-6, interval anchor-4, record time anchor+6 --
measured on all four distinct recorded replies, two of them Blastware's own
writes (15 min, then 2 s).  The old 'anchor-7 = constant 0x10' was the escape
before 04 at 1024 sps.

The channel block and strings still read the raw bytes: their label offsets were
measured there and are wrong unescaped (pinned by a test).  A reply with no
anchor -- BE9441's monitoring-time 1A answer was its device-info block -- leaves
all four None.

Store consequence: none; this is the live settings read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:19:11 -04:00
serversdownandClaude Opus 5.5 0dbd0b506d docs(plan): 1c bench fixes, Batch 1 -- #1 settings decode, #9 read-back reconnect, #8 downloads via the file import path; #15 retracted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:08:56 -04:00
serversdownandClaude Opus 5.5 46daea17b2 fix(decode): a Blastware event's record type comes from its bytes, not its filename (#41)
STRT[18] is the record-type byte: 0x46 on every one of DL2's 6,577
waveform files, 0x0A on every one of its 63,535 histograms.  The decoder
read the type from the filename's last letter, so an event with no
Blastware name -- SFM's own downloads, the call-in path -- or a manual
download ('.QZ0') came out 'Waveform' whatever it was.

The filename is now a cross-check that logs a disagreement; the bytes
win.  An unknown byte (Manual / Event / Combo never occur in DL2) is
record_type None with a decode_problems entry, not a guess.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 23:06:25 -04:00
serversdownandClaude Opus 5.5 342c69602d merge: dev into feat/series4-sfm-parity -- v0.32.0, #42, #47/#49, #44/#45, the S3 decode checker
Brings the branch up to dev (41 commits) before the 1c bench fixes, which
touch code dev changed: the histogram reader (#47/#49, bench finding #2), the
v0.32.0 event-time rules, the Blastware file's setup-block fields (#44/#45),
and the decode checker for verifying stored S3 downloads.

One conflict: the top of the Series-III reference's change table -- both sides
added rows; kept all, in date order, CRLF preserved.  CLAUDE.md, README,
blastware_file.py, models.py and database.py merged cleanly.  Suite: the known
16 failures only (15 test_bw_ascii_report, test_save_imported_bw_without_report_
works_unchanged, which also fails on dev); 1237 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 22:51:42 -04:00
serversdownandClaude Opus 5.5 b92c8e489e docs(changelog): Unreleased -- the Series 3 decode checker, and the corrected #53 note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 22:46:08 -04:00
serversdownandClaude Opus 5.5 fed6489330 merge: the Series 3 decode checker -- SFM's file-only decode against Blastware's XML reports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 22:45:24 -04:00
serversdownandClaude Opus 5.5 c0d837c14f fix(checker): final-review fixes -- regressions, baselines, the PVS carve-out, the headline
- A matching event that now fails outright is a regression: compare_runs
  walks the previous run's matching rows, so a check that collapses to
  one error row no longer hides every field it used to match.  Counts
  moved are taken over the events both runs checked.
- The default baseline is the newest completed run (run.json written) of
  the same scope; a 2,000-event sample is no baseline for a full run.
  changes.md names the previous run's scope.
- The PVS saturation carve-out now needs Blastware's OORANGE, a channel
  Blastware clamped at SFM's ceiling, and SFM's sum within three channels
  at the ceiling -- an unclipped Sensitive-range channel read 8x can no
  longer let an 8x sum through.
- 'Fields fully matching' needs a match: an always-empty element proves
  nothing.  Events without a report are a line of their own.
- CLAUDE.md: histogram PVS described correctly; 35 sub-minute histograms
  plus 2 one-minute no-mic ones, not '~37 sub-minute'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 20:11:33 -04:00
serversdownandClaude Opus 5.5 e9d352ad99 docs: the decode checker's first full run; correct the #53 note
First full run over DL2's 70,042 report-paired events (22 min, --jobs 4):
every expectation the spec set holds.  Setup and notes match everywhere;
geophone samples are exact on 6,491/6,524 waveforms across 2016-2026,
the other 33 being the 1.250 in/s range read 8x on SFM's Normal
assumption; every histogram is typed as a waveform without its filename
(#41); the three #53 files are the only waveform time mismatches.  New
findings: histogram PVS, mic psi, mic dB on ~1,000 events, ~37
sub-minute histograms, 26 histogram start dates.

The #53 note is corrected in place: those files decode as waveforms with
Blastware's full sample count; only their time falls back to the footer
start.  scratch/verify_bw_fields_against_xml.py is retired -- the
checker replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:55:07 -04:00
serversdownandClaude Opus 5.5 c8fc649568 tooling(scratch): decode-check run-to-run changes and a one-event view
Each run is diffed against the previous one (--compare-to, or the newest
other run in ~/dl2-archive/checker-runs): changes.md lists every
(event, field) that matched before and no longer does, how many now
match, and how each field's counts moved; summary.md leads with the
regression count.  --file NAME checks one event and prints its table,
writing no run folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:30:53 -04:00
serversdownandClaude Opus 5.5 5e85cf1018 tooling(scratch): decode-check summary and grouped detail report
summary.md for Brian: per field, events per verdict, how many fields
fully match, non-matches by event year, carve-out counts.  details.json
for Claude: each non-matching (field, verdict) with the attribute values
its failures concentrate in (>= 10% of the failures; concentrated at
>= 95% of compared events) and example events, each with a one-event
re-run command.  On a 2,000-event sample the event-type mismatches group
as 'type = Full Histogram, 1815/1815' -- #41, named by the report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:30:00 -04:00
serversdownandClaude Opus 5.5 5b48be3f25 tooling(scratch): run the decode check over the archive in parallel
check_s3_decode.py pairs each Series 3 event file with its _XML.XML
report (deduped by basename -- Sent/ mirrors the root), checks each in a
process pool, and writes results.jsonl.gz and run.json to a run folder
outside the repo.  A missing report or any failure is one row for that
event; the run goes on.  Partial runs by serial, year, type, field
prefix or random sample.

Timing: --sample 2000 --jobs 4 took 35 s on tmi-dev (~20 min projected
for all 70,042).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:28:50 -04:00
serversdownandClaude Opus 5.5 ff7dd908a7 feat(codec): carve-outs for proven Blastware differences -- saturation first
A mismatch becomes 'accepted' only through a written carve-out whose
evidence does not rest on SFM's output.  Saturation: Blastware clamps a
clipped channel to the range maximum and prints OORANGE, while the file
holds counts past full scale.  SFM's value must sit at the ceiling
(r - 0.0006 .. r * 1.01), so a Sensitive-range event read 8x high on
SFM's Normal assumption stays a mismatch; a vector sum is accepted when
a clipped channel under it is at the ceiling.  series_pairs() is now the
one place waveform rows and interval columns are paired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:27:01 -04:00
serversdownandClaude Opus 5.5 3662d2fac1 feat(codec): compare SFM's file-only decode with Blastware's XML, field by field
Every field the report carries (bar its format version and Blastware's
file name), the notes in order, the job number, the channel list, every
waveform sample and every histogram interval column.  Numbers match at
Blastware's printed precision, halves rounding away from zero; N/A and
empty text are no_reference; >100 needs SFM's above-range flag; OORANGE
is a mismatch unless a carve-out says otherwise.  Waveform rows pair
cells with the channels still running, so channels that end early
(T438HGTZ.B30W) match, and any row-length disagreement is counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:26:00 -04:00
serversdownandClaude Opus 5.5 3e69a2acdd feat(codec): SFM's side of the decode check, from the event bytes alone
decode_blastware_bytes with no filename and no report: the values SFM
produces today in Blastware's field names, its notes, channels and raw
counts, with its Normal-range assumption kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:24:31 -04:00
serversdownandClaude Opus 5.5 52809a5310 feat(codec): parse Blastware's _XML.XML event report
The reference for the Series 3 decode checker: scalars and value units,
channels, the job number, the user notes in order under their
operator-edited labels, waveform rows as printed (ragged where channels
end at different lengths) and histogram intervals.  Seven real DL2
events as fixtures, each covering a case the comparison must handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:23:43 -04:00
serversdownandClaude Opus 5.5 b023083c79 docs(changelog): T438HGTZ.B30W is not a decoder truncation
Its Tran, Vert and MicL end 3 samples before Long in Blastware's own XML
sample table as well; the setup-field harness compared Tran's length with
the table's row count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 18:30:27 -04:00
serversdownandClaude Opus 5.5 6bdd140c29 docs(plan): the Series 3 decode checker, task by task -- and T438HGTZ is not truncated
Eight tasks: the XML report parser, SFM's side from the bytes alone, the
field-by-field comparison, carve-outs (saturation first), the parallel
runner, the summary and grouped detail report, run-to-run changes with a
one-event view, and the first full run checked against what is known.

While pinning the plan's test values on real files: T438HGTZ.B30W, called
"3 samples short" by the setup-field harness, matches Blastware exactly.
Its Tran, Vert and MicL end 3 samples before Long, and Blastware's own
sample table does the same -- its last three rows carry only the Long cell.
The harness compared Tran's length with the table's row count.  The spec
now says so, and the plan compares samples row by row by running channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 18:30:08 -04:00
serversdownandClaude Opus 5.5 af703808db docs(spec): the Series 3 decode checker -- SFM's file-only decode against Blastware's XML reports
The first of four pieces toward SFM producing everything Blastware reports
from the event file alone: compare every field, sample and histogram
interval with DL2's 70,042 _XML.XML reports (2016-2026), report what
matches, what doesn't and what SFM can't produce yet, grouped for
diagnosis, run after run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 17:47:34 -04:00
serversdownandClaude Opus 5.5 29c8e2b034 docs(changelog): Unreleased — Blastware file-only setup and notes (#44, #45), the XML checker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 17:30:45 -04:00
serversdownandClaude Opus 5.5 42fe35f3b3 merge: a Blastware file's setup and notes from its recording-setup block (#44, #45)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 17:30:31 -04:00
serversdownandClaude Opus 5.5 6def0d1f41 docs: park the event importer; DL2's XML reports reach back to 2016, its ASCII pairs only to 2025
- README roadmap, Ingestion gaps: a bulk importer for event files on disk,
  parked -- one of the four ways events should reach SFM.
- CLAUDE.md: the 14,338 ASCII pairs were described as "back to 2018"; they
  are all 2025-26 events.  Corrected in place.  DL2's Sent/ _XML.XML files
  are Blastware's full event reports, samples included, for 70,042 events
  back to 2016 -- the reference for proving SFM's file-only decode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 17:21:26 -04:00
serversdownandClaude Opus 5.5 f46afafdb4 tooling(scratch): check file-only setup and note fields against Blastware's XML reports
verify_bw_fields_against_xml.py decodes each Blastware event file the way
ingest does, without a report, and compares sample rate, record time,
pre-trigger, sample count, the four notes and the job number with the
event's _XML.XML report -- Blastware's full event report, which DL2 kept
for 70,042 events back to 2016 (ASCII reports exist only for 2025-26).
Every disagreement counts against SFM; there is no carve-out list yet.
The first piece of the decode checker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 17:20:47 -04:00
serversdownandClaude Opus 5.5 b4706a30f0 fix(decode): a Blastware file's setup and notes come from its recording-setup block (#44, #45)
Without a paired ASCII report, a Blastware import stored no sample rate,
the record-type byte as its record time (every waveform read "70 s"), a
pre-trigger and sample count read from STRT bytes that are neither, and
blank notes (the reader stopped at the NUL after each label).

- The recording-setup block is found by structure -- 1c 08, the setup
  name, NUL -- not by the name "Standard Recording Setup", which 37% of
  DL2's files do not use.  One match in each of 70,041 archive files.
- Sample rate (uint16 BE, name-42), pre-trigger (f32 BE, name-36) and
  record time (f32 BE, name-30).  A waveform's sample count is the
  decoded count.  A histogram gets a sample rate only: Blastware reports
  neither a record time nor a pre-trigger for one.
- The setup name and the four user notes by position, as bw_ascii_report
  reads them: the labels are operator-editable ("Seis. Loc:",
  "Location:", "Project: ").
- STRT now yields only the waveform key.

Verified against Blastware's own _XML.XML event reports for the 70,042
DL2 archive events that have one (2016-2026): sample rate 70,042/70,042,
record time 6,524/6,524, pre-trigger 6,484/6,484, notes 70,042/70,042,
sample count 6,523/6,524 (one waveform the decoder ends 3 samples short;
separate).  Events imported with an ASCII report are unchanged -- the
report still overlays.

Not changed: the waveform-time estimate still finds the record time by
the marker; moving it would add a validation constraint for 37% of files
and is to be measured first.  The job number is not read yet (2,997
archive events carry one).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 17:20:39 -04:00
serversdown a8c91809a6 chore(git): ignore symlinked example-events directory 2026-10-29 15:49:37 -04:00
serversdownandClaude Opus 5.5 184a03a5cd docs(changelog): Unreleased — tier model superseded by Terra-View ADR 0003
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 18:50:02 -04:00
serversdownandClaude Opus 5.5 560869ed61 merge: the SFM/SDM tier model marked superseded by Terra-View ADR 0003
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 18:50:02 -04:00
serversdownandClaude Opus 5.5 b69ff4171d docs(claude): mark the SFM/SDM tier model superseded by Terra-View ADR 0003
SFM is the whole seismograph module and "SDM" is retired; the codec
library stays pure; lab tools leave the production image and are ported
into sfm/ when they become production tools; the call-in server becomes
SFM's front door; the repo becomes `sfm` after the parity branch merges.
The old section stays in place below the banner as history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 15:04:02 -04:00
serversdownandClaude Opus 5.5 1aa07e75d9 docs(release): v0.32.0 README status and dedup notes, release date, TOOL_VERSION comment
README: the intro no longer calls the Series-IV binary codec 'on the roadmap';
a v0.32.0 status entry; the ingest and Database sections describe the restamp
and estimate rules; the NULL-timestamp roadmap item points at #52.
CHANGELOG: v0.32.0 dated 2026-10-27, when its content was final.
TOOL_VERSION comment: times come from the event record, not the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 02:32:25 -04:00
serversdownandClaude Opus 5.5 04acb99310 docs(changelog): v0.32.0 — waveform times from the instrument's event record, estimates never merge
The release had not shipped, so its entries are corrected in place: the theme,
the time-source entry (the embedded event record, not the filename), the
estimate guard, and a note that the deploy rehearsal stands (record and filename
agree on all 1,394 prod waveforms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:18:59 -04:00
serversdownandClaude Opus 5.5 3a6df9d7f4 merge: Series-3 waveform times from the instrument's embedded event record
Brings fix/waveform-time-from-record (f91949b, 6cfcd04, and a docs pointer): the
trigger comes from the event record the unit sends in its 5A stream, validated
strictly; a filename is only a cross-check; no validated record means a
flagged estimate that never overwrites, merges or duplicates a row.  Real data,
no names: 7,961/7,961 waveforms on the record, 0 disagreements.  Suite vs dev:
the same 16 failures, byte-identical reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:18:08 -04:00
serversdownandClaude Opus 5.5 7100d8344a docs(reference): point §7.8.9's open items at the Series-III audit, #53
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:17:15 -04:00
serversdownandClaude Opus 5.5 6cfcd04513 fix(sfm): an estimated event time never overwrites, merges into or duplicates a row
Brian: keep an event whose time is only an estimate (no validated embedded
event record) -- never discard a measurement for want of an exact timestamp --
but it must not silently cause an overwrite, merge or dedup collision.

insert_events, for timestamp_source 'estimate' (_estimate_guard):
- never restamps (moves) a row;
- if its file (a Blastware name) is already stored under another time, writes
  nothing -- no second row, the stored time kept;
- if a different event already holds that second, writes nothing -- the old
  upsert would have written this event over that one;
- otherwise stores it, or refreshes its own row at the same second, as before.
Each refusal is a WARNING naming both sides; the file and sidecar (which says
'estimate' and carries the decode problem) are already in the store.  A generic
upload name ('imported.bw') is not taken as identity.

Tests: each rule, an estimate on a free second kept, generic names, and an
import end to end (a corrupted record next to a different event's second).
3 mutants, each caught.  Suite vs clean origin/dev: the same 16 failing tests,
failure reasons byte-identical; 582 passed vs 553.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:15:32 -04:00
serversdownandClaude Opus 5.5 f91949be89 fix(decode): a Series-3 waveform's time comes from the instrument's embedded event record
Brian's requirements: the instrument's data is the only time source; a filename
is a cross-check, never a fallback (an event SFM receives itself has none).

The record (found by reading a seismo_lab Inspector dump; Series-III reference
§7.8.9): 00 28 05 00 ?? ?? | fe 80 | trigger | stop, times dd mm yyyy(BE) 00 hh
mm ss.  Measured on 7,935 waveforms (DL2 + prod store): exactly one candidate
validates in every file; trigger = Blastware's report 1,320/1,320, = filename
7,935/7,935, = the unit's 0C record 10/10.

Provenance (requirement 6, measured): in Blastware's download of 8 BE9441
events the record -- with 24 B before and 22 after -- occurs exactly once in the
unit's own A5 reply payloads; SFM-only downloads (no Blastware) carry it too.
It is instrument data, not Blastware's.

- _embedded_event_record(): every fe 80 before the footer is a candidate; it
  counts only with the lead bytes, two well-formed times (zero byte zero),
  footer ts1 <= trigger <= stop, stop = footer ts2 or a second before, and a
  length matching the record time.  Exactly one must count; none or several is
  a decode problem, never a guess.
- Without one: the footer estimate, timestamp_source 'estimate', a
  decode_problems entry, a WARNING.  No filename fallback.
- A filename that disagrees is logged; the decoded time is kept.  A paired
  report fills in only without a validated record (apply_report_to_event, the
  sidecar dict overlay, event_to_sidecar_dict) and is logged when it disagrees.
- decode_blastware_bytes(raw, name=None): no file or name needed;
  save_imported_bw uses it (no temp file).  Event gains timestamp_source and
  decode_problems; the sidecar records both.
- Histograms unchanged (#51): their record (fe f5) is noted, not used.

Tests: raw bytes with no name (ZI0, 7 BE12844 oracles), a disagreeing name, each
validation rule alone, two valid candidates, no filename fallback, report
precedence, sidecar.  7 mutants, each caught.  Real data, decoded with no name:
7,961/7,961 waveforms on the record, 0 disagreements with filename or report;
10,433/10,433 prod histograms unchanged.  Suite: only the 16 known failures.

Open (reported, not changed): 3 DL2 files named as waveforms whose body the
waveform codec does not recognise keep the footer start, 4 s off, as on dev.
None in prod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 23:59:22 -04:00
serversdownandClaude Opus 5.5 895ce4917e chore(release): v0.32.0 — event times you can trust, and Series 4 mapped
Series-3 waveform times carry Blastware's own (from the filename), re-stored
events move their rows instead of duplicating, prod's ISO-dated reports are
read, mic-off / mic-on sub-minute histograms decode right (#47, #49), Micromate
.h5 samples are on Thor's own scale (#42).  Plus the Series-4 live protocol,
read-only client and setup decode (no shipped code path yet) and the SFM
Diagnostics tab.

TOOL_VERSION 0.31.0 -> 0.32.0: the deploy owes backfill_sidecars.py --force
--reparse-txt, backfill_thor_events.py, backfill_event_shape.py (~2 h on the
NAS), rehearsed on prod's 2026-09-30 store snapshot -- see Migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 19:32:19 -04:00
serversdownandClaude Opus 5.5 4058dec641 docs(changelog): waveform times from the Blastware filename, restamp in place, ISO report dates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 19:30:28 -04:00
serversdownandClaude Opus 5.5 5737168173 merge: Series-3 waveform times from the Blastware filename; a corrected time moves its row instead of duplicating it
Brings fix/waveform-time-restamp (847900b, abb671a, 3948dc1): insert_events
restamps a re-stored event's row by its Blastware filename; a paired report's
ISO-dated event time is read and survives a backfill; a waveform's time comes
from its filename.  Deploy rehearsal on prod's 2026-09-30 snapshot (11,827
files): waveforms 1,016 -> 1,394 of 1,394 on Blastware's exact time, every id
kept, no row lost or merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 19:29:38 -04:00
serversdownandClaude Opus 5.5 3948dc1a3c fix(decode): a Series-3 waveform's time comes from its Blastware filename
The review of this branch measured (and I re-measured) that the binary's
trigger -- ts2 minus the record time, from 1e76d08 -- is a second off on 260 of
prod's 1,394 waveforms (2026-09-30 snapshot): 199 late, 61 early.  A Blastware
filename encodes Blastware's own time to the second: it equals the report's
Event Time on 81/81 prod and 1,249/1,249 DL2 report-paired waveforms.

The cost of the second was real, not cosmetic:
- events is unique on (serial, timestamp), and on BE9558 the 61 early
  waveforms land on their histogram twin's second -- a fresh import wrote each
  waveform over its histogram's row (888 files -> 827 rows on dev);
- the release backfill would have moved 161 prod rows that v0.31.0 already had
  exactly right a second off.

Same-second collisions across all 11,827 prod-snapshot files: 61 with the
binary's times, 0 with waveform names.  Histograms keep the binary's ts1: their
name is Blastware's start time too (13,089/13,089) and ts1 runs a second early
on 97% of them, but with both on Blastware's times a waveform and its
histogram share a second 209 times -- the key cannot hold that.  Correcting
histogram times needs the key changed; not here.

- blastware_file.blastware_filename_time(): the inverse of
  blastware_filename(), V10.72 'AB0' names only, None for anything else.
- read_blastware_file(path, *, name=None): a waveform takes the name's time;
  save_imported_bw passes the upload's real name (it reads a temp file).
- insert_events' restamp matches only Blastware names (every unnamed upload is
  'imported.bw', so two events could share it) and, of several copies, moves a
  reviewed one with a time first (review items M1, M2).

Tests: the decoder (documented names, encoder round trip, other names), a
waveform's name time, a temp-named read, histograms unchanged, the twin
collision on BE9441's own ZI0 (binary 14:23:43, Blastware 14:23:42), and both
review items.  5 mutants, each caught.  Suite: only the 16 known failures.

Codec-library change: TOOL_VERSION to be bumped at release.  No schema change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 19:15:59 -04:00
serversdownandClaude Opus 5.5 a0fd5fcc25 docs(changelog): sub-minute histograms read big-endian, mic on and off (#47, #49)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 18:35:13 -04:00
serversdownandClaude Opus 5.5 6ed46dc3a3 merge: sub-minute histograms read big-endian from byte 5, mic on and off -- issues #47, #49
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 18:35:12 -04:00
serversdownandClaude Opus 5.5 dfc5aefef7 fix(histogram_codec): read multi-interval blocks big-endian from byte 5, mic on and off (#47, #49)
Measured 2026-10-26.  A sub-minute histogram block is [00][segment][ctr LE][0a]
(5 bytes), then one record per interval of BIG-endian peak / half-period pairs
per channel, then 0000 and one more word, then a 7-byte trailer.  A record is 20
bytes with the mic and 16 without (4 x channels + 4); the standard 32-byte block
is the same thing holding one record.  The last block is short, not padded: it
holds only the intervals recorded and ends on 9c 06 00 42.

#47: a mic-off histogram (16-byte records) decoded to nothing, so a Blastware
import carried no histogram data and SFM's download check would refuse it.
BE9441's K441LTOK.QZ0 (2 s, 22 intervals; fixture) now matches its Blastware
export on 66/66 peaks and 66/66 frequencies.

#49: the old reader took the mic-on records as little-endian from byte 6 -- the
same bytes shifted by one, identical while every high byte is zero.  It also
required byte 5 to be 0 (the first record's Tran peak high byte) and read the
last block at full stride, trimming what it overran.

Regression over every DL2 histogram with a Blastware ASCII export (13,089
files, interval counts + every geo peak, frequency and mic dB): old reader
13,087 exact, new 13,089.  The two the old one got wrong were one interval each:
K440KZP4.560H #4764 (Long half-period 1 read as 257, mic peak 389 as 133) and
M462KZUD.6R0H #145 (mic peak 6 read as 262).

Walk: blocks follow by block_ctr + 1, or the next segment every 256 blocks; the
last block is bounded by its terminal tail; with no terminal tail the old
trimming rule remains as the fallback.  Mic-off records give m_peak None and an
empty MicL channel, as a mic-off waveform does.  Inferred, not yet seen in a
file: mic-off 1-minute (28-byte) and 15 s / 5 s mic-off strides.

Not fixed here, noted on #47: half_period_to_hz assumes 1024 sps (512/hp); the
2048-sps histogram's frequencies are 1024/hp.

Operational: a decoder change -- needs a TOOL_VERSION bump at release, then
backfill_sidecars.py + backfill_event_shape.py (~2 h on the NAS) to regenerate
stored histograms.  No schema change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-26 18:30:09 -04:00
serversdownandClaude Opus 5.5 abb671a440 fix(decode): a paired report's event time is read in ISO form and survives a backfill
The event-time fix makes a Blastware report's Event Time + Event Date
authoritative over the binary, which gives the trigger only to the second.
On prod's own data it never applied (measured on the 2026-09-30 store
snapshot, all 81 report-paired Series-3 waveforms):

- every one of those reports writes Event Date as ISO ('2026-08-14');
  _parse_event_date read only 'August 14, 2026', so event_datetime was None
  (Brian's own laptop writes the long form -- it follows the PC's settings);
- the sidecar's bw_report block never stored the event time, and
  apply_bw_report_dict_to_event -- the backfill's overlay -- never set it.

The binary's trigger matched Blastware's printed time on 66 of the 81 and was
a second late on 15; 8 of those 15 hold the right time in prod today, so the
release backfill would have made them a second worse.

- _parse_event_date accepts ISO dates too (81/81 now parse to the time
  Blastware printed; 0/81 before).
- _bw_report_to_dict stores event_datetime (additive key).
- apply_bw_report_dict_to_event applies it, as apply_report_to_event does.

Prod's sidecars were written by the old parser, so the deploy runs
backfill_sidecars.py with --reparse-txt to re-read the saved .TXTs.

Tests: both date forms, the round trip through the saved block, a block with
no time, and the backfill (--force --reparse-txt) on a prod-shaped row.
Suite: only the 16 known fixture failures.

Codec-library change (report parser): TOOL_VERSION to be bumped at release.
No schema or DB migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 18:26:26 -04:00
serversdownandClaude Opus 5.5 847900baeb fix(sfm): a re-stored event at a corrected time moves its row instead of duplicating it
The waveform event-time fix (a84a46e / 1e76d08, on dev since 2026-09-20)
changed what time a Series-3 waveform decodes to: the trigger, where v0.31.0
stamped the monitoring-session start -- hours off.  events is unique on
(serial, timestamp), so re-storing an old event at its corrected time matched
nothing and inserted it a second time.

Measured 2026-10-26: files stored with v0.31.0 (prod's code), then dev's
backfill_sidecars --force -- the release's own deploy step -- gave every
waveform two rows, one at each time.  N844LQHB.ZT0W (BE12844): 06:00:13 and
10:33:29, its false-trigger mark only on the wrong-time copy.  A Blastware
re-forward of an old event would do the same with no backfill at all.  Prod
has not run the new decoder, so it holds no duplicates yet.

insert_events now matches a row by its stored file first (serial +
blastware_filename; a Blastware name encodes the serial and the second): one
under another time is moved to the new time in place -- same id, review kept --
and the usual refresh follows.  When a different stored file already holds the
corrected second, nothing moves and nothing is written; the old upsert wrote
this event's file and peaks over that other event's row.  Rows with no stored
file are matched on time alone, as before.

Tests: the move (id, review, refresh), a different file, no file, the
collision, a duplicate already at the new time, and the release backfill end
to end on a v0.31.0-shaped row.  Re-checked across versions: v0.31.0 import,
then this branch's backfill -- 5 real files, every row corrected in place, no
duplicates.  Suite: only the 16 known fixture failures.

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_01MUHR251NLznsFvPSrfegqL
2026-10-26 18:18:23 -04:00
serversdownandClaude Opus 5.5 6690434ecf docs(changelog): Micromate .h5 samples on Thor's own LSB (#42)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:49:07 -04:00
serversdownandClaude Opus 5.5 a5373deae7 merge: Thor .h5 samples on Thor's own LSB -- issue #42
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:48:41 -04:00
serversdownandClaude Opus 5.5 e506bcff9b fix(sfm): Thor .h5 samples use Thor's LSB, not the MiniMate count scale (#42)
Every idf-import .h5 converted Thor's raw geo counts with the MiniMate
body-codec scale, full_scale / _GEO_INT16_FS.  A Thor count is
0.000310308 in/s (micromate.idf_file._GEO_LSB_IPS), so the float samples
disagreed with the event's own peak by a constant:

  10/32768 (until 686ab6e, 2026-08-25)   samples -1.65%
  10/32000 (since)                       samples +0.71%

v0.30.0's LSB fix (726c2ce) never reached this path.  It corrected the
decoder's peaks, which were already right in the DB, sidecar and h5
peak attrs.  The sample arrays go through the shared .h5 writer instead.

write_event_hdf5 now takes geo_ips_per_count.  save_imported_idf and
backfill_thor_events (which replays the same bridge with its own write)
both pass _GEO_LSB_IPS.  MiniMate callers are unchanged.

Measured: all 8 thor-idf fixtures (4 IDFW + 4 IDFH, 24 channels) go from
max|sample| / peak = 1.00706 to 1.00000 through the real ingest path.

Operational consequence: no schema change, no migration, TOOL_VERSION
not bumped here.  Existing idf-import .h5 files keep the wrong scale
until regenerated: scripts/backfill_thor_events.py (--force, or bump
TOOL_VERSION at release), then backfill_event_shape.py, because the
offset detector reads these samples.  Series-3 files are unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:05:51 -04:00
348 changed files with 141609 additions and 12313 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
# Line endings (2026-11-12): every text file is stored and checked out with LF,
# whatever tool or OS wrote it -- file types we have not invented yet included.
# The protocol reference and seismo_lab.py were CRLF, so any rewrite outside the
# Edit tool turned them into whole-file diffs, and merges into them had to be
# resolved byte by byte. Same rule as Terra-View's. tests/test_line_endings.py
# fails if a CRLF file gets in anyway.
* text=auto eol=lf
# Binary -- never converted.
*.bin binary
*.pdf binary
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.h5 binary
*.pkl binary
*.db binary
*.sqlite binary
*.zip binary
*.gz binary
*.xlsx binary
*.docx binary
# Test fixtures are recorded bytes -- Blastware's own reports and exports, unit
# captures, event files -- kept byte for byte as ground truth: never converted.
tests/fixtures/** -text
+1 -1
View File
@@ -6,7 +6,7 @@
/bridges/s3-bridge/*.bin
/bridges/s3-bridge/*.log
/bridges/s3-bridge/*.set
/example-events/
/example-events
/tests/fixtures/
/manuals/
+1403 -4
View File
File diff suppressed because it is too large. Load diff
+262 -14
View File
@@ -2,7 +2,7 @@
Ground-up Python replacement for **Blastware**, Instantel's Windows-only software for
managing MiniMate Plus seismographs. Connects over direct RS-232 or cellular modem
(Sierra Wireless RV50 / RV55). Current version: **v0.31.0**.
(Sierra Wireless RV50 / RV55). Current version: **v0.35.0**.
Stack-level context — which repo owns what, and how the three project versions
pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
@@ -10,10 +10,153 @@ pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
---
## Where things stand (updated 2026-10-26)
## Where things stand (updated 2026-11-16)
Read this first when picking the project back up.
- **🔑 Prod still leans on Blastware's ASCII report, and that is scaffolding.**
- **How it works today:** when a `_ASCII.TXT` report arrives with a
Blastware file, `WaveformStore.save_imported_bw` overlays its peaks, notes,
sample rate and record time onto SFM's decode
(`event_file_io.apply_report_to_event`).
- **Only events without a report** run on the decoder alone: all DL2 events
before 2025, and everything SFM downloads itself.
- **Why that matters:** the overlay made SFM trustworthy from day one. It
also hid how much the decoder could not yet do; until the checker (below)
there was no full list of what Blastware reports.
- **The goal is full function without Blastware (Brian, 2026-10-29).** The
README roadmap has four steps:
1. the checker ✅
2. complete the file-only decode, one field group at a time
3. switch ingest so reports are kept only for checking (retire the overlay)
4. stop the watchers forwarding reports
- Until step 3, prod keeps the report as truth wherever one exists.
- **🔑 Monitor logs (.MLG) and each unit's timeline (v0.35.0, 2026-11-16).**
- **What:** every unit sends an `.MLG` at every call-in, in every mode. SFM reads it
(`minimateplus/mlg_file.py`, reference D.4) and keeps each unit's monitoring timeline:
sessions, gaps and what they mean, clock steps, and the call-ins, including calls that
left no file.
- **Why (Brian, 2026-11-09):** shot reports need proof that a unit which did not trigger was
monitoring. Continuous-mode units send no file on a quiet day. Outage history is the
second use.
- **Spec:** `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`.
- **Not yet:** the watcher still does not forward `.MLG`s (its repo, Brian's call), and
Terra-View shows none of it.
- **🔑 The Series-3 decode checker (2026-10-29; v0.33.0).**
- **Goal:** SFM produces everything Blastware reports, from the event file
alone (spec and plan in `docs/superpowers/`).
- **Running it:** `scratch/check_s3_decode.py ~/dl2-archive/files
~/dl2-archive/xml` decodes each event from its bytes only (no filename, no
report). It compares every field, sample and interval with Blastware's
`_XML.XML`: 70,042 events, 2016–2026, ~22 min at `--jobs 4`.
- **Output** (`summary.md`, `details.json`, `changes.md`) goes to
`~/dl2-archive/checker-runs/` and is never committed.
- **The rule:** every mismatch is SFM's bug unless a carve-out with evidence
covers it.
- **Byte layouts** of every field read from the file:
`docs/instantel_protocol_reference.md` Appendix **D.6**.
**Where the decoder stands** (v0.35.0; run `20261109-144544`):
**80 of 88 fields match on every event**, up from about 6 before v0.33.0,
47 before group D and 59 after it. Every other field matches or is accepted
under a carve-out with its evidence.
- Groups A, B, C and D part 1 shipped in v0.34.0 (#50, #51).
- D part 2 (the unit's own summary), E (the sensor check), F (the monitor
log), over range and the mic fixes shipped in v0.35.0, with its backfill
(`TOOL_VERSION` 0.35.0).
- Left: 16 values in two causes -- the vector sum's last digit on 4
waveform/histogram twins, and 4 accelerations (reference D.6.11). Brian
decided 2026-11-11 to leave both as they are, documented.
- 🔑 **Events are keyed unit + time + type:** `UNIQUE(serial, timestamp,
record_type)` (#51, Migration 3 in `sfm/database.py`, `dev`).
- A waveform and its histogram may share a second: 209 times in prod's
2026-09-30 store.
- Any lookup "by event" must include the type.
- An untyped event still dedups against an untyped row.
- Rehearsed on a copy of the prod snapshot: rows and ids kept, 9,852
histograms moved +1 s in place.
- ✅ **Match on every event:**
- sample rate, record time, pre-trigger, notes and event type (v0.33.0)
- geophone range, job number, event times (6,524 / 6,524) and histogram
start dates (63,518 / 63,518) — `dev`
- group A (`dev`, reference D.6.8): serial, version, calibration, battery,
trigger source, geo and mic trigger levels, stop mode, mic type
- group B (`dev`, D.6.9): interval frequencies, vector sums, size, stop
- group C (`dev`, D.6.10): histogram start and stop from the histogram's
own event record, interval times, and the peak dates and times
- group D (D.6.12): ZC frequency on every record type, peak displacement,
times of peak and the vector-sum time.
- These are **the unit's own values**, stored in the file right after
the event record. Blastware prints them; recomputing from the samples
reached only 46% and 84%.
- Peak acceleration is Blastware's own computation from the samples
(fitted g 386.2238): 6,522–6,523 / 6,524. The unit stores its own
too, which Blastware ignores. The misses are O117I1NK.R70W, whose
samples wrap at the trigger, and S353I5PZ.EP0W Vert (open).
- group E (D.6.13): sensor check frequency, ratio, mic amplitude and
result, every record type. Also the unit's own, in each sensor-check
record's header. "Check" is the unit's status code, not a limit SFM can
recompute.
- group F (D.6.14): the Monitor Log line. It is the footer's start and
stop plus words from the footer's flag word (Modem Exit, Timer Stop,
Keyboard Exit…), character for character on 69,983 / 69,983.
- 🔑 **The tail of every event file is one record chain** (D.6.13):
event record → unit summary → sensor checks → footer, each
`[length][id][payload]`. It ends exactly at the file's end on all 70,041
DL2 files, and SFM reads none of it otherwise.
- 🔑 **"Units" means three different things — keep them apart** (reference
D.6.6):
- **Recorded data:** the mic samples and interval peaks in the file, as
raw counts with no unit.
- **Report units:** dB(L) or psi(L) in a report.
- A Blastware report uses that PC's Blastware preference at the moment
it wrote the report; carve-out `units-is-a-display-preference`.
- SFM's report uses SFM's own fixed choice.
- **Unit peaks:** the unit's own summary, in its keypad Microphone Units
setting. Shown on its screen, in Blastware's event list, and in the 0C
record.
- Where the unit stores that setting is not measured yet; a keypad test
on a bench unit would show it.
- ✅ **Geophone samples** are exact on **6,524 / 6,524** waveforms in every
year (`dev`; v0.33.0 had 6,491, its 33 others being Sensitive-range events
read 8× high).
- ✅ **Histograms** decode to Blastware's own interval table on every DL2
file: Tran / Vert / Long interval peaks have 0 mismatches (`dev`).
- The codec is now chosen by STRT[18]. The waveform codec had been
claiming 2018 5 s histograms.
- The sub-minute layout check now tests peak ≤ PVS ≤ √3·peak.
- Blastware's "Number of Intervals" is the monitoring time ÷ the interval:
a carve-out, 8 events.
- ✅ **Histogram PVS** = the stored per-interval PVS²: 69,989 / 70,042.
**Mic:** one count = 0.25 Pa (an eighth at mic range 1, the mic block's
label + 29), dB offset 81.938216 (2026-11-09; 81.9384 was too high).
- ✅ **Over range (D.6.15):** a peak past 2,000 units (32,000 counts; the
mic in counts) is Blastware's `OORANGE`, per channel and per interval; the
vector sum is `OORANGE` exactly when a geophone is, never on its own.
- 🔑 **Blastware's mic unit labels don't hold on every report** (D.6.6): the
peak carries its own `<Units>`, a sample table's cells say its unit, and
a few reports mix dB and psi in one column (carve-out `mic-units-mixed`).
- ❌ **Open:**
- the vector sum's last digit on 4 waveform/histogram twins: Blastware's
value is ~1.5 ppm lower, cause unknown (no factor applied)
- 4 accelerations (D.6.12)
- ⬜ **Not read yet, in the order proposed** (2026-11-03):
- ~~**A. Setup fields**~~ ✅ done on `dev`.
- ~~**B. Histogram interval detail**~~ ✅ done on `dev`. Frequencies (#50),
per-interval PVS, interval size, stop.
- ~~**C. #51 timing**~~ ✅ done on `dev`.
- ~~**D. Blastware's waveform calculations**~~ ✅ done. ZC frequency,
displacement and time of peak are the unit's own (D.6.12); acceleration
is Blastware's.
- ~~**E. Sensor check results**~~ ✅ done (D.6.13). Plus the traces of a
unit without a mic, which the trace decoder had been dropping.
- ~~**F. Monitor log**~~ ✅ done (D.6.14): in the footer after all.
- 🔶 **#48 is still open.** The event file's setup block puts the pre-trigger
where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though,
it is **each event's own pre-trigger**, not the setting: 253–256 samples at
1024 sps, alternating on the same unit on the same day, and reported that
way by Blastware. So the files say little about whether the live 1A read
loses its anchor (reference D.6.2).
- **The Series-4 LIVE wire protocol is reverse-engineered end to end
(2026-09-25).** `docs/micromate_protocol_reference.md` is the Series-4
Rosetta Stone, sibling to `instantel_protocol_reference.md`. **A Micromate
@@ -194,6 +337,49 @@ Read this first when picking the project back up.
reads escaped bytes (#1), S3 downloads skip the file reader (#8), the S3
start read-back does not reconnect after the modem drops the line (#9), an
audit `sent: null` (#15), and page polish.
**Batch 1 fixed (2026-10-29):** #1 (`b320a53`, settings read after unescaping:
mode −7, rate −6, interval −4, record time +6), #9 (`ce441a0`, one reconnect for
the read-back), #8 (`9492e49`, downloads stored through `save_imported_bw`; since
2026-11-02 everything comes from the file -- peaks, vector sum, mic and the range
it was recorded at -- and the unit's 0C summary is only the download check). #2 came with the
`dev` merge. **#15 retracted** -- `sent` NULL is "unknown", by design.
Final review fixes: `dbd8a91` (wake before the reconnect's identity read),
`3a1d34a` ("already stored" by Blastware name too), `a72d3a9` (the 1A write
encoder refuses a patch that would not read back -- its offsets are 1024-sps
raw ones, #46).
**Phase 4 built 2026-11-02, benched 2026-11-03:** call-home on/off by serial for
both series (`GET /device/call_home/state`, `POST /device/call_home/{enable,disable}`,
the page's Call Home tab). The MiniMate frame is Blastware's byte for byte
(`tests/test_s3_call_home_bw_frames.py`, the 4-20-26 captures). On both units,
idle, the no-op, off and on writes were all verified and agreed with the unit's
menu. ⚠ **Neither series takes a call-home change while monitoring:** a MiniMate
returns its device-info block, and a Micromate acks the write and ignores it.
SFM refuses both up front.
**Phase 5 built 2026-11-03, benched 2026-11-04:** change a unit's settings by serial,
both series (`POST /device/settings/change`; the Config tab's Preview, then Send).
Spec `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md`.
- 🔑 **A MiniMate's settings block IS Series IV's `0x1A` layout** (measured):
the 1A read assembles to 2,090 bytes headed by N = 2090, and all 11
Blastware compliance writes reproduce from the block before them. One codec
serves both series: `micromate/setup_fields.py`.
- Limits are the units' own, from Instantel's manuals (Brian). A live send
needs its preview's revision; refused up front: monitoring, a Micromate on
its factory setup or whose schedule would load another setup.
- Retired: `/device/config` (410), `apply_config`, `_encode_compliance_config`.
- **Benched 2026-11-04, both series:** every change acknowledged, read back,
and confirmed on the unit's screen; both units restored byte for byte. The
MiniMate alarm write is measured and now on.
- ⚠ **A MiniMate's open setup menu wins:** a change sent while it is open is
lost when the operator presses Cancel or Save (the menu writes its whole-block
copy back). The preview warns; nobody in the menus while the office sends.
- ~~⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data
(about 1 frame in 85).~~ **Fixed in the parser (#58, 2026-11-06, measured):**
a checksum of 02/03/04 arrives as `10 X`, and that `10` is never data (7,747 /
7,747 recorded replies check). It had misread 1C battery/memory (419.84 V) and
the 2C call-home read; the 5A file builder's own compensation is gone with it,
and pre-fix `.a5.pkl` frames are converted on load (pickle version 2).
- ⚠ The Micromate scheduler switch is not in any block SFM reads, so a leftover
schedule blocks a change even with the scheduler Off.
**Ring path measured the same night:** with THOR's watchdog off, a call-home
reaches THOR when nobody holds the line, and **is lost when SFM holds it** --
the unit takes SFM's connection for the call, times out and does not retry.
@@ -247,7 +433,13 @@ Read this first when picking the project back up.
- **Series-3 decode is verified per-sample at scale (v0.27.0).** The full DL2
archive decodes **14,338 / 14,338** paired files exactly against their
preserved Blastware ASCII exports — 1,249 waveform + 13,089 histogram, 45
units, files back to 2018. That is 11x the ground truth the prod store
units, files back to 2018. ⚠ **Corrected 2026-10-29:** the 14,338 pairs
are all events from 2025–26 (five more carry a 1995 clock); DL2 kept ASCII
reports only from 2025. 🔑 Its `Sent/<stem>_<ext>_XML.XML` files are
Blastware's full event report — every report field plus every sample —
for **70,042 events back to 2016**, local copy `~/dl2-archive/xml`.
`scratch/verify_bw_fields_against_xml.py` checks file-only fields against
them. That is 11x the ground truth the prod store
carried, and it supersedes the old "per-sample on 11%, peak-only on 89%"
caveat. Harness: `scratch/verify_against_ascii.py` (note its saturation
carve-out — BW clamps clipped events, the decoder reports true counts).
@@ -318,9 +510,11 @@ Read this first when picking the project back up.
retracted 5A model: SUB 71's "offset 0x1004" reads as length 0x0400 escaped, and
Blastware escapes `03` in write data. A write whose payload holds a bare
02/03/04/10 may be malformed. One Blastware config-write capture settles it.
🔑 **Replies follow the same rule (measured, 748/748):** every 02/03/04/10 escaped,
checksum = SUM8 of the unescaped payload. The "S3 checksums frequently fail" belief
is `S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it.
🔑 **Replies follow the same rule (measured, 748/748; 7,747 / 7,747 across every
recording, #58):** every 02/03/04/10 escaped, the checksum too, and checksum = SUM8
of the unescaped payload. The "S3 checksums frequently fail" belief was
`S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it
(fixed 2026-11-06: `checksum_valid` holds on every recorded reply).
~~**⚠ KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB.**~~
`parse_strt_end_offset()` returns only `(end_key[2] << 8) | end_key[3]`,
discarding the key's page byte. An event starting at `0x0111F2A2` and ending
@@ -352,8 +546,9 @@ Read this first when picking the project back up.
take: Blastware downloading BE9441 event 2 (`0111c92c`) or 19 (`0118a4ca`)
through the recording bridge. Blastware's own files for both are fixtures
(`tests/fixtures/minimate-bench-10-25-26/blastware/`), as byte-exact targets.
- **Open, not blocking:** 14 sensitive-range files show an exact 8x
(= 10.0/1.25) units discrepancy; `scripts/backfill_sidecars.py --force` also
- **Open, not blocking:** ~~14 sensitive-range files show an exact 8x
(= 10.0/1.25) units discrepancy~~ (**resolved on `dev` 2026-11-02:** the
range is read from the file, reference D.6.4); `scripts/backfill_sidecars.py --force` also
inserts DB rows for store files that have none (one-time per store) and the
dry-run does not report that count.
- **After any codec change, regenerate the store** — `backfill_sidecars.py`
@@ -437,6 +632,26 @@ dedicated release commit when you are ready to ship to `main`.**
## Architecture: three-tier conceptual model
> ⚠ **SUPERSEDED 2026-10-27 by Terra-View's
> [`docs/adr/0003-stack-components-and-names.md`](../terra-view/docs/adr/0003-stack-components-and-names.md).**
> The SFM / SDM split below is retired.
> - **SFM is the whole seismograph module:** the call-in server, the adapters,
> decoding, the store, per-event measurements and the API. "SDM" is not
> used as a name any more.
> - **The codec library stays pure**, as described in tier 3. That rule
> survives unchanged.
> - **Lab tools** (`bridges/` bench tools, `scratch/`, `seismo_lab.py`) are
> experimental and are to leave the production image. One that becomes a
> real production tool is *ported* into `sfm/`, rebuilt on
> `sfm/device_access`.
> - **The call-in server** (today's `bridges/ach_server.py` and
> `bridges/mm_ach_server.py`) becomes SFM's front door, after the staged
> proof in the ADR.
> - **The repo becomes `sfm`** after `feat/series4-sfm-parity` merges.
>
> The text below is history, kept in place per this repo's retraction
> convention.
seismo-relay is a **suite of cooperating components**, not a single app.
The three tiers below are the canonical mental model — the current
directory layout doesn't fully reflect them yet (some of what is
@@ -562,6 +777,9 @@ minimateplus/ ← Python client library (primary focus)
per-sample decoder — see "Waveform body codec" section below)
sfm/server.py ← FastAPI REST server exposing device data over HTTP
sfm/sfm_webapp.html ← the SFM page; its JavaScript is in sfm/static/ (no inline JS,
sfm/static/ ← a stack-wide rule since 2026-11-02): device_routing.js holds the
DOM-free rules (Node-tested), sfm_webapp.js the page glue
seismo_lab.py ← Tkinter GUI (Bridge + Analyzer + Console tabs)
bridges/
mm_probe.py ← name the fault behind a dead unit (4 verdicts, read-only)
@@ -743,6 +961,14 @@ block still covers exactly one minute:
| 15 s | 4 | 92 |
| 2 s | 30 | 612 |
> ⚠ **CORRECTED in v0.32.0 (#47/#49), recorded here 2026-11-02.** The
> records are **big-endian, starting at byte 5**. Each holds a uint16 peak
> and a uint16 half-period per channel, then the interval's **PVS² as a
> uint32 BE**. Record = 4 × channels + 4 bytes: 20 with the mic, 16
> without. `stride = 12 + n × record`. The little-endian reading below was
> the same words shifted by one byte. Its "2-word tail" is the PVS²
> (reference D.6.5).
`stride = 12 + n * 20`. Block = `[00][segment][ctr uint16 LE][0a][00]`,
then n x 20-byte records of 8 x uint16 **LITTLE**-endian values
(`T_peak, T_halfp, V_peak, V_halfp, L_peak, L_halfp, M_peak, M_halfp`)
@@ -750,6 +976,7 @@ plus a 2-word tail whose first word is `0000` on every real interval,
then a 6-byte block trailer.
⚠ The standard 32-byte block is BIG-endian; this variant is LITTLE-endian.
*(Retracted: both are big-endian; see the box above.)*
Recovers **415 files** (216 on BE18193, 199 on BE9440) that decoded to
nothing. Ground truth `BE9440/K440L3AQ.T70H` matches its BW ASCII export
@@ -777,6 +1004,9 @@ block has its own tail signature. Two long-standing errors:
`1e 0a 00 00`, with arbitrary bytes at `[21:23]`. Rejecting it
dropped the final interval of nearly every histogram — frequently the
one holding the event peak, so the file's PPV read low.
- **`[21:25]` is the interval's PVS² as a uint32 BE** (v0.33.0, reference
D.6.5). The "arbitrary bytes" above are probably its high half
(inferred).
Verified against 1211 production histograms paired with their BW ASCII
exports: **1211/1211 decode exactly** (interval count plus every
@@ -785,11 +1015,14 @@ with zero mismatches. Before: 1 of 1196.
### What's NOT solved
- **MicL channel conversion to dB(L)** — the codec emits MicL as
- ~~**MicL channel conversion to dB(L)** — the codec emits MicL as
raw ADC counts (same format as geo channels), but BW's ASCII export
shows mic in dB(L) with ~6 dB quantization steps. Need to map
ADC counts → dB(L) for direct comparison; likely
`dB = 20*log10(|counts|) + offset` or similar.
`dB = 20*log10(|counts|) + offset` or similar.~~ **Solved in v0.33.0.**
One count = 0.25 Pa, and dB(L) = 81.938216 + 20·log10(|count|), an offset
measured from Blastware's printed values (reference D.6.6; 81.9384 until
2026-11-09).
- **Variable-prefix segment descriptors** — 3 of the 75 ground-truth
production events still truncate. The walk reaches a segment header
whose channel-id field is preceded by a *variable-width* prefix (2, 4
@@ -872,6 +1105,14 @@ dated subdirectory under `tests/fixtures/` (e.g. `tests/fixtures/5-18-26/`).
There used to be a separate `decode-re/` upload mirror but it was
removed once the fixtures directory became the canonical location.
⚠ **A test reads only tracked files** (2026-11-20). `bridges/captures/`,
`example-events/` and most of `tests/fixtures/` are gitignored, so a file a test
reads from there exists only on this box: a fresh checkout then fails or skips
it. Copy what the test needs into `tests/fixtures/` and `git add -f` it
(captures go under `tests/fixtures/captures/<their folder>/`), and do not guard a
fixture with a skip -- a missing fixture should fail. A fresh worktree is the
check: it must pass as the dev box does.
---
## Protocol fundamentals
@@ -1486,7 +1727,7 @@ Do NOT use fixed absolute offsets for sample_rate or record_time.
| trigger_level_geo | float32 BE, located in channel block |
| alarm_level_geo | float32 BE, adjacent to trigger_level_geo |
| geo_hardware_constant (adc_scale_factor) | float32 BE at **channel_label+28** in both read (E5) and write (SUB 71) payloads — reads **6.206053** on BOTH tested units (BE11529 and BE18189); identical across all geo channels (Tran/Vert/Long) and all captures. **Confirmed 2026-04-17 from Interface Handbook §4.5**: this is the **ADC-to-velocity scale factor** = 1/sensitivity = (in/s per V). Firmware uses it as: `PPV (in/s) = ADC_voltage × 6.206053`. Cross-check: `1.61133 V (ADC full-scale) × 6.206053 = 10.000 in/s` (Normal range ✅). Do NOT write this field — it is a hardware/firmware constant. |
| geo_range (sensitivity selector) | **uint8 at channel_label+33** in both read (E5) and write (SUB 71) payloads — **CONFIRMED 2026-04-20** from 4-20-26 geo sensitivity captures: `0x00` = Normal 10.000 in/s (standard gain), `0x01` = Sensitive 1.250 in/s (high gain). Present in all three geo channel blocks (Tran, Vert, Long). **NOTE: `channel_label+20` reads `0x01` on ALL captures regardless of range setting — it is NOT this field.** Note: the "SUB 71 write offset = +29" that appears in earlier analysis was an artifact of incorrect BW-style destuffing applied to write frame data — write frame data is RAW, so the literal `0x10` bytes in the channel block header are preserved, and the offset is the same as in the E5 read payload. |
| geo_range (sensitivity selector) | **uint8 at channel_label+33** in both read (E5) and write (SUB 71) payloads (an event file's setup copy has it at label+29: reference D.6.4) — **CONFIRMED 2026-04-20** from 4-20-26 geo sensitivity captures: `0x00` = Normal 10.000 in/s (standard gain), `0x01` = Sensitive 1.250 in/s (high gain). Present in all three geo channel blocks (Tran, Vert, Long). **NOTE: `channel_label+20` reads `0x01` on ALL captures regardless of range setting — it is NOT this field.** Note: the "SUB 71 write offset = +29" that appears in earlier analysis was an artifact of incorrect BW-style destuffing applied to write frame data — write frame data is RAW, so the literal `0x10` bytes in the channel block header are preserved, and the offset is the same as in the E5 read payload. |
| setup_name | ASCII, null-padded, in cfg body |
| project / client / operator / sensor_location | ASCII, label-value pairs |
@@ -1637,10 +1878,16 @@ GET /db/monitor_log?serial=BE11529&from_dt=&to_dt= ← monitoring intervals
GET /db/sessions?serial=BE11529&limit=50 ← ACH call-home sessions, newest first
PATCH /db/events/{id}/false_trigger?value=true ← flag/unflag false triggers
GET /db/device_commands?serial=UM20147&limit=100 ← start/stop audit trail (sent, states), newest first
POST /db/import/mlg_file?serial=&call_in=true ← Blastware .MLG upload (form field mtimes = JSON {name: unix s UTC})
GET /db/units/{serial}/timeline?from_dt=&to_dt= ← sessions, gaps (+ meaning), clock steps, call-ins, from .MLGs
GET /db/units/{serial}/monitoring_at?at= ← monitoring / not_monitoring / unknown at a unit-clock time
GET /db/mlg_records?serial=BE8081&from_dt=&to_dt= ← raw .MLG records, oldest first
GET /db/mlg_files/{id} ← the original .MLG, byte for byte
```
DB file: `bridges/captures/seismo_relay.db` (default; override with `--db-path` at startup).
All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger`.
All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger` and the
`/db/import/*` uploads.
---
@@ -1831,7 +2078,8 @@ A re-analysis in the prior session incorrectly concluded `section[1]` is always
and is device-specific. The 2026-04-09 re-analysis confirms `section[1]` was right.
**IMPORTANT — `frame.data` has checksum already stripped** by `S3FrameParser._finalise()`
(`raw_payload = body[:-1]`; `data = raw_payload[5:]`). There is NO trailing checksum byte in
(`raw_payload` = the body less its checksum, and less the `10` of an escaped one since #58;
`data = raw_payload[5:]`). There is NO trailing checksum byte in
`section`. All relative-from-end offsets must account for this.
Battery and memory fields are present in **both** states:
@@ -2246,7 +2494,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: `<prefix_letter><serial3><4-char-base36-stem><ext>`
- **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: `<prefix_letter><serial3><4-char-base36-stem><ext>`
**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).
+3 -1
View File
@@ -17,11 +17,13 @@ RUN apt-get update && \
# docker-compose; storage in the DB is always UTC regardless.
ENV TZ=America/New_York
# The product and its maintenance scripts (the backfills run in this
# container). The bench and lab tools -- bridges/, scratch/, seismo_lab.py --
# stay out of the image (ADR 0003; SFM imports nothing from them).
COPY pyproject.toml requirements.txt ./
COPY minimateplus ./minimateplus
COPY micromate ./micromate
COPY sfm ./sfm
COPY bridges ./bridges
COPY scripts ./scripts
RUN pip install --no-cache-dir -e .
+130 -8
View File
@@ -1,11 +1,11 @@
# seismo-relay `v0.31.0`
# seismo-relay `v0.35.0`
A ground-up replacement for **Blastware** — Instantel's aging Windows-only
software for managing seismographs. Supports both the **MiniMate Plus
(Series III)** and the **Micromate (Series IV / "Thor")** families:
Series III via the live RS-232 / TCP wire protocol *and* Blastware ACH file
ingest; Series IV currently via Thor TXT-paired IDF file ingest, with the
binary codec on the roadmap.
ingest; Series IV via Thor IDF file ingest (binary codec verified per-sample
against Thor's own exports), plus a read-only live client in `micromate/`.
Built in Python. Runs on Windows, Linux, or macOS. Connects to instruments
over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
@@ -59,6 +59,74 @@ over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
> recent.zip` (recent events' waveform files), and a gated
> `POST /db/restore` (`SFM_DB_RESTORE_ENABLED`, dev-only). Terra-View
> v0.17.0 drives them to pull a one-pass prod→dev refresh.
> **v0.32.0 (2026-10-27)** makes stored event times trustworthy.
> - **Series-III waveform times** now come from the instrument's own event
> record, which the unit sends inside its 5A stream. They used to be stamped
> with the monitoring-session start, hours off. The new time matches
> Blastware on every one of 1,320 report-paired waveforms, with no filename
> needed.
> - **Re-storing an event at its corrected time moves its row in place**,
> instead of duplicating it.
> - **Sub-minute histograms recorded with the mic off now decode** (#47, #49).
> - **Micromate `.h5` samples are on Thor's own scale** (#42).
> - **Series IV:** the live protocol is mapped (`docs/micromate_protocol_reference.md`)
> and has a read-only client.
>
> ⚠ The deploy owes a backfill and moves stored waveform times; see the
> changelog's *Migration*.
>
> **v0.33.0 (2026-11-01)** reads Series-III events from the file alone, and
> proves it.
> - **Fields now read from the event file** when no Blastware report comes with
> the event:
> - sample rate, record time, pre-trigger and the four notes (#44/#45)
> - the event type (#41)
> - a histogram's peak vector sum, which the unit stores per interval
> - the mic, at one count = 0.25 Pa (it read ~95× low in psi)
>
> This matters for every DL2 event from before 2025, and for SFM's own
> download and call-in paths, none of which have a report.
> - **The decode checker** (`scratch/check_s3_decode.py`) compares SFM's
> file-only decode with Blastware's `_XML.XML` event reports, field by field
> and sample by sample, for 70,042 DL2 events back to 2016:
> - every setup field, the notes and the event type match on every event
> - geophone samples are exact on 6,491 / 6,524 waveforms
> - the histogram vector sum matches on 69,919
>
> ⚠ The deploy owes a backfill; it does not move event times. See the
> changelog's *Migration*.
>
> **v0.34.0 (2026-11-04)** reaches Series-4 parity and reads most of
> Blastware's report from the event file alone.
> - **Series-4 parity:** one device door by serial for both series, with
> reads, downloads, start/stop, call-home and settings changes, each audited
> and read back. MiniMate request framing is fixed (#46).
> - **The file-only decode:** 47 of Blastware's 88 report fields match on
> every DL2 event, and 8 more on all but one or two.
> - Sensitive-range events are no longer 8× high.
> - Histograms decode correctly and carry Blastware's own times (#51).
> - Interval frequencies follow the sample rate (#50).
> - New from the file: the job number, serial, version, calibration,
> battery, trigger source and levels, interval detail, peak times and
> peak acceleration.
> - **Events are identified by unit + time + type.**
>
> ⚠ The deploy migrates the events table and owes an overnight backfill that
> moves every Series-3 histogram time by one second. See the changelog's
> *Migration*.
>
> **v0.35.0 (2026-11-16)** reaches 80 of Blastware's 88 report fields from the
> event file alone, and reads monitor logs.
> - **The file-only decode, groups D–F:** ZC frequency, displacement, times of
> peak, the sensor check, the Monitor Log line and over range, all from the
> unit's own records. A range-1 mic no longer reads 8× high.
> - **Monitor logs (.MLG):** SFM reads Blastware's `.MLG` files and keeps each
> unit's monitoring timeline, so it can answer "was unit X monitoring at T"
> for a shot report. See the `.MLG` endpoints below.
> - **An escaped checksum is the checksum, not data (#58).**
>
> ⚠ The deploy owes a backfill (about 8 hours on the NAS) and creates two
> empty tables. See the changelog's *Migration*.
> See [CHANGELOG.md](CHANGELOG.md) for full version history.
---
@@ -217,6 +285,10 @@ Query the SQLite database written by `ach_server.py`. All read-only except
| `GET` | `/db/monitor_log` | Monitoring intervals |
| `GET` | `/db/sessions` | ACH call-home session history |
| `PATCH` | `/db/events/{id}/false_trigger?value=true` | Flag / unflag false triggers |
| `GET` | `/db/units/{serial}/timeline?from_dt=&to_dt=` | A unit's monitoring timeline from its `.MLG`s: sessions (how each ended, events, trigger level), gaps and what each means, clock steps, call-ins (delivered / no_file / nothing_new). Times are the unit's own clock. |
| `GET` | `/db/units/{serial}/monitoring_at?at=` | Was the unit monitoring at `at`: `monitoring` / `not_monitoring` / `unknown`, with the session or gap that says so and the records and file behind it. |
| `GET` | `/db/mlg_records?serial=&from_dt=&to_dt=` | A unit's raw `.MLG` records, oldest first |
| `GET` | `/db/mlg_files/{id}` | The original `.MLG`, byte for byte (for printing or opening in Blastware) |
### File ingest endpoints
@@ -224,11 +296,14 @@ Used by watcher daemons to push field-collected event files into the SFM DB
+ waveform store. Both accept multipart uploads of binary event files
optionally paired with their ASCII sidecar reports; both dedup by
`(serial, timestamp)` and UPSERT device-authoritative fields on re-import.
Since v0.32.0 a Series-III event re-stored at a corrected time is matched by
its Blastware filename and moved in place (see *Database* below).
| Method | URL | Description |
|--------|-----|-------------|
| `POST` | `/db/import/blastware_file` | Series III: `.AB0*` / `.N00` binaries + paired `_ASCII.TXT`. Source: `series3-watcher`. |
| `POST` | `/db/import/idf_file` | Series IV: `.IDFH` / `.IDFW` binaries + paired `.IDFW.txt` / `.IDFH.txt`. Source: `thor-watcher`. |
| `POST` | `/db/import/mlg_file` | Series III monitor logs (`.MLG`), with each file's modified time as a JSON form field `mtimes`. Each file stored once; a damaged file stores nothing. Source: `scripts/import_mlg_dir.py` today; `series3-watcher` does not forward `.MLG`s yet. |
### DB snapshot / restore endpoints
@@ -345,13 +420,15 @@ reverse-engineering plan. The `micromate/idf_file.py` stub is where
`ach_server.py` and the file-ingest endpoints write to
`bridges/captures/seismo_relay.db` (SQLite, WAL mode) via the `SeismoDb`
persistence layer. Three tables, all unit-keyed by serial number:
persistence layer. The main tables, all unit-keyed by serial number:
| Table | Key | Contents |
|-------|-----|----------|
| `ach_sessions` | UUID | Per-call-home audit record: serial, timestamp, peer IP, events_downloaded, monitor_entries, duration_seconds |
| `events` | UUID, UNIQUE(serial, timestamp) | Triggered events: timestamp, Tran/Vert/Long/VectorSum/Mic PPV, project/client/operator/sensor_location strings, sample_rate, record_type, false_trigger flag, **`device_family`** ("series3" / "series4"), `blastware_filename` (binary at-rest in `waveforms/`), sidecar references |
| `monitor_log` | UUID, UNIQUE(serial, start_time) | Monitoring intervals: serial, waveform_key, start_time, stop_time, duration_seconds, geo_threshold_ips |
| `monitor_log` | UUID, UNIQUE(serial, start_time) | Monitoring intervals from live 0x0A reads (`ach_server.py` only): serial, waveform_key, start_time, stop_time, duration_seconds, geo_threshold_ips |
| `mlg_files` | UUID, UNIQUE(file_name, sha256) | One row per Blastware `.MLG` received (v0.35.0): serial, size, record count, empty flag, call-in flag, the file's modified time, where the original is kept, and the call it came from (`last_stop`, `no_file_stops`) |
| `mlg_records` | UUID, UNIQUE(serial, start, stop, flag word, trigger source) | One row per `.MLG` log record, stored once: start, stop (NULL = monitoring started), flag word, trigger source, Blastware's text and trigger level |
**Deduplication is by `(serial, timestamp)`** — the device clock is the
stable natural key. Repeat call-homes or re-runs UPSERT the row in place,
@@ -363,6 +440,20 @@ resets to `0x01110000` after every erase, so timestamps are the correct
dedup field. Migration handles the transition transparently on first
startup.
**Since v0.32.0**, `insert_events` also matches a row by its Blastware filename
(Blastware names only; a generic upload name like `imported.bw` says nothing):
- **A corrected time moves the row.** An event re-stored at a corrected time —
the v0.32.0 backfill, or a watcher re-forward — has its existing row moved in
place, keeping its id and review.
- **A taken second is refused.** If a different file already holds that second,
nothing is written.
- **An estimate never changes a row.** An event whose time is only an estimate
(no validated embedded event record; see Series-III reference §7.8.9) is still
stored, but its time never moves, merges into or duplicates a row.
Every refusal is logged as a warning.
**`device_family` (added v0.19.0)** discriminates Series III from Series
IV at the SQL level. Set by every import path; the UI dispatches on it
to render mic units correctly (Series III: psi → dBL conversion; Series
@@ -462,6 +553,7 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
- [x] Monitor control (start/stop, status polling, battery/memory)
- [x] Monitor log entries (continuous monitoring intervals without full waveform download)
- [x] Blastware file ingest at `/db/import/blastware_file` (paired with `series3-watcher`)
- [x] Blastware monitor logs (`.MLG`) at `/db/import/mlg_file`, and each unit's monitoring timeline (`/db/units/{serial}/timeline`, `/monitoring_at`) (v0.35.0)
**Series IV (Micromate / Thor) device support:**
- [x] Thor IDF file ingest at `/db/import/idf_file` (paired with `thor-watcher`, v0.18.0+)
@@ -471,7 +563,7 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
- [ ] Live-device protocol — pending codec
**Data persistence:**
- [x] SQLite database (`seismo_relay.db`) with `events`, `monitor_log`, `ach_sessions` tables
- [x] SQLite database (`seismo_relay.db`) with `events`, `monitor_log`, `ach_sessions`, `device_commands`, `mlg_files` and `mlg_records` tables
- [x] Per-row `device_family` column ("series3" / "series4") for clean UI / unit-of-measurement dispatch (v0.19.0+)
- [x] Deduplication by `(serial, timestamp)` — natural key handles post-erase counter resets
- [x] UPSERT on re-import refreshes every device-authoritative field (peaks, project, sample_rate); preserves operator review state (`false_trigger`)
@@ -584,7 +676,35 @@ Implementation steps (concrete):
### High-impact (unblocks product features)
- [ ] **Series III waveform body codec reverse-engineering.** The 5A bulk-stream body is some kind of compressed/encoded format (not raw int16 LE as previously assumed — see §7.6.1 retraction in `docs/instantel_protocol_reference.md`). Structural framing is ~50% decoded on branch `claude/codec-re-cBGNe` (tagged-block walker, segment counters); per-byte sample mapping is still open. Until this lands, the in-app waveform viewer renders garbage and BW-import peak values fall back to `_peaks_from_samples()` saturation noise. Workaround: pair every BW-imported event with its `_ASCII.TXT` so the device-authoritative peaks land in the DB regardless of codec.
- [x] **Series III waveform body codec reverse-engineering.** ✅ The body codec is fully decoded (`minimateplus/waveform_codec.py`, `histogram_codec.py`), and verified per-sample against Blastware's own exports. Geophone samples are exact on all 6,524 DL2 waveforms against their `_XML.XML` reports, across 2016–2026 (`dev`; v0.33.0 had 6,491, before the geophone range was read from the file).
- [ ] **SFM produces everything Blastware reports, from the event file alone.**
**Why this matters:** until it's done, prod overlays Blastware's ASCII report onto SFM's decode wherever a report exists. That made SFM trustworthy from day one, but it is scaffolding: the goal is full function without Blastware.
The four-piece plan:
1. the decode checker ✅ v0.33.0
2. complete the file-only decode, one field group at a time, each proven by the checker
3. flip ingest so reports are kept only for checking (retire the overlay)
4. stop the watchers forwarding reports
**Done so far: 47 of 88 report fields match on every DL2 event.**
- In v0.33.0: setup fields, notes, event type, histogram PVS, mic.
- On `dev`:
- the geophone range
- the job number
- histograms that decoded wrongly
- the footer: no more day-late histograms; every waveform time exact
- serial, version, calibration, battery, trigger source and levels, stop mode, mic type
- histogram interval detail: frequencies (#50 fixed), per-interval PVS, interval size, stop
- histogram start, stop, interval and peak times (#51 fixed); events keyed unit + time + type
- A Blastware report's dB/psi is its PC's preference, not anything in the event file: a carve-out.
**Next:**
- the values Blastware computes itself: ZC frequency, acceleration, displacement, time of peak
- the sensor check results
- the monitor log
Design: `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`. Status detail: CLAUDE.md "Where things stand".
- [x] **Series IV (Thor IDF) binary codec reverse-engineering.** ✅ v0.21.0 — `micromate/idf_file.read_idf_file()` decodes both IDFW (waveform body at offset `0x0f1f`, reusing `decode_waveform_v2()`; 87–99% sample fidelity on quiet events) and IDFH (dedicated segment-based decoder: all 859 corpus files decode, 181,071 intervals, peaks within ~1.8% of sidecar values). `WaveformStore.save_imported_idf` now also projects parsed Thor data into a `bw_report` block via `micromate/idf_to_bw_report.py` so Thor events render in the existing Event Report PDF pipeline without a separate renderer.
- [ ] **In-app waveform viewer accuracy.** Depends on Series III codec decode. Plot.v1 JSON pipeline + viewer skeleton already exist; will start showing real waveforms automatically once `_decode_a5_waveform` produces correct samples. Series IV waveforms come online when the IDF codec lands.
- [ ] **Series IV live-device support.** Once the IDF binary is decoded, extend `micromate/` with `transport.py` / `framing.py` / `protocol.py` / `client.py` mirroring the `minimateplus/` package layout — depends on capturing Thor's wire protocol (TCP / RS-232 captures TBD).
@@ -600,6 +720,8 @@ Implementation steps (concrete):
### Ingestion gaps
- [ ] **Event importer (parked 2026-10-29).** A way to load a folder of event files from disk into SFM in bulk — a historical archive, a laptop's Blastware folder, a backup — without routing them through a watcher. It is one of the four ways events should reach SFM (watcher forward, upload from disk, SFM's own serial/modem download, SFM's future call-in server). Prompted by DL2's 2016–2024 backfill, which the watcher could only drip-feed at 500 events a pass.
- [ ] **MLG forwarding.** `series3-watcher` forwards event binaries + their `_ASCII.TXT` reports, but skips `.MLG` per-unit monitor log files entirely. Adding an `POST /db/import/mlg_file` endpoint + watcher scan path would populate `monitor_log` for non-ACH-routed units (coverage queries, "was this unit monitoring on date X" lookups).
- [ ] **0C-record raw bytes persistence in the sidecar.** Currently on branch `claude/codec-re-cBGNe` as commit `a187124`; cherry-pick if useful as a standalone fix. Preserves the 210-byte 0C record under `extensions.raw_records.waveform_record_b64` so future field-offset analysis (Peak Acceleration / Time of Peak / etc. — the fields BW computes client-side from samples) can run offline.
@@ -622,7 +744,7 @@ Implementation steps (concrete):
- [ ] Locate "Sensor Check" byte in compliance config (need capture with Disabled vs Before-monitoring).
- [ ] Call Home — map time slots 3/4 offsets; confirm `modem_power_relay_enabled`.
- [ ] RV55 DCD/DTR — newer RV55 firmware doesn't assert DCD by default; units don't resume monitoring after call-home disconnect (`--restart-monitoring` flag deferred).
- [ ] **NULL-timestamp duplicate-row dedup.** A small handful of events (2 known on prod as of 2026-05-22) have `events.timestamp IS NULL` because the codec couldn't extract a timestamp from the binary footer. The `UNIQUE(serial, timestamp)` constraint doesn't fire on `NULL` (SQL semantics: `NULL ≠ NULL`), so every `--force` backfill INSERTs a new row instead of UPSERTing the existing one. Cleanup: a one-shot SQL query that keeps only the newest row per `(serial, blastware_filename)` and deletes the rest. Longer-term: extend the unique key to `(serial, COALESCE(timestamp, blastware_filename))` or reject inserts with NULL timestamp.
- [ ] **NULL-timestamp duplicate-row dedup (#52).** A small handful of events (2 known on prod as of 2026-05-22) have `events.timestamp IS NULL` because the codec couldn't extract a timestamp from the binary footer. The `UNIQUE(serial, timestamp)` constraint doesn't fire on `NULL` (SQL semantics: `NULL ≠ NULL`), so every `--force` backfill INSERTs a new row instead of UPSERTing the existing one. Cleanup: a one-shot SQL query that keeps only the newest row per `(serial, blastware_filename)` and deletes the rest. Longer-term: extend the unique key to `(serial, COALESCE(timestamp, blastware_filename))` or reject inserts with NULL timestamp.
- [ ] **Histogram body sub-format with `byte[5] != 0`.** ~3 events on prod (`T190LD5Q.LD0H`, `O121L4L1.GU0H`) use a histogram body my walker doesn't recognize — the first block has `byte[5] = 0x01` or `0x07` instead of `0x00`, and the entire body lacks the `1e 0a 00 00` tail signature. Codec returns 0 valid blocks; their DB PVS comes from the bw_report ASCII overlay (which BW computed from the same binary, so the DB columns are correct). Only the `.h5` waveform plot is empty. Cracking the sub-format would unlock the plot. Needs binary+ASCII pairs from a few `byte[5]!=0` events; same RE approach as the K558 case.
- [ ] **Histogram body sub-format with `byte[5] == 0x00` but undecodable.** Observed 2026-05-28 on BE17353 (S353) events: `S353L4H2.FZ0H`, `S353L4H2.P00H`, `S353L4H3.7O0H`, `S353L4H3.E10H`. Body starts `00 00 00 01 0a 00 XX 00 ...` which LOOKS like a valid histogram block header (marker 0x000a at byte[4:6] ✓, byte[5]=0x00 normal-format ✓), but the walker finds zero data blocks across the whole body. Likely an extra header before the block stream OR a different tail signature than `1e 0a 00 00`. Smaller body lengths (1900-2100 bytes) suggest these may be short-recording histogram variants. Same operational impact as the byte[5]!=0 case: event ingests cleanly, DB peaks correct via bw_report overlay, only the chart is empty. Worth dumping a hex view of one body to diagnose.
- [ ] **Sensor-check waveform extraction from the BW binary.** BW's Event Report PDFs include a narrow panel on the right side of the waveform plot showing each channel's response to the sensor self-check signal (a damped sinusoid for geo, sawtooth-at-test-freq for mic). Our parser captures the test RESULTS (`test_freq_hz`, `test_ratio`, `test_amplitude_mv`, `test_results` pass/fail) and the PDF + modal display them as text — but BW's per-sample sensor-check waveform isn't accessible to us today. Two paths to add it: (a) RE the binary to find where the sensor-check samples are stored — could be a section before STRT, after the footer, or in a separate sub-record; protocol reference doesn't currently mention it. (b) If samples aren't in the binary, synthesize a representative waveform from the test parameters (damped sinusoid at `test_freq_hz` with damping from `test_ratio`). Path (a) is the honest answer; path (b) is decorative. Until either lands, the text-only sensor-check display in the report is fine.
+51
View File
@@ -405,6 +405,57 @@ Header bytes 0–5: `00 12 01 00 00 00`. Followed immediately by the
strings (Operator name, etc.) and on through the project / client /
title strings. No `STRT` record observed in this layout.
### The event's settings, notes and time, from the file (2026-11-20, #44 / #45)
✅ Measured on **2,384** Signature-A files, **2,027** of them with Thor's own report
beside them (`thor-watcher/example-data`, `thor-csv-req`, and SFM's 2026-10-25 bench
downloads of UM12947). Code: `micromate.idf_file.extract_binary_metadata`.
**The settings record.**
- **Signature:** `[00 2a][04 00 00]`. The fields sit at the same offsets as the head
of the live `0x1A` setup block (`micromate/setup_block.py`):
| offset | field |
|---|---|
| `[5]` | record mode, 1–4 |
| `[6:8]` | sample rate, uint16 BE |
| `[12:16]` | this event's pre-trigger, f32 BE, negative seconds |
| `[17]` | stop mode |
| `[18:22]` | record time, f32 BE |
- **Where it sits:** at 0x910, 0x946, 0x98e or 0x9c4 (seen), depending on the
header's shape, so it is found by its signature, not its offset. Every one of the
2,384 starts `00 2a 04 00 00`. The one other `00 2a` that passed the field checks
(UM11402_20250610173039.IDFH at 0x915) had `92` in place of `04`.
- **Sample rate:** matches the report on **2,027 / 2,027**.
- **Record time:** matches on **291 / 291** waveforms.
- **Pre-trigger:** matches on **291 / 291** waveforms within the report's 0.01 s
rounding. The file holds the event's exact value: UM12947_20250929144014 has
193 samples = 0.18848 s, and the report prints 0.19. As in Series 3 (reference
D.6.2), it is the event's own pre-trigger, which can be shorter than the setting.
- **Histograms (`.IDFH`):** the record's sample rate is right, but its `[18:22]`
varies file to file (0.3 s to 840 s), so it is not a setting. Thor's report prints
no record time or pre-trigger for a histogram.
- ⚠ **Retracted:** the old reader found these by the bytes `be 80 00 00 00 00`,
the Series-3 "stable anchor". Those are a −0.25 s pre-trigger and Fixed stop
mode, so any other pre-trigger (UM12947's 1.0 s) left the sample rate and record
time unread (#44).
**The event time** is at settings record + `0x34`: it equals the filename's time on
**2,384 / 2,384**. The old fixed offsets 0x97A / 0x9F8 are that place for records at
0x946 / 0x9c4 only. A record at 0x910 left the time unread, and the event came out
1970-01-01.
**The notes** are four `[label 22][value 42]` pairs, 64 bytes apart, from **0x23c**,
at that fixed offset in every file seen. This is the live setup block's note layout.
In order, they are Thor's TitleString1–4, which the report maps to project, client,
operator and notes. All four match the report on **2,027 / 2,027**. The setup name
(e.g. `thump.MMB`) sits at 0x1ec in the bench files; not yet read.
**Also seen:** Thor writes `.MLG` monitor logs too
(`THORDATA_example/UPMC Presby/UM11719/UM11719_20231219161648.MLG`). Not examined;
compare with the Blastware `.MLG` (`instantel_protocol_reference.md` D.4).
### Signature B — older firmware (2 files: BE9439 from 2020)
```
File diff suppressed because it is too large. Load diff
+81
View File
@@ -1925,6 +1925,15 @@ at `payload[3:5]`:
| 2nd | `0x0002` | 535 B | the file body |
| 3rd | `0x0000` | 11 B | all zeros = **end of file** |
✅ **SFM reads the schedule this way, read-only (2026-11-03, phase 5)** --
`MicromateProtocol.read_file` / `MicromateClient.read_schedule`, frames equal to
THOR's byte for byte (`tests/test_micromate_schedule.py`). Two details the table
above leaves out: the `0x94` request carries **`params[3] = 1`**, and the **first**
`0x48` carries **`params[7] = 1`** (the later ones all-zero params); both `0x48`
offsets are `0xFFFF`. A long file is **written** in 1,024-byte `0x8E` pieces
(the five-entry *actioncheck* schedule went as 1,024 + 280). ⚠ Unmeasured: what
`0x94` / `0x48` return for a unit with no schedule file.
⚠ This is the single most consequential find of the session, because it is not
specific to the scheduler. **`callhome.MMB` is a file too**, and the call-home
config is the last unsolved piece of the project. Reading it should be a
@@ -2693,10 +2702,82 @@ noted, which is cheap to collect during any future ACH capture.
Neighbouring bytes: `write[117]` is `0x03`, lining up with Series III's
`num_retries` of 3, and `write[120:122]` is `00 3c` = 60.
#### Bench 2026-11-03: SFM's own call-home writes to UM20147
SFM's audited `POST /device/call_home/{enable,disable}`, one send per go.
Audit records are in the bench DB.
**Measured, idle:**
- UM20147 reads `content[5] = 0x01` for on. It **accepts `0x00` for off**, a
value THOR was never seen writing. The read-back reads off, and the unit's own
menu said "Auto Call Home: Disabled"; on again, "Enabled".
- **A no-op write is acked** (`0x81`, `0x80`), and `[118:120]` does **not** move:
`8fab` → `8fab`.
- **Flipping bit 0 of `[5]` moves `[118:120]` by XOR `0x6D7D`, both directions:**
`8fab` ↔ `e2d6`. That is the same XOR as UM12947's `0x04` ↔ `0x05` above, on
a different unit with a different block. Writing the original block back
restores the original value (`8fab`).
This **settles the open question above (hash vs nonce): it is not a per-write
nonce.** The field is a function of the block's content, and the fixed delta
for a fixed bit flip is the signature of a linear checksum (CRC family) over a
region that includes `[5]`. The fixed-delta part is *inferred*. A desk lead:
solve the polynomial from the deltas; the earlier sweep's regions or variants
were wrong.
**Measured, monitoring:**
- The unit returns its **real** call-home block (`00 7C DC`…).
- It **acks** a `0x7E`/`0x7F` write but **does not apply it**: three read-backs
over 3 s were unchanged, and `[118:120]` did not move. After the stop,
call-home still read on, so the write was **ignored, not staged**.
- Its own menu refuses the call-home screen while monitoring: **"Feature
disabled while monitoring"**.
- SFM therefore refuses a call-home change while monitoring (`f35845d`).
**Measured, also:**
- A stop with call-home on started a call-in **after** the stop's ack. SFM hung
up within about 1 s, and the call **reached THOR**: the session's histogram
arrived. (2026-10-29 Run A lost the call: there the ring replaced the ack.)
- UM20147's clock read one hour ahead after daylight saving ended (16:09:25 at
15:09:22 EST).
⚠ Beyond the enable byte and the dial string, **the field map is not
established** — only one setting was varied. Series III's offsets are a starting
hypothesis, not a transfer.
#### Bench 2026-11-04: SFM's first setup push (UM20147)
SFM's audited `POST /device/settings/change`, one send per go (Brian at the
unit). Notes: `~/bench-logs/2026-11-04-sfm-settings/`.
**Measured:**
- **The setup push works as THOR's.** Trigger 0.6 → 0.5, then a five-field
change (Location, Client, job number + its report flag, record time), then a
full restore. Each send was THOR's seven frames, acknowledged in THOR's order
(`25 97 8C 7D 7C 8E 8D`), read back as sent, and confirmed in the unit's menu.
The setup block ended byte for byte as found, CRC included.
- **The unit's recomputed CRC equals SFM's** (`with_crc`): after the first push
the stored block equalled SFM's computed image byte for byte, CRC `ea8d`
included.
- **`schedule.dat` read on a real unit** (`0x94` → `0x6B`; `0x48` → descriptor
`04 00 … 01 … 01`, body, all-zero end). UM20147 holds a leftover THOR
schedule: repeat on, 07:00, start monitoring with
`Fay - Commercial Street - Irish Center.mmb`. The unit runs `test2.MMB`, so
SFM blocked the change, as designed.
- 🔑 **The scheduler On/Off switch is in none of the blocks SFM reads.** With
the keypad switch Off, then On (saved), these were byte for byte identical:
`0x08` prefs, `0x2E`, `0x1A`, `0x2C`, `0x41` and `schedule.dat`. The
firmware's `SysPref.bMonitorScheduler` lives elsewhere. THOR's end-of-push
`0x47` pair (`params[7]` 1 then 3; replies `04 00 … 0N … 00 01`) was only
ever captured with the switch On. **Next:** a THOR bridge recording with the
switch Off (parked for the work-hours project).
- **While monitoring**, a settings preview and a live attempt were both refused
on the run state before any block was read (409, nothing sent, 0 write frames).
- **With call-home off, a stop goes straight to idle** (`monitoring` →
`idle`): no calling-home state and no ring.
- Call-home `0x01` ↔ `0x00` was taken again, both ways. The plan's
"unobserved" warning is retired for those values.
## What the THOR manual settles about the ACH session (2026-09-24)
Source: `manuals/723U0201 THOR Operator Manual Rev 08.pdf` §6.2, §3.6.
@@ -0,0 +1,648 @@
# Series 3 Decode Checker Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** A repeatable check that decodes every DL2 Series 3 event file the way SFM ingest does, with no report and no filename, and compares every field, sample and histogram interval with Blastware's `_XML.XML` report. It reports matches, mismatches and gaps, grouped for diagnosis, run after run.
**Architecture:** There are four pieces. Two are pure codec-library modules:
- `bw_xml_report.py` parses the reference.
- `decode_check.py` builds SFM's side from the bytes and compares the two.
A carve-out list sits beside the comparison. Two lab-tool scripts in
`scratch/` do the rest: one runs the corpus in parallel and writes a
results file, the other turns results into the summary, the detailed
report and the run-to-run changes.
**Tech Stack:** Python 3.10, standard library only (`xml.etree.ElementTree`, `concurrent.futures`, `gzip`, `json`), pytest.
**Spec:** `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`
## Global Constraints
- Work on branch `feat/s3-decode-checker`, worktree `~/seismo-relay-checker`.
Never commit to `main` or `dev`. **Do not touch `CHANGELOG.md`**: it is
written on dev at merge.
- **Standard library only.** `lxml` is not installed; do not add dependencies.
- **Codec-library modules never import `sfm/`.** These are
`minimateplus/bw_xml_report.py`, `minimateplus/decode_check.py` and
`minimateplus/decode_check_carveouts.py`. Only `scratch/` may import `sfm/`.
- **SFM's side comes only from the event bytes:**
`decode_blastware_bytes(raw, name=None)`. No filename, no report overlay,
and nothing from the XML ever reaches it.
- **SFM's own assumptions are kept:**
- geophone counts become in/s at the Normal range, `10.0 / 32000` per count
(`event_file_io._GEO_NORMAL_FS_INS / _GEO_INT16_FS`)
- mic counts become dB with `waveform_codec.mic_count_to_db`, or psi with
`event_file_io._MIC_FS_PSI`
- the range is never taken from the reference
- **Precision rule:** a number matches when
`|sfm − printed| ≤ 0.5·10^(−decimals in the printed text) + 1e-9`.
Blastware rounds halves away from zero.
- **Verdicts are exactly** `match`, `mismatch`, `sfm_blank`, `accepted`,
`no_reference`, `error`.
- **Series 3 only:** skip `UM…` XMLs. Dedupe binaries by upper-cased basename
(`Sent/` mirrors the root).
- **Run output goes outside the repo.** Default
`~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/`; it contains customer
names, so never commit it.
- **Speed:** a full run (70,042 events, `--jobs 4`) in under 1 h; `--sample
2000` in a few minutes.
- **Tests:** run with `/home/serversdown/seismo-relay/.venv/bin/python -m
pytest`.
- The full suite has 18 known failures in this worktree, and they also fail
on unchanged dev: 15 in `tests/test_bw_ascii_report.py`,
`tests/test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`,
and 2 in `tests/test_idf_binary_codec.py` (three-channel).
- A task may add **no new** failures.
- **Fixtures:** `tests/fixtures/` is gitignored. Add new fixtures with
`git add -f`.
## Review Focus
1. **Ragged sample rows.** Channels can end at different lengths: in
`T438HGTZ.B30W`, Tran/Vert/MicL stop 3 samples before Long. Blastware's
own table then prints rows with fewer cells, holding the channels still
running, in order. Cells must be attributed by SFM's per-channel lengths,
not by position. That file must come out `match`. A row whose cell count
disagrees with SFM's running channels is a `mismatch` with
`row_length_disagreements` in `detail`; never a silent zip. Tests in Task 3.
2. **The Sensitive range: a clipped 1.250 in/s event** (`M007HVWF.K30W`,
`OORANGE`). SFM's Normal-range values (8× high) must stay `mismatch`; the
saturation carve-out must not swallow them. Test in Task 4.
3. **An event that fails to decode, or an XML that is truncated or
malformed.** That event gets one `error` row and the run continues. Test in
Task 5.
4. **Non-numeric reference text where numbers are expected:** `>100`, `N/A`,
`Check`, `OORANGE`, and units inside the text (`6.7 Volts`, `3.0 sec.`).
These parse without exceptions and map to the rules in Task 3. Tests in
Tasks 1 and 3.
5. **Mic units: `dB(L)` vs `psi(L)` vs none** (`in/s` only, 3 channels, 7
interval columns). The comparison picks SFM's conversion by the reference's
units, and a no-mic event has no MicL rows at all. Tests in Tasks 1 and 3.
---
### Task 1: Fixtures and the XML report parser
**Files:**
- Create: `tests/fixtures/decode-checker-10-29-26/` holding these binaries
plus each one's `<stem>_<ext>_XML.XML`, copied from `~/dl2-archive/files/`
and `~/dl2-archive/xml/`:
- `R352HIUI.F40W`: waveform, setup `BE16352.set`
- `M529L4XQ.R30H`: histogram, relabelled notes
- `T1905KDW.5F0W`: waveform, job number, `>100`, `N/A`, `Check`
- `M007HVWF.K30W`: waveform, range 1.250, `OORANGE`
- `T004JTRF.ME0H`: histogram, `psi(L)`
- `R352HFZ7.530H`: histogram, no mic
- `T438HGTZ.B30W`: waveform, ragged rows, `OORANGE` at range 10.000
- Create: `minimateplus/bw_xml_report.py`
- Test: `tests/test_bw_xml_report.py`
**Interfaces:**
- Produces:
```python
@dataclass
class XmlReport:
scalars: dict[str, str] # tag -> text: top-level simple elements, and
# <Tag><Value>v</Value><Units>u</Units></Tag> -> v
units: dict[str, str] # tag -> the nested <Units> text
event_units: Optional[str] # top-level <Units>, e.g. "in/s and dB(L)"
channels: list[str] # <Channels>/<Channel> in order
job_number: Optional[str]
notes: list[tuple[str, str]] # (tag, value), non-empty, in order, between
# top-level </Units> and <GeoRange>, JobNumber excluded
sample_rows: Optional[list[list[str]]] # waveform: printed cells per row, as-is;
# a row holds only the channels still running
interval_columns: Optional[list[str]] # histogram: ColumnTitle, whitespace collapsed
intervals: Optional[list[tuple[str, list[str]]]] # histogram: (Time, cells)
def parse_xml_report(data: bytes) -> XmlReport
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport
```
- [ ] **Step 1: Copy the seven pairs into the fixture folder** (`cp` from the two dl2 folders; XML names keep the `_XML.XML` form).
- [ ] **Step 2: Write the failing tests** (literal values read from the XMLs):
```python
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
def test_scalars_units_and_special_text():
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
assert r.scalars["SampleRate"] == "1024 sps"
assert r.scalars["RecordTime"] == "1.0 sec."
assert r.scalars["TranPPV"] == "0.005" and r.units["TranPPV"] == "in/s"
assert r.scalars["VertZCFreq"] == ">100" # entity unescaped
assert r.scalars["TranZCFreq"] == "N/A"
assert r.scalars["TranTestResults"] == "Check"
assert r.scalars["BatteryLevel"] == "6.7 Volts"
assert r.job_number == "1" and r.notes == []
assert r.channels == ["Tran", "Vert", "Long", "MicL"]
def test_waveform_sample_rows():
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
assert len(r.sample_rows) == 1024
assert r.sample_rows[0] == ["-0.005", "0.000", "0.000", "81.94"]
assert r.intervals is None
def test_ragged_rows_are_kept_as_printed():
r = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
assert len(r.sample_rows) == 2304
assert r.sample_rows[-4] == ["-0.185", "0.235", "-0.255", "-87.96"]
assert r.sample_rows[-1] == ["-0.245"] # only Long still running
def test_relabelled_notes_keep_their_tags_in_order():
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
assert r.notes == [("Location", "Test Loc")]
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
assert r.notes[1] == ("Client", "Mele & Mele & Sons, Inc.")
assert r.event_units == "in/s and psi(L)"
def test_histogram_intervals_and_columns():
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
assert r.interval_columns[0] == "Tran Peak in/s" and len(r.interval_columns) == 10
assert r.intervals == [("2025-07-02 14:55:08",
["2.430", "13", "0.940", ">100", "1.900", "5.8", "3.095", "0.001", "106.0", "51"])]
assert r.samples is None
def test_no_mic_histogram_has_seven_columns():
r = parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML")
assert r.event_units == "in/s"
assert r.channels == ["Tran", "Vert", "Long"]
assert len(r.interval_columns) == 7 and len(r.intervals[0][1]) == 7
def test_oorange_and_range_values():
r = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
assert r.scalars["TranPPV"] == "OORANGE"
assert r.scalars["GeoRange"] == "1.250" and r.units["GeoRange"] == "in/s"
def test_truncated_xml_raises_valueerror():
data = (FIX / "M529L4XQ_R30H_XML.XML").read_bytes()
with pytest.raises(ValueError):
parse_xml_report(data[: len(data) // 2])
```
- [ ] **Step 3: Run them to watch them fail.**
Run: `…/python -m pytest tests/test_bw_xml_report.py -v`. Expected: FAIL on import.
- [ ] **Step 4: Implement `bw_xml_report.py`.**
- Parse with `xml.etree.ElementTree.fromstring`; wrap `ParseError` in `ValueError`.
- Walk the root's children in order.
- A child with a `<Value>` child goes in `scalars` and `units`.
- The notes are the simple children after the top-level `Units` and before
`GeoRange`.
- Waveform cells: `WaveformDataChannels/Data/Row/Cell`, one list per row,
unaltered.
- Histogram: `HistogramData/HistogramDataColumnTitle/ColumnTitle` and
`HistogramDataIntervals`, which interleaves `Time` and `Row`.
- [ ] **Step 5: Run the tests.** Expected: PASS.
- [ ] **Step 6: Commit** (fixtures with `git add -f`):
`feat(codec): parse Blastware's _XML.XML event report`
---
### Task 2: SFM's side, from the bytes alone
**Files:**
- Create: `minimateplus/decode_check.py`
- Test: `tests/test_decode_check.py`
**Interfaces:**
- Consumes: `minimateplus.event_file_io.decode_blastware_bytes`, `_GEO_NORMAL_FS_INS`, `_GEO_INT16_FS`, `_MIC_FS_PSI`; `minimateplus.waveform_codec.mic_count_to_db`.
- Produces:
```python
GEO_IPS_PER_COUNT: float = 10.0 / 32000 # from the event_file_io constants
@dataclass
class SfmSide:
event: Event
values: dict[str, object] # reference tag -> SFM's value, or absent/None = blank
notes: list[str] # non-empty project_info slots, in order
job_number: Optional[str] # None until the decoder reads it
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
counts: dict[str, list[int]] # waveform samples or histogram interval peaks, per channel
def sfm_side(raw: bytes) -> SfmSide
```
The `values` keys, and the only ones SFM fills today:
- `EventType`: `"Full Waveform"` / `"Full Histogram"` from `record_type`
- `SampleRate` (int), `RecordTime` (float)
- `Pre-triggerLength`: `-pretrig_samples / sample_rate`
- `EventDate` and `EventTime` for a waveform, or `HistogramStartDate` and
`HistogramStartTime` for a histogram: `YYYY-MM-DD` and `HH:MM:SS` from
`event.timestamp`
- `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum` from `peak_values`
- `MicLPSPL dB(L)`: `mic_count_to_db` of the largest |MicL count|
- `MicLPSPL psi(L)`: `peak_values.micl`
- `NumberofIntervals` for a histogram: the interval count
- [ ] **Step 1: Write the failing tests:**
```python
def test_waveform_side_from_bytes():
s = sfm_side((FIX / "R352HIUI.F40W").read_bytes())
assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0)
assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024)
assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52")
assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"]
assert len(s.counts["Tran"]) == 1277 and s.job_number is None
def test_histogram_interval_peak_in_counts():
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
# Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count
assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1
def test_no_filename_reaches_the_decoder():
# the type must come from bytes; today they can't tell (#41), so a histogram reads Waveform
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
assert s.values["EventType"] == "Full Waveform"
def test_report_fields_stay_blank():
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
assert s.values.get(tag) is None
```
When #41 is fixed, `test_no_filename_reaches_the_decoder` is updated to
`"Full Histogram"`. Until then it pins that no name is passed.
- [ ] **Step 2: Run them; expect a FAIL on import.**
- [ ] **Step 3: Implement `sfm_side`** in `minimateplus/decode_check.py`, per the Interfaces block.
- [ ] **Step 4: Run them; expect PASS.**
- [ ] **Step 5: Commit:** `feat(codec): SFM's side of the decode check, from the event bytes alone`
---
### Task 3: The comparison
**Files:**
- Modify: `minimateplus/decode_check.py`
- Test: `tests/test_decode_check.py`
**Interfaces:**
- Consumes: `XmlReport` (Task 1), `SfmSide` (Task 2), `Carveout` (Task 4,
passed in; default `()` so this task stands alone).
- Produces:
```python
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
@dataclass
class FieldResult:
field: str # reference tag, or "notes", "JobNumber", "Channels",
# "samples.<ch>", "intervals.<column title>"
verdict: str
bw: Optional[str] # printed text, or "<n> cells" for a series
sfm: Optional[str] # SFM's value rendered at the printed precision
detail: str = "" # series: "rows=… differing=… row_length_disagreements=… first_diff=… max_abs=…"
carveout: Optional[str] = None
def matches_printed(value: float, printed: str) -> bool
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]
```
**Rules** (exact; the tests pin each):
- **Which fields:** every tag in `ref.scalars` is compared except
`FileVersion` and `FileName`. So a field the XML carries and SFM doesn't is
automatically `sfm_blank`.
- **The reference says `N/A`:** the verdict is `no_reference`.
- **SFM has nothing (`None`):** `sfm_blank`.
- **Numbers:** for a value whose printed text begins with a number
(`-?\d+(\.\d+)?`, units after it ignored), the verdict is `match` when
`matches_printed` holds, else `mismatch`.
- **`>100`:** matches only when SFM's matching `*_zc_above_range` flag is True.
- **`OORANGE`:** a `mismatch` unless a carve-out applies.
- **Text:** anything else is compared exactly after whitespace collapse.
- **`MicLPSPL`:** compared against SFM's `MicLPSPL dB(L)` when `event_units`
contains `dB(L)`, `MicLPSPL psi(L)` when it contains `psi(L)`, otherwise
`sfm_blank`.
- **`notes`:** the list of note values vs `sfm.notes`. **`JobNumber`:**
`ref.job_number` vs `sfm.job_number` (skipped when the reference has none).
**`Channels`:** `ref.channels` vs `sfm.channels`.
- **`samples.<ch>`, one result per reference channel:**
- SFM's cells are geophone `count × GEO_IPS_PER_COUNT`; MicL uses
`mic_count_to_db(count)` for `dB(L)` or `count × _MIC_FS_PSI` for
`psi(L)`.
- For row *j*, SFM's running channels are the reference channels (in
order) with `len(sfm.counts[ch]) > j`. Their cells pair up, in order,
with the reference row's cells.
- A row whose cell count differs from SFM's running count is a row-length
disagreement for every channel in it. So are reference rows past SFM's
longest channel.
- A channel is `match` only with no row-length disagreements and every
paired cell `matches_printed`.
- `detail` always carries `rows=`, `differing=`,
`row_length_disagreements=`, `first_diff=` and `max_abs=`.
- **`intervals.<column>`, one row per column title:**
- The peak columns compare like samples: geophone `Peak in/s`, MicL
`Peak psi(L)` and `Peak dB(L)`.
- The `Freq` and `Geo PVS` columns are `sfm_blank` (SFM drops them).
- `intervals.Time` is `sfm_blank`.
- [ ] **Step 1: Write the failing tests:**
```python
def test_matches_printed_rounds_half_away():
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
assert not matches_printed(0.0026, "0.002")
def test_full_waveform_row_verdicts():
raw = (FIX / "R352HIUI.F40W").read_bytes()
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HIUI_F40W_XML.XML"))}
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
assert res[f].verdict == "match", (f, res[f])
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
assert res["BatteryLevel"].verdict == "sfm_blank"
assert "FileName" not in res
def test_ragged_rows_match_by_running_channels():
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
raw = (FIX / "T438HGTZ.B30W").read_bytes()
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"))}
for ch in ("Tran", "Vert", "Long"):
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
def test_an_extra_reference_row_is_a_mismatch_with_detail():
raw = (FIX / "T1905KDW.5F0W").read_bytes()
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
res = {r.field: r for r in compare(sfm_side(raw), ref)}
assert res["samples.Tran"].verdict == "mismatch"
assert "row_length_disagreements=1" in res["samples.Tran"].detail
def test_job_number_na_and_above_range():
raw = (FIX / "T1905KDW.5F0W").read_bytes()
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML"))}
assert res["JobNumber"].verdict == "sfm_blank"
assert res["TranZCFreq"].verdict == "no_reference" # N/A
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
def test_mic_units_pick_the_conversion():
raw = (FIX / "T004JTRF.ME0H").read_bytes() # psi(L)
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML"))}
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
raw = (FIX / "R352HFZ7.530H").read_bytes() # no mic
fields = {r.field for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML"))}
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
```
- [ ] **Step 2: Run them; expect a FAIL** (no `compare`).
- [ ] **Step 3: Implement `matches_printed` and `compare`**, per the rules.
- [ ] **Step 4: Run them; expect PASS.** If a `match` assertion fails, report
the `FieldResult` and stop. Do not loosen a rule to make it pass.
- [ ] **Step 5: Commit:** `feat(codec): compare SFM's file-only decode with Blastware's XML, field by field`
---
### Task 4: Carve-outs
**Files:**
- Create: `minimateplus/decode_check_carveouts.py`
- Modify: `minimateplus/decode_check.py` (apply carve-outs in `compare`)
- Test: `tests/test_decode_check.py`
**Interfaces:**
- Produces:
```python
@dataclass(frozen=True)
class Carveout:
id: str
fields: tuple[str, ...] # exact names, or prefixes ending in "." ("samples.")
evidence: str # why Blastware is the one that differs, and the source
applies: Callable[[SfmSide, XmlReport, FieldResult], bool]
SATURATION: Carveout
CARVEOUTS: tuple[Carveout, ...] = (SATURATION,)
```
- **How `compare` uses them:** a `mismatch` whose field a carve-out covers and
whose `applies` returns True becomes `accepted`, with `carveout=<id>`.
- **`SATURATION`:**
- Covers `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum`,
`samples.Tran/Vert/Long` and the `intervals.* Peak in/s` columns.
- `r = float(ref.scalars["GeoRange"])`. A cell or value Blastware printed as
`OORANGE`, or with `|bw| ≥ r − 0.0006`, is "clamped".
- It applies when every differing cell/value is clamped and SFM's is the
same sign with `r − 0.0006 ≤ |sfm| ≤ r × 1.01`.
- The upper bound keeps an 8× Sensitive-range value a mismatch.
- **`PeakVectorSum`** is a vector sum, so it can exceed the range (11.55
on `T438HGTZ`). It is accepted when Blastware printed `OORANGE` and at
least one of SFM's three PPVs sits in that ceiling band.
- Evidence text: *"Blastware clamps a clipped channel to the range maximum
and prints OORANGE; the file holds counts past full scale (32016 counts =
10.005 in/s observed). scratch/verify_against_ascii.py, 2026-08-28."*
- [ ] **Step 1: Write the failing tests:**
```python
def test_clipped_normal_range_is_accepted():
# Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55
raw = (FIX / "T438HGTZ.B30W").read_bytes()
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"), CARVEOUTS)}
assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match"
for f in ("LongPPV", "PeakVectorSum"):
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
def test_sensitive_range_8x_stays_a_mismatch():
raw = (FIX / "M007HVWF.K30W").read_bytes()
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML"), CARVEOUTS)}
assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch"
def test_every_carveout_has_evidence():
assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)
```
- [ ] **Step 2: Run them; expect a FAIL.**
- [ ] **Step 3: Implement the module and the hook in `compare`.**
- [ ] **Step 4: Run all `tests/test_decode_check.py`; expect PASS.**
- [ ] **Step 5: Commit:** `feat(codec): carve-outs for proven Blastware differences -- saturation first`
---
### Task 5: The runner
**Files:**
- Create: `scratch/check_s3_decode.py`
- Test: `tests/test_check_s3_decode.py`
**Interfaces:**
- Consumes: `parse_xml_report_file`, `sfm_side`, `compare`, `CARVEOUTS`.
- Produces:
```python
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]
# (basename, binary, xml or None); Series 3 binaries only (^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$),
# deduped by upper-case basename; xml = <stem>_<ext>_XML.XML in xml_dir
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]
# grouping keys, all from the reference or the file:
# model ("MiniMate Plus" / "BlastMate III" from Version), serial (SerialNumber),
# type (EventType), year (EventDate or HistogramStartDate), sample_rate, range (GeoRange),
# mic_units (event_units), interval (IntervalSize or "-"),
# setup_standard ("yes" if b"Standard Recording Setup" in raw else "no")
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict
# {"file", "attrs", "results": [[field, verdict, bw, sfm, detail, carveout], ...]}
# no xml -> one ["event","no_reference",…] row; any exception -> one ["event","error",None,None,repr(exc),None] row
def main(argv: Optional[list[str]] = None) -> int
```
- **CLI:** `bin_dir xml_dir [--out DIR] [--serial S]... [--year Y]...
[--type W|H] [--field PREFIX]... [--sample N] [--seed K] [--jobs N]
[--file NAME] [--compare-to DIR]`.
- `--field` keeps only result rows whose field starts with a given prefix
(the spec's "field group" partial run).
- `--file` and `--compare-to` are wired in Task 7; here they are only
accepted.
- The spec's "decoder path" grouping key is omitted: the decoder does not
expose it today.
- **Output:** writes `<out>/results.jsonl.gz` (one line per event) and
`<out>/run.json`.
- `run.json` holds the args, the `git rev-parse HEAD`, the event count and
the wall time.
- It prints the run folder.
- Parallelism: `ProcessPoolExecutor(jobs).map(…, chunksize=64)`.
- [ ] **Step 1: Write the failing tests** (on the fixture folder, which holds
binaries and XMLs together):
```python
def test_find_pairs_dedupes_and_pairs(tmp_path):
(tmp_path / "Sent").mkdir()
for n in ("R352HIUI.F40W", "Sent/R352HIUI.F40W", "UM11719_20240404193109.IDFH"):
(tmp_path / n).write_bytes(b"x")
pairs = find_pairs(tmp_path, FIX)
assert [p[0] for p in pairs] == ["R352HIUI.F40W"] and pairs[0][2].name == "R352HIUI_F40W_XML.XML"
def test_check_event_rows_and_attrs():
out = check_event("M007HVWF.K30W", str(FIX / "M007HVWF.K30W"), str(FIX / "M007HVWF_K30W_XML.XML"))
assert out["attrs"]["range"] == "1.250" and out["attrs"]["model"] == "MiniMate Plus"
assert any(r[0] == "TranPPV" and r[1] == "mismatch" for r in out["results"])
def test_bad_input_is_one_error_row(tmp_path):
bad = tmp_path / "R352HIUI.F40W"; bad.write_bytes(b"not a blastware file")
out = check_event(bad.name, str(bad), str(FIX / "R352HIUI_F40W_XML.XML"))
assert out["results"] == [["event", "error", None, None, out["results"][0][4], None]]
def test_cli_writes_results(tmp_path):
assert main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
lines = gzip.open(tmp_path / "run/results.jsonl.gz", "rt").read().splitlines()
assert len(lines) == 7 and json.loads((tmp_path / "run/run.json").read_text())["events"] == 7
```
- [ ] **Step 2: Run them; expect a FAIL.**
- [ ] **Step 3: Implement**, per the Interfaces block.
- [ ] **Step 4: Run them; expect PASS.**
- [ ] **Step 5: Time a sample.** Run `scratch/check_s3_decode.py
~/dl2-archive/files ~/dl2-archive/xml --sample 2000 --jobs 4`. Expected: a
few minutes. Note the time in the commit body.
- [ ] **Step 6: Commit:** `tooling(scratch): run the decode check over the archive in parallel`
---
### Task 6: The summary and the detailed report
**Files:**
- Create: `scratch/decode_check_report.py`
- Modify: `scratch/check_s3_decode.py` (write both reports at the end of a run)
- Test: `tests/test_check_s3_decode.py`
**Interfaces:**
- Produces:
```python
def aggregate(results_path: Path) -> dict
def write_summary(agg: dict, path: Path) -> None # <out>/summary.md, for Brian
def write_details(agg: dict, path: Path) -> None # <out>/details.json, for Claude
```
- **`summary.md`** has four parts:
- a per-field table with one column per verdict (in `VERDICTS` order),
sorted by non-match count
- a line `N of M fields fully matching`
- the non-match counts per event year
- the carve-out counts
- **`details.json`** has one entry per `(field, verdict)` with verdict ≠
`match`. Each entry holds:
- `total`
- `groups`: for each attribute, the values whose failing count is ≥ 10% of
`total`. Each value carries `{value, failing, compared, rate}`, where
`compared` counts events where the field's verdict was not
`no_reference`. Sorted by `failing` descending; `concentrated: true` when
`rate ≥ 0.95`.
- `examples`: up to 8, taking one per top group value first. Each gives
`{file, bw, sfm, detail, rerun}` with `rerun = "python
scratch/check_s3_decode.py <bin_dir> <xml_dir> --file <name>"`.
- [ ] **Step 1: Write the failing tests:** build a small `results.jsonl.gz` by
hand with literal rows: 3 events, one field `SampleRate`, two `mismatch` on
`sample_rate=2048`, one `match` on `1024`. Assert:
- `details.json["SampleRate|mismatch"]["groups"]["sample_rate"]` is
`[{"value": "2048", "failing": 2, "compared": 2, "rate": 1.0,
"concentrated": True}]`
- `summary.md` contains `0 of 1 fields fully matching`
- every example carries a `rerun` with `--file`
- [ ] **Step 2: Run them; expect a FAIL.**
- [ ] **Step 3: Implement**, streaming the results file line by line and
holding only counters plus a capped example list.
- [ ] **Step 4: Run them; expect PASS.**
- [ ] **Step 5: Commit:** `tooling(scratch): decode-check summary and grouped detail report`
---
### Task 7: Run-to-run changes and the single-event view
**Files:**
- Modify: `scratch/decode_check_report.py`, `scratch/check_s3_decode.py`
- Test: `tests/test_check_s3_decode.py`
**Interfaces:**
- Produces:
```python
def compare_runs(prev_results: Path, cur_results: Path) -> dict
# {"fields": {field: {verdict: [before, after]}},
# "regressions": [{"file", "field", "before", "after"}], # before == "match", after != "match"
# "fixed": int} # before != "match", after == "match"
def write_changes(chg: dict, path: Path) -> None # <out>/changes.md, regressions first
```
- **`--compare-to DIR`:** defaults to the newest other folder in the runs
folder. `summary.md` starts with a regressions line (`0 regressions` or the
count plus a pointer to `changes.md`).
- **`--file NAME`:** finds that one event, runs `check_event` and prints a
table `field | verdict | Blastware | SFM | detail` to stdout. No run folder
is written.
- [ ] **Step 1: Write the failing tests:**
- Two hand-built results files where one `(file, field)` goes from `match`
to `mismatch` and another from `sfm_blank` to `match`: assert one
regression and `fixed == 1`.
- `main([FIX, FIX, "--file", "M007HVWF.K30W"])` prints a line containing
`TranPPV` and `mismatch`, and returns 0.
- [ ] **Step 2: Run them; expect a FAIL.**
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run them; expect PASS.**
- [ ] **Step 5: Commit:** `tooling(scratch): decode-check run-to-run changes and a one-event view`
---
### Task 8: The first full run, checked against what we know
**Files:**
- Delete: `scratch/verify_bw_fields_against_xml.py` (the checker replaces it)
- Modify: `CLAUDE.md` ("Where things stand": one short bullet with the first
run's headline numbers and the command)
- Modify: `docs/instantel_protocol_reference.md`. Correct the `#53` note in
place, per the retraction convention: the three files pick an earlier,
false footer, get the right sample count and a time 4 s off, and log no
`decode_problems`. ⚠ The file is CRLF, so edit it with the Edit tool, not a
Python text-mode rewrite.
- [ ] **Step 1: Full run.** `scratch/check_s3_decode.py ~/dl2-archive/files
~/dl2-archive/xml --jobs 4`. Expected: it finishes in under an hour and
writes `summary.md`, `details.json` and `results.jsonl.gz`.
- [ ] **Step 2: Check the first-run expectations from the spec's "What success
looks like"**, one by one, against `summary.md` and `details.json`:
- `SampleRate`, `RecordTime`, `Pre-triggerLength` and `notes` all `match`
- `samples.*` mismatch only on the range-1.250 events (8×) among 2025–26
events; `T438HGTZ.B30W` matches
- `EventType` mismatches exactly on the histograms
- `JobNumber` and the calculated fields are `sfm_blank`
- the three `#53` files show as time mismatches
Any other non-match is a finding. Write it into the report's notes for
Brian; **do not change a rule to hide it.** If an expectation fails because
the checker is wrong, fix the checker with a test first.
- [ ] **Step 3: Full suite.** Expected: no new failures beyond the 18 known.
- [ ] **Step 4: Docs, per Files above.**
- [ ] **Step 5: Commit:** `docs: the decode checker's first full run; correct the #53 note`
@@ -0,0 +1,172 @@
# SFM 1c bench fixes, Batch 1 — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Fix the three reliability findings from the 2026-10-29 bench that put wrong or missing data in front of a user: MiniMate settings read from escaped bytes (#1), a MiniMate start reported failed because the read-back did not survive a dropped modem line (#9), and MiniMate downloads stored without the file reader (#8).
**Architecture:** Three independent fixes on `feat/series4-sfm-parity` (merged up with `dev` at `342c696`), each behind its own tests on recorded BE9441 bytes. #1 changes only the four anchor-relative fields of the live `SUB 1A` decode; #9 adds one guarded reconnect to the Series-3 start read-back; #8 stores Series-3 downloads through the same Blastware-file import path production uses (`WaveformStore.save_imported_bw`), the way Series 4 already uses `save_imported_idf`.
**Tech Stack:** Python 3.10, pytest; `minimateplus` (client, framing, blastware_file), `sfm` (device_access, event_ingest, waveform_store).
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` → *Left open by the 1c bench (2026-10-29)*, items 1, 8, 9 (and 15, retracted below).
## Global Constraints
- Branch `feat/series4-sfm-parity` only; push each commit; never `main`; no `CHANGELOG.md` edits (feature branch).
- **Reliability before speed** (Brian, 2026-10-29): no change removes a check; a start/stop is still sent exactly once, never retried.
- **File boundary with the S3 decode-checker session:** do not edit `minimateplus/event_file_io.py`, `histogram_codec.py`, `waveform_codec.py`, `bw_xml_report.py`, `decode_check*.py`.
- `docs/instantel_protocol_reference.md` is CRLF: edit it with the Edit tool only.
- Tests: `/home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider`; the baseline is exactly 16 known failures (15 `test_bw_ascii_report.py`, `test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`).
- Store consequence (state it in the commit and docs): #8 changes how **new** live downloads are stored; existing rows and files are untouched; no backfill, no migration.
## Review Focus
1. A modem that closes the line cleanly (FIN) during the read-back shows as silence, not an `OSError`: no reconnect, the result stays "sent, not checked", nothing re-sent. (Task 2 test.)
2. A MiniMate on a serial cable: never reconnect in the read-back — opening its port reboots the unit (measured 2026-10-25). (Task 2 test.)
3. A settings read while the unit is monitoring returns the device-info block, not the settings block (measured 2026-10-29): mode, sample rate, interval and record time must come back `None`, not garbage. (Task 1 test.)
4. Downloading an event twice, or one the watcher already imported, must not add a second row. (Task 3 tests.)
5. The channel block (trigger level, range, scale) and the note strings must read exactly as before: only the four anchor fields move to unescaped bytes. (Task 1 test.)
## Retraction carried by this plan
**#15 is not a bug.** `device_commands.sent` is documented as `1 acknowledged, 0 nothing sent, NULL unknown` (`sfm/database.py:148`, `change.py:12-14`); a stop answered by a ring instead of its ack is exactly "unknown", and the row's `error` text already says the frame was sent. Task 4 retracts it in the spec.
---
### Task 1: The live settings decode reads its four anchor fields from unescaped bytes (#1)
**Files:**
- Modify: `minimateplus/client.py` — `_decode_compliance_config_into` (~line 2312), its anchor block (~2385–2440)
- Create: `tests/test_s3_compliance_anchor_fields.py`
**Interfaces:** Produces nothing new; `_decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None` keeps its signature. `info.compliance_config` fields `recording_mode`, `sample_rate`, `histogram_interval_sec`, `record_time` change meaning only for escaped replies.
Measured layout once escapes are removed (`framing.unescape_reply`), from every distinct recorded reply: **mode `anchor−7` (u8), sample rate `anchor−6` (u16 BE), histogram interval `anchor−4` (u16 BE, s), record time `anchor+6` (f32 BE)**. The channel block and strings are correct on the raw bytes and must stay there (unescaped, `"Tran"+28` reads 0.0 instead of 6.2061).
- [ ] **Step 1: Write the failing tests** — a helper collects every `SUB 0xE5` frame from `tests/fixtures/minimate-bench-10-25-26/*_rx.bin` and `tests/fixtures/minimate-bench-10-26-26-histogram/unit_replies.bin` whose `data` contains the anchor, de-duplicated by the 18 bytes around it (`S3FrameParser().feed`).
```python
@pytest.mark.parametrize("fixture,expect", [ # (mode, sample_rate, interval_s, record_time_s)
("10-25", (1, 4096, 5, 5.0)), # Continuous
("10-26a", (4, 2048, 2, 20.0)), # Histogram + Continuous
("10-26b", (3, 4096, 900, 20.0)), # Blastware's 16:26 write: Histogram, 15 min
("10-26c", (3, 4096, 2, 20.0)), # Blastware's 16:27 write: back to 2 s (tonight's unit)
])
def test_anchor_fields_read_from_unescaped_bytes(fixture, expect): ...
# decode the frame's data with _decode_compliance_config_into(DeviceInfo())
# assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, round(cc.record_time, 2)) == expect
def test_channel_block_still_reads_from_raw_bytes():
# data = the 10-26c frame-B data + the next E5 frame whose data contains b"Tran"
# assert cc.trigger_level_geo == pytest.approx(0.04, abs=1e-4)
# assert cc.geo_adc_scale == pytest.approx(6.2061, abs=1e-3) and cc.geo_range == 0
def test_a_reply_without_the_settings_block_reads_as_unknown():
# the recorded SUB 0xFE (device info) reply data -- what a monitoring BE9441 returned for 1A
# assert all four anchor fields are None
```
The fixture labels are the test's own: number the de-duplicated replies in file order and map them to the four expectations above (assert there are exactly four).
- [ ] **Step 2: Run** `…pytest -q tests/test_s3_compliance_anchor_fields.py` → FAIL: `10-25` reads mode 0, `10-26c` reads sample rate 0 and interval 4098 (today's decoder on escaped bytes).
- [ ] **Step 3: Implement** — in the anchor block, search `_ANCHOR` in `logical = unescape_reply(data)` (same `0:150` window) and read the four fields from `logical` at the offsets above; leave every other read on `data`. Update the layout comment to the measured logical layout and note the old "anchor−7 constant 0x10" was the escape before `04` at 1024 sps.
- [ ] **Step 4: Run** the new tests, then the full suite → only the 16 known failures.
- [ ] **Step 5: Commit** `fix(minimateplus): read a MiniMate's mode, sample rate, interval and record time after removing escapes (#1)`.
### Task 2: The Series-3 start read-back reconnects once after a dropped line (#9)
**Files:**
- Modify: `sfm/device_access/s3.py` — `change_monitoring`'s `read_state` (~line 230)
- Modify: `tests/device_access_fakes.py` — `FakeMiniMateClient`: add `read_serial()` (returns `serial_reported`, default the unit's serial; records `"read_serial"`) and `wake_errors=` (exceptions raised by successive `wake()` calls)
- Test: `tests/test_device_access_change.py`
**Interfaces:** Consumes `MiniMateClient.read_serial()` (exists), `normalise_serial` (`sfm/device_access/series.py`). No new public names.
Behaviour: in `read_state`, an `OSError` from `_woken_state(client)` (Broken pipe / reset / aborted — measured: `[Errno 32] Broken pipe` at BE9441's first wake after the sensor check) **on a TCP address, the first time only**: log a warning "the line dropped during the read-back — reconnecting to read the state (nothing is re-sent)", `client.close()`, `client.open()`, require `normalise_serial(client.read_serial()) == serial` (else raise `WrongUnit`), then `_woken_state(client)`. A second `OSError`, any other error, or a serial-cable address propagates as today.
- [ ] **Step 1: Write the failing tests**
```python
def test_series3_start_read_back_reconnects_after_a_dropped_line():
fake = FakeMiniMateClient(monitor_states=[False, True], wake_errors=[BrokenPipeError(32, "Broken pipe")])
r = access3(fake).start_monitoring(TCP3, "BE18193")
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring")
assert fake.writes == ["start_monitoring"] and fake.opened == 2 and "read_serial" in fake.calls
def test_series3_read_back_reconnects_only_once():
fake = FakeMiniMateClient(monitor_states=[False], wake_errors=[BrokenPipeError(32, "x")] * 2)
with pytest.raises(ChangeUnconfirmed): access3(fake).start_monitoring(TCP3, "BE18193")
assert fake.writes == ["start_monitoring"] and fake.opened == 2
def test_series3_read_back_reconnect_refuses_a_different_unit():
fake = FakeMiniMateClient(monitor_states=[False], wake_errors=[BrokenPipeError(32, "x")], serial_reported="BE11529")
with pytest.raises(ChangeUnconfirmed) as e: access3(fake).start_monitoring(TCP3, "BE18193")
assert e.value.http_status == 409 and fake.writes == ["start_monitoring"]
def test_series3_read_back_does_not_reconnect_on_a_serial_cable():
# address with port=, no host: opening a MiniMate's port reboots it
... assert fake.opened == 1 and raises ChangeUnconfirmed
def test_series3_read_back_silence_is_not_a_dropped_line():
fake = FakeMiniMateClient(monitor_states=[False], wake_errors=[NoAnswer("quiet")])
... raises ChangeUnconfirmed; fake.opened == 1; writes == ["start_monitoring"]
```
(`serial_reported` applies to `read_serial()` only; `connect()` keeps returning the real serial so the pre-send identity check passes. Use the module's existing `access3`, `TCP3` helpers; add a serial-cable `UnitAddress` beside `TCP3`.)
- [ ] **Step 2: Run** them → the reconnect tests FAIL (no reconnect today); the last two may already pass — keep them as guards.
- [ ] **Step 3: Implement** `read_state` as described (a closed-over `reconnected` flag).
- [ ] **Step 4: Run** `tests/test_device_access_change.py`, then the full suite → only the 16 known failures.
- [ ] **Step 5: Commit** `fix(sfm): a MiniMate start's read-back reconnects once when the modem dropped the line (#9)`.
### Task 3: MiniMate downloads are stored through the Blastware-file import path (#8)
**Files:**
- Modify: `minimateplus/blastware_file.py` — add `blastware_file_bytes(event: Event, a5_frames: list) -> bytes`; `write_blastware_file` writes its result (no behaviour change)
- Modify: `sfm/device_access/models.py` — `DownloadedEvent.bw_bytes: Optional[bytes] = field(default=None, repr=False)` (Series 3: the assembled Blastware file)
- Modify: `sfm/device_access/s3.py` — `download_event` fills `bw_bytes` from the verified event's frames
- Modify: `sfm/waveform_store.py` — `save_imported_bw(..., source_kind: str = "bw-import")` writes it into the sidecar's `source.kind`
- Modify: `sfm/event_ingest.py` — `persist_download`'s Series-3 branch
- Test: `tests/test_event_ingest.py`, `tests/test_5a_blastware_walk_histogram.py`
**Interfaces:** Produces `blastware_file_bytes(event, a5_frames) -> bytes`; `DownloadedEvent.bw_bytes`; `save_imported_bw(bw_bytes, source_path, *, serial_hint=None, bw_report_text=None, source_kind="bw-import") -> tuple[Event, dict]`.
Behaviour: Series 3 mirrors Series 4 — `ev, rec = store.save_imported_bw(dl.bw_bytes, source_path=Path(dl.filename), serial_hint=dl.serial, source_kind="sfm-live")`, then the existing `db.insert_events(...)`. No `backfill_series3_event` on this path (the file's setup block supplies sample rate and record time, #44/#45); no overlay of the live `0C` peaks (data comes from the binary — they stay the download *check*). A download with no `bw_bytes` raises `IngestError("…the download carried no event file; nothing was stored")`. The "Waveform" label on a live histogram stays until the checker session's #41 (record type from `STRT[18]`) lands on `dev`.
- [ ] **Step 1: Write the failing tests**
```python
# tests/test_5a_blastware_walk_histogram.py, beside the existing K441LTON.900 comparison:
def test_blastware_file_bytes_is_blastwares_file():
# the walk's frames for key 0111f210 -> blastware_file_bytes(ev, frames) == (FIX/"blastware"/"K441LTON.900").read_bytes()
# tests/test_event_ingest.py
def test_a_series3_histogram_download_is_stored_from_its_file(tmp_path):
bw = (HIST_FIX / "K441LTON.900").read_bytes() # byte-identical to SFM's download (sha f10f39a8…)
out = persist_download(DownloadedEvent(event_id="BE9441:0111f210:20261026170036", serial="BE9441",
series=3, filename="K441LTON.900", verified=None, bw_bytes=bw,
timestamp=datetime.datetime(2026, 10, 26, 17, 0, 36)), store=WaveformStore(tmp_path / "w"), db=SeismoDb(tmp_path / "s.db"))
# assert the stored file's sha256 == hashlib.sha256(bw).hexdigest()
# assert plot_json_from_hdf5(<h5>)["channels"]["Tran"]["values"] (non-empty: the histogram decoded)
# assert the sidecar's source.kind == "sfm-live" and the row's sample_rate == 4096
def test_the_small_mic_off_histogram_is_stored_with_samples(tmp_path): # K441LTOK.QZ0, refused on 10-29
def test_a_repeat_series3_download_adds_no_row(tmp_path): # persist twice: one row; second inserted False
def test_a_series3_download_with_no_file_stores_nothing_and_says_so(tmp_path) # replaces the no-event test
```
Rewrite `test_a_series3_event_is_backfilled_then_stored_as_series3` to the new contract (bytes in, `save_imported_bw` called with `source_kind="sfm-live"`, no backfill); keep `test_downloading_an_event_the_watcher_stored_writes_nothing_series3` passing unchanged.
- [ ] **Step 2: Run** them → FAIL (`bw_bytes` / `blastware_file_bytes` / `source_kind` do not exist).
- [ ] **Step 3: Implement** the five file changes above.
- [ ] **Step 4: Run** `tests/test_event_ingest.py tests/test_5a_blastware_walk_histogram.py tests/test_device_access_events.py tests/test_server_device_access.py`, then the full suite → only the 16 known failures.
- [ ] **Step 5: Commit** `fix(sfm): store a MiniMate download through the Blastware-file import path, as production does (#8)` — body states: new live downloads only; existing rows untouched; no backfill or migration.
### Task 4: Docs
**Files:** the spec (*Left open by the 1c bench*), `docs/instantel_protocol_reference.md` (CRLF — Edit tool), `CLAUDE.md` ("Where things stand").
- [ ] **Step 1:** Spec: mark #1, #8, #9 fixed (commit ids); **retract #15 in place** (by design: `sent` NULL = sent without acknowledgement); #2 fixed by the `dev` merge (`342c696`).
- [ ] **Step 2:** Instantel reference, a dated change-log row + §7.6.1 note: the measured logical `1A` layout (mode −7, rate −6, interval −4, record time +6 after unescaping; the old "anchor−7 constant 0x10" was the escape before `04`); while monitoring, BE9441 answered the `1A` reads with its device-info block (measured 2026-10-29); the channel block is read on raw bytes, so a trigger/alarm float containing `02/03/04/10` would read shifted — open, unmeasured.
- [ ] **Step 3:** CLAUDE.md: one line under the 1c entry — Batch 1 done (#1, #8, #9), #15 retracted.
- [ ] **Step 4: Commit** `docs: 1c bench Batch 1 -- #1, #8, #9 fixed; #15 retracted; the 1A layout after unescaping`.
@@ -0,0 +1,245 @@
# Phase 4 — Call-home enable/disable Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Turn a unit's automatic call-home on or off from SFM, for both series, through the audited change path start/stop already uses: identity check → audit → one send → read back → audit.
**Architecture:** `run_change` (`sfm/device_access/change.py`) becomes kind-agnostic: a `ChangeKind` says what the change is called and which state means it took. Each series supplies a call-home state read (`"enabled"` / `"disabled"`, plus Series 4's `"calling_home"`) and a send built from the block it read moments before. Series 4 sends `micromate.writes.plan_call_home_enabled` (frames already equal to THOR's). Series 3 patches byte 5 of the unescaped `0x2C` image and sends it through the existing `0x7E`/`0x7F` path. A gate keeps that send refused until its frame is reproduced from a Blastware capture. New serial-keyed routes, and the page's Call Home tab by serial gets On/Off buttons.
**Tech Stack:** Python 3 / FastAPI (SFM), pytest; page JS in `sfm/static/` tested with Node.
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` — row 9 of the job table, "The safety layer" (tiers, read-back: "call-home → re-read `0x2C` and compare the edited bytes"), the per-operation table (`call-home enable/disable | read 0x2C → 0x7E (126 B content, offset 0x007E) → 0x7F | re-read 0x2C`), build phase 4.
## Global Constraints
- Branch `feat/series4-sfm-parity`, worktree `~/seismo-relay-parity`. Never commit to `main`. Push every commit. No `CHANGELOG.md` edits (written on `dev` at merge).
- **No live write without Brian's explicit go, per send.** Dry runs and tests only, until the bench task.
- A write is never retried (`DeviceAccess._dispatch(change=True)`); never send `0xA2`; never write modem baud or modem type.
- File boundary with the decode-checker session: do not edit `minimateplus/event_file_io.py`, `histogram_codec.py`, `waveform_codec.py`, `bw_xml_report.py`, `decode_check*.py`.
- No inline JavaScript: new page logic goes in `sfm/static/device_routing.js` (DOM-free, Node-tested); `sfm/static/sfm_webapp.js` only applies it (stack-wide rule, 2026-11-02).
- Series 4: read-modify-write. Send back every byte of the block as read except bit 0 of `content[5]`. Never synthesise or zero `content[118:120]` (unit-maintained; it changes after a config write).
- Series 3: read the enable byte from the **unescaped** block (the lesson of bench finding #1). `0x00` off, `0x01` on (measured April 2026, BE11529). Any other value is `unknown(0xNN)` and nothing is sent.
- Speed is secondary to reliability: no new round trips beyond the reads the change needs.
- Test command: `/home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider`. Baseline: exactly 16 known failures (15 in `tests/test_bw_ascii_report.py`, `tests/test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`). Read the failure list before committing.
## Review Focus
1. A change requested while a Micromate is calling home (run state `0x03`) → 503, nothing sent, the line released (the existing `CallHomeInProgress` path).
2. A MiniMate whose unescaped byte 5 is neither `0x00` nor `0x01` → state `unknown(0xNN)`: a dry run still shows it, a live change sends nothing (`UnitStateUnknown`, 409).
3. A read-back where other bytes changed (Series 4 `[118:120]` always does) → verified on the edited bit alone; the changed offsets are recorded in the result and the audit row, never a mismatch.
4. Already in the requested state → skipped with no send, unless `even_if_already` (the bench's no-op write is exactly that experiment).
5. A live Series-3 call-home change before its frame has been reproduced from a Blastware capture → 501 before any connection. A dry run works.
---
### Task 1: `run_change` takes a `ChangeKind`
**Files:**
- Modify: `sfm/device_access/change.py` (signature and the three derived names at the top of `run_change`; the finish paths that build `detail` and `states`)
- Modify: `sfm/device_access/s3.py` (`change_monitoring`), `sfm/device_access/s4.py` (`s4_change_monitoring`) — call sites only
- Test: `tests/test_device_access_change_kind.py` (new)
**Interfaces:**
- Produces:
- `@dataclass(frozen=True) class ChangeKind: action: str; want: str; became: str` in `change.py`.
- `monitoring_change(start: bool) -> ChangeKind` gives exactly today's values: `("start monitoring", "monitoring", "started")` / `("stop monitoring", "idle", "stopped")`.
- `call_home_change(enabled: bool) -> ChangeKind` gives `("enable call-home", "enabled", "enabled")` / `("disable call-home", "disabled", "disabled")`.
- `run_change(*, kind: ChangeKind, serial, series, dry_run, even_if_already, audit, address, caller, sleep, verify_timeout_s, verify_interval_s, read_serial, read_state, describe_plan, send, is_refusal=_never, is_ring=_never, pre_send=None, snapshot: Optional[Callable[[], Dict[str, Any]]] = None) -> ChangeResult`. `start` is gone.
- `snapshot`: called once, after the read-back loop, on the two normal finish paths (verified `ok` or `mismatch`). Its dict goes in `detail["snapshot"]` and the audit row's `states["snapshot"]`. A snapshot that raises is recorded as `{"error": str(exc)}` and does not change the outcome.
- [ ] **Step 1: Write the failing tests** (fake callables, no device, the `Audit` fake pattern from `tests/test_device_access_change.py`):
- `test_monitoring_kinds_are_todays_names`: `monitoring_change(True) == ChangeKind("start monitoring", "monitoring", "started")`, and likewise for stop.
- `test_a_call_home_change_is_verified_by_its_own_state`: `kind=call_home_change(False)`, states `["enabled", "disabled"]` → `(outcome, verified, state_after) == ("sent", "ok", "disabled")`, and `result.action == "disable call-home"`.
- `test_a_call_home_read_back_that_did_not_change_is_a_mismatch`: states `["enabled", "enabled", "enabled", "enabled"]` with verify `(3.0, 1.0)` → `("failed", "mismatch")`.
- `test_the_snapshot_is_kept_in_the_result_and_the_audit`: `snapshot=lambda: {"after": "ab"}` → `result.detail["snapshot"] == {"after": "ab"}` and the audit row's `states["snapshot"] == {"after": "ab"}`.
- `test_a_failing_snapshot_does_not_change_the_outcome`: a snapshot raising `RuntimeError("x")` → still `("sent", "ok")`, `detail["snapshot"] == {"error": "x"}`.
- [ ] **Step 2: Run** `pytest tests/test_device_access_change_kind.py -v`. Expected: FAIL (`ImportError: cannot import name 'ChangeKind'`).
- [ ] **Step 3: Implement.** Replace `start` with `kind` in `run_change`, deriving `action`, `want` and `became` from `kind`. Add the snapshot as specified. Update the two call sites to `kind=monitoring_change(start)`, keeping their own `start` parameter.
- [ ] **Step 4: Run** the new file plus `tests/test_device_access_change.py tests/test_device_access_s3_events.py tests/test_server_device_access.py`. Expected: all pass, with the existing start/stop tests unchanged.
- [ ] **Step 5: Commit** `refactor(sfm): run_change takes a ChangeKind -- start/stop unchanged, call-home next (phase 4)`.
### Task 2: Series 4 — read call-home, change it
**Files:**
- Modify: `micromate/opcodes.py` (`ENABLEABLE_WRITES`), `micromate/client.py` (new method)
- Modify: `sfm/device_access/models.py` (new `CallHomeState`), `sfm/device_access/s4.py` (two new functions)
- Modify: `tests/device_access_fakes.py` (`FakeMicromateClient` call-home support), `tests/test_micromate_execute.py:37` (the ceiling assertion)
- Test: `tests/test_device_access_s4_call_home.py` (new)
**Interfaces:**
- Consumes: Task 1's `ChangeKind`, `call_home_change`, `run_change(snapshot=…)`.
- Produces:
- `ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F})`.
- `MicromateClient.get_call_home_content() -> bytes`: the 126-byte content, `_content(self.protocol.read_call_home_config())`.
- `@dataclass class CallHomeState: serial: str; series: int; enabled: Optional[bool]; dial_string: Optional[str]; detail: Dict[str, Any]` (`detail["byte5"]` as `"0xNN"`, `detail["block"]` as hex).
- `s4_call_home_state(client, serial) -> CallHomeState`: enabled is bit 0 of `content[5]`; the dial string is `content[6:46]` up to its first NUL, decoded as ASCII.
- `s4_change_call_home(client, serial, *, enabled, dry_run, even_if_already, audit, address, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`:
- `read_state` returns `"calling_home"` when `client.read_run_state().name == "calling_home"`, else `"enabled"` / `"disabled"` from `content[5] & 1`. It keeps the last content it read.
- `describe_plan`: `plan_call_home_enabled(last_content, enabled).describe()`, so the plan is built from the read `run_change` made just before.
- `send` executes that same plan object.
- `snapshot` returns `{"before": hex, "after": hex, "changed_offsets": [...]}`, comparing the first and last content read.
- `pre_send`, `is_refusal` and `is_ring` are as in `s4_change_monitoring`.
- [ ] **Step 1: Fake support.**
- `FakeMicromateClient(call_home=<126-byte content>)`, defaulting to UM12947's enabled read from `tests/fixtures/micromate-writes` (the reads `tests/test_micromate_writes.py::_call_home_reads` uses), plus a `read_call_home_config()` on `_FakeProtocol` returning `bytes(11) + content`.
- `execute(plan)` applies a `0x7E` step's data as the new content, then replaces `[118:120]` with its bitwise complement, mimicking the unit-maintained field (the default read already holds `2e 5e`, so a fixed value would not change it).
- [ ] **Step 2: Write the failing tests:**
- `test_s4_call_home_state_reads_the_enable_bit_and_dial_string`: on the default content (UM12947, `[5] = 0x05`) → `enabled is True`, `dial_string == "RADIO RING"`, `detail["byte5"] == "0x05"`.
- `test_s4_dry_run_shows_thors_frames`: dry run `enabled=False` → `result.plan` frames equal `plan_call_home_enabled(content, False).describe()["steps"]` frames, and `fake.executed == []`.
- `test_s4_disable_sends_7e_7f_and_verifies`: live `enabled=False` → `("sent", "ok", "disabled")`; executed plan subs `[0x7E, 0x7F]`.
- `test_s4_unit_maintained_bytes_do_not_make_a_mismatch`: same run → `verified == "ok"` and `detail["snapshot"]["changed_offsets"] == [5, 118, 119]`.
- `test_s4_no_change_while_calling_home`: `run_states=[0x03]` → `CallHomeInProgress`, nothing executed.
- `test_s4_already_enabled_is_skipped`: `enabled=True` on enabled content → `outcome == "skipped"`, nothing executed. With `even_if_already=True` → executed once, and the plan carries the "changes nothing" warning.
- Update `test_micromate_execute.py:37` to the new four-SUB set.
- [ ] **Step 3: Run** the new file. Expected: FAIL (`ImportError: s4_call_home_state`).
- [ ] **Step 4: Implement** as specified in Interfaces.
- [ ] **Step 5: Run** the new file plus `tests/test_micromate_execute.py tests/test_micromate_writes.py tests/test_device_access_change.py`. Expected: pass.
- [ ] **Step 6: Commit** `feat(sfm): Series-4 call-home state and audited enable/disable (phase 4)`.
### Task 3: Series 3 — read call-home, change it (live send gated)
**Files:**
- Modify: `minimateplus/protocol.py` (two pure functions next to `write_image`), `minimateplus/client.py` (two methods)
- Modify: `sfm/device_access/s3.py` (gate constant + two adapter methods)
- Modify: `tests/device_access_fakes.py` (`FakeMiniMateClient` call-home support)
- Test: `tests/test_s3_call_home.py` (new)
**Interfaces:**
- Consumes: Task 1, and Task 2's `CallHomeState`.
- Produces:
- `call_home_enabled(raw: bytes) -> Optional[bool]` in `minimateplus/protocol.py`: `unescape_reply(raw)[5]`, `0x01` → True, `0x00` → False, else None.
- `call_home_image(raw: bytes, enabled: bool) -> bytes`: `write_image(SUB_CALL_HOME_WRITE, raw)` with byte 5 set to `0x01`/`0x00` and every other byte unchanged. Raises `ValueError` when the image's byte 5 is not `0x00`/`0x01`.
- `MiniMateClient.read_call_home_raw() -> bytes` (the protocol's `read_call_home_config()`) and `MiniMateClient.write_call_home_image(image: bytes) -> None` (the protocol's `write_call_home_config(image)`: `0x7E` then `0x7F`, each ack checked).
- `S3_CALL_HOME_FRAME_VERIFIED = False` in `sfm/device_access/s3.py`. Task 4 flips it.
- `Series3Adapter.call_home_state(address, serial) -> CallHomeState`: `wake`, then `read_call_home_raw()`. The dial string is the unescaped `[6:46]` up to its first NUL. `detail` carries `byte5`, `block` (raw hex) and `serial_verified: False`, as status does.
- `Series3Adapter.change_call_home(address, serial, *, enabled, dry_run, even_if_already, audit, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`:
- When `not dry_run and not S3_CALL_HOME_FRAME_VERIFIED`, raise `NotSupported("a MiniMate call-home write waits until its frame has been reproduced from a Blastware capture -- nothing sent")` before `_run`.
- Otherwise use `run_change(kind=call_home_change(enabled), retry=False)` with:
- `read_serial` = `client.connect()`, as for start/stop;
- `read_state` = `wake` + `read_call_home_raw()`, giving `enabled` / `disabled` / `unknown(0xNN)` and keeping the last raw;
- `describe_plan` = the steps `[{"sub": "0x7E", "frame": build_bw_write_frame(0x7E, image).hex()}, {"sub": "0x7F", "frame": build_bw_write_frame(0x7F, b"").hex()}]`;
- `send` = `client.write_call_home_image(image)`, returning `{"subs": ["0x81", "0x80"]}`;
- `snapshot` as in Task 2, over unescaped images.
- [ ] **Step 1: Fake support.**
- `FakeMiniMateClient(call_home_raw=<125 B>)`. The default is built from the documented 4-20-26 layout: `00 7C DC 00 00`, `[5] = 0x01`, `[6:46] = b"RADIO RING"` NUL-padded, `[117:119] = 10 03`, zeros elsewhere to 125 bytes.
- `read_call_home_raw()` steps and returns it.
- `write_call_home_image(image)` records `self.writes.append("call_home")` and stores the image for the next read.
- [ ] **Step 2: Write the failing tests:**
- `test_s3_enable_byte_reads_from_the_unescaped_block`: on the default raw → `call_home_enabled(raw) is True`. A raw with an escape spliced in before byte 5 (`00 7C 10 03 00 00 01 …`) still reads True.
- `test_s3_image_changes_only_byte_5`: `call_home_image(raw, False)` differs from `write_image(0x7E, raw)` at index 5 only, and its length is 126 (N `0x7C` + 2).
- `test_s3_image_refuses_an_unknown_byte_5`: raw with unescaped `[5] = 0x07` → `ValueError`.
- `test_s3_call_home_state`: through `Series3Adapter` with the fake → `enabled is True`, `dial_string == "RADIO RING"`, `detail["serial_verified"] is False`; the calls include `"wake"` before `"read_call_home_raw"`.
- `test_s3_live_change_is_refused_until_the_frame_is_verified`: `dry_run=False` → `NotSupported` (501), the factory never called.
- `test_s3_dry_run_shows_both_frames`: `dry_run=True` → plan steps `0x7E`/`0x7F`, `fake.writes == []`.
- `test_s3_change_once_verified` (monkeypatch `S3_CALL_HOME_FRAME_VERIFIED = True`): live `enabled=False` → `("sent", "ok", "disabled")`, `fake.writes == ["call_home"]`, `detail["snapshot"]["changed_offsets"] == [5]`.
- `test_s3_unknown_byte_5_sends_nothing` (gate open): raw with `[5] = 0x07` → `UnitStateUnknown`, no write.
- [ ] **Step 3: Run** the new file. Expected: FAIL (`ImportError: call_home_enabled`).
- [ ] **Step 4: Implement** as specified.
- [ ] **Step 5: Run** the new file plus `tests/test_device_access_change.py tests/test_server_series3_guard.py`. Expected: pass.
- [ ] **Step 6: Commit** `feat(sfm): Series-3 call-home state and audited enable/disable, live send gated until its frame is verified (phase 4)`.
### Task 4: Reproduce Blastware's Series-3 call-home write (opens the gate)
**Precondition:** Brian has found a capture of Blastware changing call-home settings, from the BW VM (CLAUDE.md names it `4-20-26/call home settings/`, BE11529), and copied the BW-TX and S3-RX files into `tests/fixtures/s3-call-home-bw/`. **If no capture exists, skip this task.** The gate stays shut, the Series-3 half of the bench (Task 7) starts by recording one, and this task runs after it.
**Files:**
- Create: `tests/fixtures/s3-call-home-bw/` (Brian's files, added with `git add -f` if they match an ignore rule) and `tests/test_s3_call_home_bw_frames.py`
- Modify: `sfm/device_access/s3.py` (`S3_CALL_HOME_FRAME_VERIFIED = True`, with a comment naming the test)
- [ ] **Step 1: Write the test** `test_sfm_builds_blastwares_call_home_write`:
1. Parse the S3-RX file with `S3FrameParser`, taking each `0xD3` data reply (`data[11:]`) in order. Parse the BW-TX file for the `0x7E` and `0x7F` request frames, using the #46 parser in `tests/test_minimate_write_frames.py` (`_frames`, `_payload`; import or copy them).
2. For each `0x7E`, work out what Blastware asked for: the unescaped byte 5 of its image.
3. Assert `build_bw_write_frame(0x7E, call_home_image(prev_read, wanted)) == bw_7e_frame` and `build_bw_write_frame(0x7F, b"") == bw_7f_frame`.
4. If Blastware also changed fields other than byte 5 in that write, assert only on writes where byte 5 is the sole difference from the read, and record the count.
- [ ] **Step 2: Run it.** Expected: PASS, with at least one write asserted. A FAIL means SFM's frame is not Blastware's: stop, record the byte differences in the spec's phase-4 notes, and leave the gate shut.
- [ ] **Step 3: Flip the gate**, then run `tests/test_s3_call_home.py`. The "refused until verified" test now fails by design: change it to assert the gate's comment names this test, and keep the monkeypatched tests.
- [ ] **Step 4: Commit** `test(s3): SFM's call-home write equals Blastware's, frame for frame -- opens the live send`.
### Task 5: DeviceAccess and the serial routes
**Files:**
- Modify: `sfm/device_access/access.py` (two methods, two constants), `sfm/server.py` (three routes, `_SERIAL_AWARE_PATHS`)
- Test: `tests/test_device_access_call_home.py`, plus additions to `tests/test_server_device_access.py`
**Interfaces:**
- Consumes: Tasks 2 and 3.
- Produces:
- `DeviceAccess.call_home_state(address, serial) -> CallHomeState` (a read, via `_dispatch`).
- `DeviceAccess.set_call_home(address, serial, *, enabled: bool, dry_run=False, even_if_already=False, caller="api") -> ChangeResult` (`change=True`). It uses `_CALL_HOME_VERIFY_TIMEOUT_S = 3.0` and `_CALL_HOME_VERIFY_INTERVAL_S = 1.0`, at most 3 read-backs one second apart, not the monitoring window.
- Routes:
- `GET /device/call_home/state?serial=&host=&tcp_port=` → the `CallHomeState` as a dict.
- `POST /device/call_home/enable` and `/device/call_home/disable`, taking `serial` (required), `host`, `tcp_port`, `dry_run`, `even_if_already` and `caller`, through `_change_response`. The statuses are the start/stop route's, including Batch 2's `sent`/`audit_id` on an unconfirmed change.
- All three go in `_SERIAL_AWARE_PATHS`. The legacy `GET`/`POST /device/call_home` stay unchanged, and outside that set.
- [ ] **Step 1: Write the failing tests:**
- `test_set_call_home_dispatches_by_series`: a `UM` serial reaches the S4 function and a `BE` serial the S3 adapter, using the fakes from Tasks 2 and 3.
- `test_set_call_home_is_never_retried`: an S4 held line that drops → raised, executed once.
- `test_call_home_routes_need_a_serial`: no `serial` → 422.
- `test_enable_route_returns_the_change_result`: a fake access → 200 and the body's `action == "enable call-home"`.
- `test_legacy_call_home_post_still_refuses_a_micromate_serial`: `_device_guard("/device/call_home", {"serial": "UM20147"})` → 501, unchanged.
- `test_call_home_routes_are_serial_aware`: the three new paths are in `_SERIAL_AWARE_PATHS`.
- [ ] **Step 2: Run.** Expected: FAIL (`AttributeError: set_call_home`).
- [ ] **Step 3: Implement**, mirroring `start_monitoring` / `device_monitor_start`.
- [ ] **Step 4: Run** the new and modified test files plus `tests/test_server_series3_guard.py`. Expected: pass.
- [ ] **Step 5: Commit** `feat(sfm): call-home state and enable/disable by serial -- GET /device/call_home/state, POST /device/call_home/{enable,disable} (phase 4)`.
### Task 6: The page — Call Home by serial
**Files:**
- Modify: `sfm/static/device_routing.js` (routes, `controlsFor`, `serialPanes`, `changeErrorText`, new `callHomeRows`), `sfm/static/sfm_webapp.js` (glue), `sfm/sfm_webapp.html` (a state box and two buttons in the Call Home tab)
- Test: `tests/test_webapp_device_routing.py`, plus a jsdom run of `page_files_load.js` in the scratchpad (not committed)
**Interfaces:**
- Consumes: Task 5's routes and Batch 2's `serialPanes` / `changeErrorText`.
- Produces:
- `DEVICE_ROUTES`:
- `call_home_state: ['GET', '/device/call_home/state', true]`
- `call_home_on: ['POST', '/device/call_home/enable', true]`
- `call_home_off: ['POST', '/device/call_home/disable', true]`
- `controlsFor(unit).callHomeChange = serialMode && (series === 3 || series === 4)`. `callHomeWrite` (the legacy multi-field form) stays `false`, with `reasons.callHomeWrite = 'By serial: use Call-home On / Off (audited). Other call-home fields wait for the THOR round.'`
- `serialPanes(...)` gains `callHomeForm: !bySerial` and `callHomeBox: bySerial`. Batch 2's existing test gets the two keys added.
- `changeErrorText(label, status, body, unit, statusText)` takes the whole label (`"Start monitoring"`, `"Enable call-home"`) and returns `` `${label} not confirmed: …` `` / `` `${label} failed: …` ``. Update its two callers and Batch 2's test.
- `callHomeRows(state) -> [[label, value], …]` returns:
- `['Call-home', 'On' | 'Off' | 'Unknown (byte 5 = 0xNN)']`
- `['Dial string', … or '—']`
- `['Series', 3 | 4]`
- [ ] **Step 1: Write the failing Node tests:**
- `test_call_home_routes_need_a_serial`: `deviceUrl('call_home_on', BLANK)` → null; with S4 → `{method: 'POST', path: '/device/call_home/enable?serial=UM20147&host=h&tcp_port=9034'}`.
- `test_call_home_change_needs_a_confirmed_series`: typed but unconfirmed → false; confirmed 3 → true; confirmed 4 → true; legacy → false.
- `test_call_home_rows`: `{enabled: true, dial_string: 'RADIO RING', series: 4}` → `[['Call-home','On'],['Dial string','RADIO RING'],['Series',4]]`; `{enabled: null, detail: {byte5: '0x07'}, series: 3}` → first row `['Call-home','Unknown (byte 5 = 0x07)']`.
- Update the `changeErrorText` and `serialPanes` tests to the new shapes.
- [ ] **Step 2: Run** `pytest tests/test_webapp_device_routing.py`. Expected: FAIL (`callHomeRows` is not defined).
- [ ] **Step 3: Implement the routing functions**, then the glue:
- By serial, the Call Home tab hides the legacy form and shows the state box via `serialPanes`, in `applyControls`.
- `readCallHome()` uses `call_home_state` and renders `callHomeRows`.
- `changeCallHome(on)` asks `confirm()` with the serial and on/off, sends `call_home_on`/`call_home_off`, reports with `changeSummary` / `changeErrorText('Enable call-home' | 'Disable call-home', …)`, then re-reads the state.
- The buttons are enabled by `controlsFor().callHomeChange`.
- HTML: `#ch-state` (a `dev-table`), `#ch-on-btn` and `#ch-off-btn` inside a `#ch-serial` box; the existing form goes in `#ch-legacy`.
- [ ] **Step 4: Run** the Node tests (pass), then the jsdom check. Extend `page_files_load.js` with:
- S4: Call Home read → rows shown, legacy form hidden;
- Off → `POST /device/call_home/disable?serial=UM20147…` sent after confirm, status from `changeSummary`;
- legacy mode: form shown;
- no script errors.
- [ ] **Step 5: Commit** `feat(sfm): the page's Call Home tab by serial -- state and audited On / Off (phase 4)`.
### Task 7: Docs, and the bench session (Brian's go per send)
**Files:**
- Modify: the spec (a "Phase 4" entry after phase 3's under Build phases), `CLAUDE.md` ("Where things stand"), and `docs/micromate_protocol_reference.md` / `docs/instantel_protocol_reference.md` (CRLF: Edit tool or byte-safe writes) for whatever the bench measures
- [ ] **Step 1: Docs before the bench.**
- Spec: what was built, with commit IDs; the gate's state; the bench questions below.
- CLAUDE.md: one status line.
- Commit `docs: phase 4 built -- call-home enable/disable by serial; bench questions`.
- [ ] **Step 2: Bench, UM20147 on its modem, idle.** One send per go:
- (a) dry run `disable`, showing frames and warnings, including "0x00 is unobserved";
- (b) `enable` with `even_if_already` (the no-op write: does a Micromate accept it?);
- (c) `disable`: read-back, the unit's screen, and the snapshot's changed offsets;
- (d) `enable`, back to how it was.
- Record each audit id and `[118:120]` before/after.
- [ ] **Step 3: Bench, BE9441 on its modem, idle.**
- If Task 4 did not run: first record Blastware changing call-home on BE9441 through the bridge, then run Task 4.
- Then (a) to (d) as above.
- [ ] **Step 4: One unit monitoring** (Brian picks which): a dry run, then one `disable` / `enable` pair. This settles whether a unit accepts a call-home write while monitoring. Unmeasured; nothing in the code assumes either answer.
- [ ] **Step 5: Record the results** in the spec and the protocol references (measured, with audit ids), and commit `docs: phase 4 bench -- call-home on/off on both series`.
@@ -0,0 +1,525 @@
# Phase 5: Changing a Unit's Settings by Serial — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** An operator edits a unit's live settings in SFM, by serial, on either series: preview old → new, send once (audited), and see what the unit now holds.
**Architecture:**
- **One pure settings codec for both series** (`micromate/setup_fields.py`), on the measured shared 2,090-byte layout.
- **Each series' adapter supplies reads, the plan and the send** to the existing `run_change` core, unchanged.
- Its "state" is a read-back verdict: `as asked` / `unchanged` / `differs`.
- Series 3 sends through `push_config_raw`; Series 4 through `plan_setup_push`.
- Series 4 also reads the unit's schedule, read-only, to refuse a change that a scheduled start would undo.
- **One audited route**, `POST /device/settings/change`. The legacy by-host write is retired.
**Tech Stack:** Python 3 (FastAPI, pytest), vanilla JS tested in Node (`tests/test_webapp_device_routing.py`).
**Spec:** `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md` (approved by Brian 2026-11-03). Parent spec: `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`.
## Global Constraints
- **Worktree and branch:** work in `~/seismo-relay-parity` on `feat/series4-sfm-parity`. Check `git branch --show-current` before every commit; never commit to `main`; push every commit.
- **Python:** `/home/serversdown/seismo-relay/.venv/bin/python -m pytest …` from the worktree root.
- **The suite has 16 known failures.**
- Run the full suite once before Task 1 and save the failure list in the plan workspace as `baseline-failures.txt`.
- Before every commit, run the suite, read the failure list, and confirm it equals the baseline.
- Commit in a separate call, never chained to the test run.
- **No live device traffic** in any task. The bench is after the final review, with Brian's explicit go per send.
- Never port 8200.
- Never write modem baud or modem type.
- Never send `0xA2`.
- **`CHANGELOG.md` is not touched** on this branch; it is written on `dev` at the merge.
- **No inline JavaScript.** New page logic goes in `sfm/static/device_routing.js` (DOM-free, Node-tested); glue goes in `sfm/static/sfm_webapp.js`.
- **`docs/instantel_protocol_reference.md` is CRLF.** Edit it only with the Edit tool. Keep its rows in date order.
- **Off-limits (the checker session's files):** `minimateplus/event_file_io.py`, `histogram_codec.py`, `waveform_codec.py`, `bw_xml_report.py`, `decode_check*.py`.
- **`TOOL_VERSION` is unchanged:** nothing here changes event decoding. Operational consequence: none; no migration, no backfill.
- **Grade every protocol claim** in comments and docs as measured or inferred.
- **Mutation checks:** after a mutate/restore, delete the module's `__pycache__/*.pyc` before the confirming run.
## Review Focus
1. **A Micromate with no schedule file, or a schedule read that fails.**
- A body with no records means no conflict, and the change proceeds.
- A read that raises refuses the change in plain words.
- Owner: Task 4; tests `test_no_schedule_records_is_no_conflict` and `test_an_unreadable_schedule_refuses`.
2. **A float that is stored as f32.** 0.3 reads back as 0.30000001192.
- The verdict compares bytes with the image written, never floats, so it reads `as asked`.
- Owner: Task 2; test `test_f32_values_read_back_as_asked`.
3. **A stale or foreign revision** after a keypad edit, or a preview of another unit.
- The send is refused with 409, nothing is sent, and no audit row is written.
- Owner: Tasks 4 and 5; tests `test_s4_stale_revision_sends_nothing` and `test_s3_stale_revision_sends_nothing`.
4. **Range and trigger changed in one request.** The trigger is checked against the **new** range.
- Owner: Task 2; test `test_trigger_checked_against_the_new_range`.
5. **Notes at the edges.**
- `""` clears a note.
- 41 bytes is accepted; 42 is refused; non-ASCII is refused.
- Labels are never written.
- Owner: Task 2; tests `test_note_edges` and `test_note_labels_are_never_written`.
---
## File Structure
| file | responsibility |
|---|---|
| `minimateplus/protocol.py` | **Series 3 assembly:** `assemble_compliance_content`, `is_compliance_content`, `MiniMateProtocol.read_compliance_content`. **Writes:** `push_config_raw`'s pre-check raises `ImageRefused`. |
| `minimateplus/client.py` | **Added:** `read_compliance_content()` and `read_settings_blocks()`. **Deleted:** `apply_config`, `set_project_info`, `_encode_compliance_config`. |
| `micromate/setup_block.py` | **Added:** `with_crc(content)`. |
| `micromate/setup_fields.py` (new) | **The shared, pure settings codec:** field registry, `editable_fields`, `check_changes`, `encode_setup`, `field_values`, `settings_state`, `revision`. |
| `micromate/schedule.py` (new) | **Pure:** `parse_schedule`, `ScheduleEntry`, `schedule_conflicts`. |
| `micromate/protocol.py` | **Added:** `read_file(path)`, using `0x94` then `0x48` pages. |
| `micromate/client.py` | **Added:** `read_schedule()`, `get_active_setup_raw()`, `get_prefs_content()`, `get_trigger_content()`, `get_setup_content()`. |
| `micromate/opcodes.py` | `ENABLEABLE_WRITES` gains the setup-push SUBs. |
| `sfm/device_access/errors.py` | **Added:** `SettingsChanged` and `ChangeRefused`, both 409. |
| `sfm/device_access/change.py` | **Added:** `settings_change()`. |
| `sfm/device_access/s4.py` | `s4_settings` moves onto the codec. **Added:** `s4_change_settings`. |
| `sfm/device_access/s3.py` | `Series3Adapter.settings` moves onto the codec. **Added:** `Series3Adapter.change_settings`. |
| `sfm/device_access/access.py` | **Added:** `DeviceAccess.change_settings`. |
| `sfm/server.py` | **Added:** `POST /device/settings/change`. `/device/config` and `/device/config/project` return 410. |
| `sfm/static/device_routing.js`, `sfm/static/sfm_webapp.js`, `sfm/sfm_webapp.html` | The edit form. |
| `tests/device_access_fakes.py` | The fakes gain settings blocks, a schedule, and writes. |
---
### Task 1: Series 3 — assemble a settings read into the logical block
**Measured basis (spec, 2026-11-03):** unescape each `1A` data frame and take `data[11:]`. Every frame but the last starts with one non-content `00` byte; drop it. The result is 2,090 bytes with `N = 2090` at `[0:2]`.
**Files:**
- Modify: `minimateplus/protocol.py`, near `read_compliance_config` (≈ line 913)
- Modify: `minimateplus/client.py`
- Modify: `docs/instantel_protocol_reference.md` (one dated row, 2026-11-03)
- Test: `tests/test_s3_settings_read.py` (new)
**Interfaces:**
- Produces:
- `assemble_compliance_content(frames: list[bytes]) -> bytes`. `frames` is each data reply's `frame.data`, escapes kept, in order.
- `is_compliance_content(block: bytes) -> bool`: `len == 2090` and `int.from_bytes(block[0:2], "big") == 2090`.
- `COMPLIANCE_CONTENT_LEN = 2090`.
- `MiniMateProtocol.read_compliance_content() -> bytes`:
- sends the same probe and B/C/D requests as `read_compliance_config`;
- a missing data frame raises `ProtocolError` (no `continue`);
- returns the assembled bytes **without** judging them, so a monitoring unit's device-info answer comes back for the caller to recognise.
- `MiniMateClient.read_compliance_content() -> bytes`.
- `MiniMateClient.read_settings_blocks() -> dict` with keys `event_index`, `compliance`, `trigger` and `waveform`. Each value is the bytes its existing read returns:
- `event_index`: `proto.read_event_index()`
- `compliance`: `read_compliance_content()`
- `trigger`: `proto.read_trigger_config()`
- `waveform`: `proto.read_waveform_data_raw()`
- [ ] **Step 1: Write the failing tests** in `tests/test_s3_settings_read.py`. Use `tests/fixtures/minimate-bench-10-26-26-histogram` (`unit_replies.bin` parsed with `S3FrameParser`). Group the `0xE5` frames into reads: a frame with `len(data) == 11` starts each read. Take the write images from `tests/test_minimate_write_frames.py` (`WRITES[0:13]`, `WRITES[13:26]`; the `0x71` payloads `[16:]` joined).
```python
def test_reads_assemble_to_2090_bytes(): # all 12 reads, both frame patterns (5 and 3 frames)
assert all(len(assemble_compliance_content(r)) == 2090 for r in READS)
def test_a_read_after_a_blastware_write_equals_the_write():
assert assemble_compliance_content(READS[1]) == IMAGES[0][:2090]
assert assemble_compliance_content(READS[2]) == IMAGES[1][:2090]
def test_a_monitoring_units_answer_is_not_settings(): # READS[3:8] start 0e 'BE9441'
assert [is_compliance_content(assemble_compliance_content(r)) for r in READS[3:8]] == [False] * 5
assert all(is_compliance_content(assemble_compliance_content(r)) for r in READS[:3] + READS[8:])
def test_read_compliance_content_refuses_a_missing_frame():
... # a fake transport that answers the probe and frame B, then times out: ProtocolError, nothing assembled
```
- [ ] **Step 2: Run them.** `…pytest tests/test_s3_settings_read.py -q`. Expected: FAIL (ImportError: `assemble_compliance_content`).
- [ ] **Step 3: Implement** the Produces block in `protocol.py` and `client.py`. Use `unescape_reply` from `minimateplus.framing`. The docstring cites the measurement and its fixture.
- [ ] **Step 4: Run them.** Expected: PASS (4 passed).
- [ ] **Step 5: Add a reference row** to `docs/instantel_protocol_reference.md` (Edit tool; CRLF), dated 2026-11-03, measured. Cover:
- the assembly rule;
- the round trip (2 of 2);
- `[26:28]`: Blastware writes `00 00` (11 of 11), and the unit sets `01 7f` after monitoring;
- the trailing two bytes: a per-unit Blastware constant (`7c ea` BE11529 ×9, `0c e9` BE9441 ×2), not the CRC, and never in a reply;
- `0x09 [200:202]`: echoed 9 of 9 in April; changed on 10-26 (`17 17` → `78 76`).
- [ ] **Step 6: Run the full suite** and compare the failure list with the baseline. **Then commit** (separate call): `feat(s3): assemble a settings read into the 2,090-byte block`.
---
### Task 2: The shared settings codec
**Files:**
- Create: `micromate/setup_fields.py`
- Modify: `micromate/setup_block.py`: add `with_crc(content: bytes) -> bytes`, which returns the content with `CRC-16/AUG-CCITT` over `[0:N-2]` written BE at `[N:N+2]`.
- Test: `tests/test_setup_fields.py` (new)
**Interfaces:**
- Consumes: Task 1's `assemble_compliance_content`, used in tests only. The codec itself imports nothing from `minimateplus` and nothing from `sfm`.
- Produces (all pure). Each `content` is the 2,090-byte (Series 3) or 2,092-byte (Series 4) block.
- `editable_fields(content: bytes, series: int) -> list[dict]`. Each dict has `field`, `label`, `kind` (`"number"`, `"choice"`, `"text"` or `"bool"`) and `value`, plus as relevant `unit`, `min`, `max`, `choices` (a list of `{value, label}`) and `maxlength`.
- `field_values(content: bytes, series: int) -> dict[str, Any]`: the same fields, values only.
- `check_changes(content: bytes, series: int, changes: dict) -> dict`: returns the normalised changes, or raises `SettingsValueError(ValueError)` with a plain sentence. It has two kinds of check: static (names, types, choices, limits) and content-dependent (unit strings, the trigger against the range).
- `encode_setup(content: bytes, series: int, changes: dict) -> bytes`:
- same length as `content`;
- only the changed fields' bytes move;
- bit fields are patched bit by bit;
- Series 3 also sets `[26:28] = 00 00` (`S3_BLASTWARE_FIXED`);
- Series 4 returns `with_crc(...)`.
- `settings_state(before: bytes, written: bytes, now: bytes, *, series: int) -> str`. It compares `[0:2090]`:
- `"as asked"` if `now` equals `written` (Series 4 also needs `crc_ok(now)`);
- else `"unchanged"` if `now` equals `before`;
- else `"differs"`.
- `revision(blocks: list[bytes]) -> str` = `hashlib.sha256(b"".join(blocks)).hexdigest()[:16]`.
- `S3_ALARM_WRITE_MEASURED = False`. While False, `geo_alarm_ips` is shown (read-only, `kind` plus `"readonly": True`) and refused in `check_changes`.
**The field registry** (content offsets; channel `k` = `1708 + 48·k`, `k` = 0, 1, 2 for the geophones):
| field | series | bytes | values (exact) |
|---|---|---|---|
| `record_mode` | 3 | `[5]` | `single_shot`=0, `continuous`=1, `histogram`=3, `histogram_continuous`=4 |
| `record_mode` | 4 | `[5]` | `waveform`=1, `manual`=2, `histogram`=3, `combo`=4 |
| `sample_rate` | 3, 4 | `[6:8]` u16 BE | {1024, 2048, 4096} |
| `histogram_interval_s` | 3, 4 | `[8:10]` u16 BE | {2, 5, 15, 60, 300, 900} |
| `record_time_s` | 3 | `[18:22]` f32 BE | 1.0 ≤ v ≤ `S3_MAX_RECORD_S[sample_rate]` = {1024: 104, 2048: 52, 4096: 26}, and ≤ 13 when `record_mode` is `histogram_continuous` (the **new** mode and rate if they change too) |
| `record_time_s` | 4 | `[18:22]` f32 BE | 1.0 ≤ v ≤ 90.0 |
| `geo_trigger_ips` | 3, 4 | ch k `+30` f32 BE, all three | 0.005 ≤ v ≤ 10.0, a multiple of 0.001 (within 1e-9), and ≤ the (new) range's full scale (10.0 / 1.25) |
| `geo_range` | 3 | ch k `+29` u8, all three | `normal`=0, `sensitive`=1 |
| `geo_alarm_ips` | 3 (gated) | ch k `+38` f32 BE, all three | 0.005 ≤ v ≤ full scale |
| `job_number` | 3, 4 | `[40:42]` u16 BE | 1 ≤ v ≤ 9999 |
| `job_number_shown` | 3, 4 | `[39]` bit `0x02` | bool |
| `note_1` … `note_4` | 3, 4 | value `[144+64n : 186+64n]`; label `[122+64n : 144+64n]` read only | printable ASCII 0x20–0x7E, ≤ 41 bytes, zero-filled to 42 |
The limits are **the units' own, from Instantel's manuals** (Brian, 2026-11-03), cited in the module as comments:
- **Trigger** 0.005–10 in/s, steps of 0.001: MiniMate Plus manual 716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual 721U0201 Rev 06, *Geophone Trigger Level*.
- **Record time:**
- Micromate 1–90 s (*Record Time*).
- MiniMate: §4.4's *Maximum Record Times*, 1 MB unit, channels 1–4; §3.8.9, 13 s in Histogram Combo.
- **Job number** 1–9999: both manuals.
**A level write is refused** unless all three geophone channels' unit string, `ch +34:+38` with NULs and `.` stripped, equals `in`. Measured: `in.` and `in` both occur on UM20147. A unit set to Metric is unmeasured.
- [ ] **Step 1: Write the failing tests** in `tests/test_setup_fields.py`:
```python
def test_s3_reproduces_every_blastware_write():
# BE11529's 9 April images (bridges/captures/4-20-26/**/raw_bw_*.bin), in time order (the HHMMSS in
# the name): before = the previous image; the first (151921) uses the assembled 1A read in its own
# raw_s3 capture if that read is whole, else it is skipped (say so in the test). BE9441's 2 images:
# before = the assembled READS[0], then image 1. changes = field_values(after) for every field whose
# value differs. Assert encode_setup(before, 3, changes)[:2090] == after[:2090].
# The 16:26 write also moves [25] (mic on): include `_sensors_mic` as a test-only patch helper,
# not a registry field.
def test_s4_fixture_pairs_reproduce():
# for every ordered pair (a, b) of tests/fixtures/micromate-setup/*.bin whose differing bytes outside
# [2090:2092] all lie inside registry fields: encode_setup(a, 4, {f: field_values(b)[f] for differing f}) == b
def test_trigger_checked_against_the_new_range(): ... # Series 3: {"geo_range": "sensitive", "geo_trigger_ips": 2.0} refuses (above 1.25); 1.25 passes; {"geo_trigger_ips": 2.0} alone on Normal passes
def test_limits_refuse_outside_values(): ... # 0.004 and 10.001 in/s; 0.3005 (not a 0.001 step); job 0 and 10000; S4 0.9 and 90.1 s;
# S3 at 4096 sps: 26 ok, 26.1 refused; S3 histogram_continuous: 13 ok, 13.1 refused;
# S3 {"sample_rate": 1024, "record_time_s": 100} passes from a 4096 sps block (the new rate counts);
# sample rate 8192; interval 30
def test_field_not_offered_for_the_series(): ... # geo_range on series 4 -> SettingsValueError naming the series
def test_alarm_is_read_only_until_measured(): ... # Series 3 geo_alarm_ips -> SettingsValueError while S3_ALARM_WRITE_MEASURED is False
def test_metric_unit_string_refuses_level_writes(): ... # ch +34 = b"mm\x00\x00" -> SettingsValueError; b"in.\x00" and b"in\x00\x00" pass
def test_note_edges(): ... # "" clears; 41 bytes ok; 42 refused; "café" refused
def test_note_labels_are_never_written(): ... # changing note_2 moves only [208:250]
def test_bit_fields_keep_unknown_bits(): ... # [39] = 0x81: job_number_shown True -> 0x83, False -> 0x81
def test_s3_fixed_bytes(): ... # any S3 encode sets [26:28] = 00 00
def test_s4_encode_recomputes_the_crc(): ... # crc_ok(encode_setup(fixture, 4, {"job_number": 7}))
def test_f32_values_read_back_as_asked(): ... # written = encode(0.3); settings_state(before, written, written) == "as asked"
def test_settings_state(): ... # "as asked" / "unchanged" / "differs"; S4 with a bad CRC -> "differs"
def test_revision_is_stable_and_content_sensitive(): ...
```
- [ ] **Step 2: Run them.** Expected: FAIL (ModuleNotFoundError: `micromate.setup_fields`).
- [ ] **Step 3: Implement** `micromate/setup_fields.py` and `with_crc`. Decode via the registry (not via `decode_setup`, whose notes are keyed by label). Note labels come from the unit and are display only.
- [ ] **Step 4: Run them.** Expected: PASS. Then mutation-check `S3_BLASTWARE_FIXED` (remove it: the Blastware-write test fails), delete the `.pyc`, and restore.
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(codec): one settings codec for both series, on the shared layout`.
---
### Task 3: Micromate — read the schedule file
**Measured basis:** reference *The scheduler, and a generic file transfer* and *The schedule record format*.
- `0x94 <path>` opens a file for read; `offset` = the path's length, and the payload is the path, unpadded.
- `0x48` reads the next page, repeated until an all-zero 11-byte response.
- The file is 260-byte records. `[4]` is the half-hour slot. `[6]` is the action bitmask: 2 start-with-setup, 4 stop, 8 self-check, 16 ACH. `[7]` is the name length; `[8:260]` is the name.
**Files:**
- Create: `micromate/schedule.py`
- Modify: `micromate/protocol.py` (`read_file`), `micromate/client.py`
- Modify: `docs/micromate_protocol_reference.md`: one line under the scheduler section saying SFM reads it (read-only) from 2026-11-03.
- Test: `tests/test_micromate_schedule.py` (new)
**Interfaces:**
- Produces:
- `SCHEDULE_PATH = "\\system\\schedule\\schedule.dat"`.
- `MicromateProtocol.read_file(path: str) -> bytes`: the concatenated content of each `0x48` page after the page-0 descriptor, stopping at the all-zero response; at most 64 pages, else `ProtocolError`.
- `MicromateClient.read_schedule() -> bytes`.
- `MicromateClient.get_active_setup_raw() -> str`: the `0x41` name up to its NUL, **not** stripped.
- `MicromateClient.get_prefs_content() -> bytes` (`0x08`), `get_trigger_content() -> bytes` (`0x2E`) and `get_setup_content() -> bytes` (`0x1A`), each `_content(...)` of its read.
- `@dataclass(frozen=True) class ScheduleEntry`: `index: int`, `time: str` (`"HH:MM"`), `day: int`, `action_bits: int`, `actions: tuple[str, ...]`, `setup: str`.
- `parse_schedule(body: bytes) -> list[ScheduleEntry]`: 260-byte records; a record with `[4:8]` all zero and no name ends the list. `actions` names the bits 2/4/8/16 as `start_with_setup`, `stop`, `self_check` and `call_home`; any other bit becomes `unknown(0xNN)`.
- `schedule_conflicts(entries, active_setup: str) -> list[ScheduleEntry]`: start entries whose setup, compared case-insensitively after `strip()`, is not the active setup.
- [ ] **Step 1: Write the failing tests.** Parse the bodies from `bridges/captures/9-24-26 - micromate2/raw_s3_20260924_191835_read_scheduler.bin` (frames 0–4), and from the two `raw_*_20260925_*` captures, with `MicromateFrameParser`.
```python
def test_the_read_capture_parses(): # 2 records: start-with-setup 07:30 (40-char name), call_home 19:30 (no name)
def test_the_five_entry_schedule_parses(): # 07:30 start TEST1.mmb, 08:00 stop, 08:30 self_check, 09:00 start test2.mmb, 19:30 call_home
def test_conflicts_are_case_insensitive(): # active "test1.MMB" -> only the test2.mmb start conflicts
def test_no_schedule_records_is_no_conflict(): assert schedule_conflicts(parse_schedule(bytes(524)), "x.mmb") == []
def test_read_file_sends_the_path_unpadded_and_stops_at_zeros(): ... # a fake protocol: 0x94 offset 0x001D, then 0x48 until all-zero
def test_get_active_setup_raw_keeps_spaces(): ... # " LOC 4 .mmb " survives
```
- [ ] **Step 2: Run them.** Expected: FAIL (ModuleNotFoundError: `micromate.schedule`).
- [ ] **Step 3: Implement** the Produces block. `read_file` builds `0x94` with `build_request(0x94, len(path), bytes(10), path.encode("ascii"))`. Both SUBs are already in `READ_SUBS`.
- [ ] **Step 4: Run them.** Expected: PASS.
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(micromate): read the schedule file (read-only)`.
---
### Task 4: Change-path pieces and the Series 4 settings change
**Files:**
- Modify: `sfm/device_access/errors.py`, `sfm/device_access/change.py`, `micromate/opcodes.py`, `sfm/device_access/s4.py`, `tests/device_access_fakes.py`
- Modify: `tests/test_micromate_execute.py`, `tests/test_micromate_opcodes.py`. Their over-ceiling example `0x71` becomes enableable here; use `0xA8` (delete one event) instead.
- Test: `tests/test_device_access_s4_settings.py` (new)
**Interfaces:**
- Consumes:
- Task 2: `editable_fields`, `field_values`, `check_changes`, `encode_setup`, `settings_state`, `revision`.
- Task 3: `read_schedule`, `parse_schedule`, `schedule_conflicts`, `get_active_setup_raw`, and the content getters.
- `micromate.writes.plan_setup_push(prefs, trigger, setup, name)`.
- Produces:
- `class SettingsChanged(DeviceError)`, `http_status = 409`.
- `class ChangeRefused(DeviceError)`, `http_status = 409`.
- `settings_change() -> ChangeKind("change settings", "as asked", "applied")`.
- `ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F, 0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72})`.
- `s4_settings(client, serial) -> UnitSettings`. It keeps every current field, plus `detail["editable"] = editable_fields(setup, 4)`. The revision comes only from a preview (dry run), never from this read.
- `s4_change_settings(client, serial, *, changes: dict, revision: Optional[str], dry_run: bool, audit, address, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`.
**`s4_change_settings` behaviour**, through `run_change` (`even_if_already=False`):
- **`read_state`, first call:**
- Read the run state.
- `calling_home` and `unknown*` are returned as they are.
- `monitoring` raises `UnitStateUnknown(f"{serial} is monitoring -- stop it first (a stop makes it call in if call-home is on) -- nothing sent")`.
- Read the name (raw), prefs, trigger and setup.
- `check_changes` (a `SettingsValueError` becomes `BadRequest`).
- When live, `revision([name.encode("ascii"), prefs, trigger, setup])` must equal the request's. Otherwise raise `SettingsChanged("the unit's settings changed since the preview -- preview again; nothing sent")`.
- `image = encode_setup(setup, 4, changes)`.
- Read the schedule; a read error is kept as a blocking reason.
- Return `settings_state(setup, image, setup, series=4)`.
- **Later calls:** read the setup and return `settings_state(before, image, now, series=4)`.
- **`describe_plan`:**
- `plan_setup_push(prefs, trigger, image, name).describe()`, plus `fields` = `{f: {label, old, new}}` for the changed fields, `revision`, `warnings` and `blocked`.
- `warnings` always includes: "this reads the unit's keypad edit buffer: if someone is in its menu, their unsaved edits are sent too".
- `blocked`:
- the name is `factory.MMB` (case-insensitive): "this unit is running its factory setup; load any other setup on its keypad, then try again";
- each schedule conflict: "this unit's schedule loads <setup> at <HH:MM>, which would replace this change";
- a schedule read error: "could not read this unit's schedule (<error>) -- SFM will not change a unit whose schedule it cannot check";
- `plan_setup_push` raising `ValueError` (a block size or header THOR's offsets were never seen at, or a failed checksum): "this unit's <message> -- SFM has not seen a block like it".
- When `blocked` is non-empty, `steps` is `[]`, and a live call raises `ChangeRefused("; ".join(blocked) + " -- nothing sent")`.
- When the schedule names the active setup, `warnings` adds: "the unit's schedule loads this setup at <HH:MM>; the change survives it".
- **`send`:** `client.protocol.execute(plan)`, as `s4_change_call_home` does.
- **`snapshot`:**
- `fields`: `{f: {label, old, new, now}}`;
- `before` / `after` hex of the setup;
- `changed_offsets`;
- `prefs` and `trigger`: before hex only.
- **`is_refusal`**, **`is_ring`** and **`pre_send`**: as in `s4_change_call_home`.
**Validation order:** a live call without `revision` is refused before any I/O, in Task 6's `DeviceAccess` (not here).
- [ ] **Step 1: Write the failing tests.** Extend `FakeMicromateClient` with:
- `setup` (default: `tests/fixtures/micromate-setup/um20147_baseline.bin`'s last 2,092 bytes);
- `prefs`, `trigger` and `active_name` (default `"test2.mmb"`);
- `schedule_body` (default `bytes(524)`) and `schedule_error`;
- `execute` applies a setup-push plan's `0x71` data to `self.setup` (re-adding the CRC with `with_crc`), so a read-back sees it.
```python
def test_s4_dry_run_previews_old_to_new_and_sends_nothing(): # fields == {"geo_trigger_ips": {"label": ..., "old": 0.5, "new": 0.3}}; revision present; fake.executed == []
def test_s4_trigger_change_sends_the_push_and_verifies(): # subs [0xDA,0x68,0x73,0x82,0x83,0x71,0x72]; outcome sent/ok; state_after "as asked"
def test_s4_stale_revision_sends_nothing(): # SettingsChanged; fake.executed == []; audit has no rows
def test_s4_already_as_asked_is_skipped(): # outcome skipped, nothing executed
def test_s4_monitoring_is_refused(dry_run in (True, False)): # "stop it first" and "nothing sent"
def test_s4_factory_setup_is_refused_live_and_shown_in_preview():
def test_s4_schedule_conflict_blocks(): # schedule starts "other.mmb" at 07:00 -> ChangeRefused naming other.mmb and 07:00
def test_s4_schedule_on_the_active_setup_warns_only():
def test_an_unreadable_schedule_refuses():
def test_no_schedule_records_is_no_conflict(): # bytes(524) -> sent
def test_s4_a_lost_ack_records_what_the_unit_holds(): # execute_error -> outcome failed, sent True, snapshot present
def test_s4_unseen_block_size_is_blocked(): # prefs 91 B -> preview blocked; live ChangeRefused; nothing executed
def test_setup_push_subs_are_now_enableable():
```
- [ ] **Step 2: Run them.** Expected: FAIL (ImportError: `s4_change_settings`).
- [ ] **Step 3: Implement** the Produces block and update `s4_settings`. In the two opcode tests, swap the over-ceiling example to `0xA8`.
- [ ] **Step 4: Run them**, plus `tests/test_micromate_execute.py`, `tests/test_micromate_opcodes.py`, `tests/test_micromate_writes.py` (THOR's setup-push frames still reproduce) and `tests/test_device_access_s4_call_home.py`. Expected: PASS.
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(s4): change a Micromate's settings by serial, audited, schedule-checked`.
---
### Task 5: The Series 3 settings change
**Files:**
- Modify: `sfm/device_access/s3.py`, `minimateplus/client.py` (`push_config_raw` pre-check), `tests/device_access_fakes.py`
- Test: `tests/test_device_access_s3_settings.py` (new)
**Interfaces:**
- Consumes:
- Task 1: `read_compliance_content`, `read_settings_blocks`, `is_compliance_content`.
- Task 2: the codec.
- Task 4: `settings_change`, `SettingsChanged`, `ChangeRefused`.
- `MiniMateClient.push_config_raw(event_index, compliance, trigger, waveform)`.
- Produces:
- `push_config_raw` raises `ImageRefused` (from `minimateplus.protocol`) when its pre-check refuses a block, before any frame.
- `Series3Adapter.settings(address, serial) -> UnitSettings`. It is built on `read_compliance_content` and the codec, with the same top-level fields as today, plus `detail["editable"]`. A non-settings answer raises `UnitStateUnknown(S3_SETTINGS_WHILE_MONITORING)`.
- `S3_SETTINGS_WHILE_MONITORING = "did not return its settings -- a MiniMate answers this way while monitoring; stop monitoring first"`.
- `Series3Adapter.change_settings(address, serial, *, changes, revision, dry_run, audit, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`, through `run_change` and `self._run(address, op, retry=False)`:
- `read_serial`: `client.connect().serial`.
- **`read_state`, first call:**
- Wake, then `read_settings_blocks()`.
- A non-settings `compliance` raises `UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")`.
- `check_changes`, and the live revision check over `[event_index, compliance, trigger, waveform]`.
- Compute `image = encode_setup(...)` and return `settings_state(...)`.
- **Later calls:** wake, `read_compliance_content()`, then the verdict.
- **`describe_plan`:**
- `steps` in Blastware's order: 68 (event index, as read), 73, 71 (settings block, 2,092 B), 72, 82 (trigger, as read), 83, 69 (waveform data, as read), 74, 72. Each step has `sub`, `what` and `data_len`.
- `fields`, `revision` and `warnings` as Series 4. The warning: "the two bytes after the settings block go out as 00 00 (Blastware sends its own constant; effect unmeasured)".
- **`send`:** `client.push_config_raw(event_index, image, trigger, waveform)`.
- **`is_refusal`:** `isinstance(e, ImageRefused)`.
- **`snapshot`:** as Series 4, without prefs and trigger.
- [ ] **Step 1: Write the failing tests.** Extend `FakeMiniMateClient` with:
- `settings_blocks`: the default compliance is BE9441's assembled 10-26 read 2; `event_index`, `trigger` and `waveform` are the `0x68`, `0x82` and `0x69` payloads (`[16:]`) of `WRITES[13:26]` in `tests/test_minimate_write_frames.py`, each minus its two trailing bytes (a write is the read plus two);
- `push_config_raw` records its four arguments and makes the compliance the new `read_compliance_content`;
- `monitoring_settings=True` returns a device-info-shaped block.
```python
def test_s3_settings_read_uses_the_codec(): # editable includes geo_range; record_mode "histogram"; notes by slot with unit labels
def test_s3_dry_run_previews_and_sends_nothing():
def test_s3_trigger_change_sends_the_units_own_blocks(): # push args: event_index/trigger/waveform == the read blocks; compliance == encode_setup(...)
def test_s3_change_verifies_by_read_back(): # outcome sent/ok, state_after "as asked", snapshot fields old/new/now
def test_s3_stale_revision_sends_nothing():
def test_s3_monitoring_is_refused(dry_run in (True, False)):
def test_s3_a_refused_image_is_audited_as_nothing_sent(): # push_config_raw raises ImageRefused -> row sent 0, "refused before sending"
def test_push_config_raw_precheck_raises_image_refused(): # a 2,089-byte compliance block -> ImageRefused, no frame written
```
- [ ] **Step 2: Run them.** Expected: FAIL (AttributeError: `change_settings`).
- [ ] **Step 3: Implement** the Produces block.
- [ ] **Step 4: Run them**, plus `tests/test_s3_call_home.py`, `tests/test_minimate_write_frames.py` and `tests/test_device_access_*`. Expected: PASS, except the tests Task 6 deletes or rewrites. If one fails here only because it pins `apply_config`, leave it for Task 6 and note that in the ledger.
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(s3): change a MiniMate's settings by serial on the shared codec`.
---
### Task 6: Device access, the route, and retiring the legacy write
**Files:**
- Modify: `sfm/device_access/access.py`, `sfm/server.py`, `minimateplus/client.py`
- Delete: `poc_set_project.py`. Remove `exp_compliance_only` (and its registration) from `experiments.py`.
- **Ruling (spec: "the legacy write is retired"):** both write a live unit through the retired encoder, which #46 found wrong. Git keeps them.
- Modify tests:
- `tests/test_s3_compliance_anchor_fields.py`: remove its write-side tests (the encoder is gone).
- `tests/test_minimate_write_frames.py`: `test_apply_config_writes_the_units_own_trigger_block` moves to Task 5's `test_s3_trigger_change_sends_the_units_own_blocks`; delete it here.
- `tests/test_server_series3_guard.py`: drop `apply_config` from `WRITES` and its fake method.
- `tests/test_server_device_access.py`: `/device/config` now 410.
- Test: `tests/test_device_access_settings.py` (new), `tests/test_server_settings_change.py` (new)
**Interfaces:**
- Consumes: Task 4's `s4_change_settings` and Task 5's `Series3Adapter.change_settings`.
- Produces:
- `DeviceAccess.change_settings(address, serial, *, changes: dict, revision: Optional[str], dry_run: bool = False, caller: str = "api") -> ChangeResult`:
- `normalise_serial`, then `series_for_serial`;
- `changes` must be a non-empty dict, else `BadRequest`;
- a live call without `revision` raises `BadRequest("preview first: a live change needs the revision from its preview -- nothing sent")`;
- a live call with no audit log raises `NotSupported` (as `set_call_home`);
- `_dispatch(..., change=True)` with `verify_timeout_s=_SETTINGS_VERIFY_TIMEOUT_S = 2.0` and `verify_interval_s=_SETTINGS_VERIFY_INTERVAL_S = 1.0`.
- `POST /device/settings/change`:
- query: `serial` (required), `host`, `tcp_port`, `port`, `baud`, `dry_run`, `caller`;
- JSON body `{"changes": {...}, "revision": "..."}`;
- returns `_change_response(...)`;
- added to `_SERIAL_AWARE_PATHS`.
- `POST /device/config` and `POST /device/config/project` return **410** with `{"detail": "retired: change a unit's settings by serial with POST /device/settings/change (audited, previewed, read back)"}`. Remove the cache-dirty hooks that only these routes called; keep the read routes.
- Delete `MiniMateClient.apply_config`, `set_project_info` and `_encode_compliance_config`, and any import left orphaned.
- [ ] **Step 1: Write the failing tests:**
```python
def test_live_change_without_revision_is_refused_before_io(): # factory never called
def test_empty_changes_is_a_bad_request():
def test_change_settings_dispatches_by_series_with_change_true():
def test_route_dry_run_returns_fields_and_revision(): # 200, body.plan.fields, body.plan.revision
def test_route_verified_change_is_200_and_mismatch_409():
def test_route_unconfirmed_carries_sent_and_audit_id():
def test_route_refusal_is_409_with_reason(): # ChangeRefused / SettingsChanged / monitoring
def test_legacy_config_routes_are_gone(): # both 410, nothing reaches a client factory
def test_settings_change_is_serial_aware(): # in _SERIAL_AWARE_PATHS; a UM serial goes to the Series-4 path
```
- [ ] **Step 2: Run them.** Expected: FAIL (404 / AttributeError).
- [ ] **Step 3: Implement** the Produces block, the deletions, and the test updates listed under Files.
- [ ] **Step 4: Run them**, plus `tests/test_server_*.py`. Expected: PASS. Check that `grep -rn "apply_config\|set_project_info\|_encode_compliance_config" --include=*.py .` finds only comments and history.
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(sfm): POST /device/settings/change; retire the legacy config write`.
---
### Task 7: The page — edit, preview, send, "the unit now holds"
**Files:**
- Modify: `sfm/static/device_routing.js`, `sfm/static/sfm_webapp.js`, `sfm/sfm_webapp.html`
- Modify: `CLAUDE.md` (the "Where things stand" Series-4 parity line: phase 5 built, bench pending), and the spec's status line ("Built 2026-11-xx; bench pending").
- Test: `tests/test_webapp_device_routing.py` (extend `EXPORTS` and cases), `tests/test_webapp_static.py`
**Interfaces:**
- Consumes: `UnitSettings.detail.editable` / `.revision`, and the `ChangeResult` shapes from Tasks 4–6.
- Produces (DOM-free, in `device_routing.js`):
- `DEVICE_ROUTES.settings_change = ['POST', '/device/settings/change', true]`; remove `config_write`.
- `controlsFor(unit)`: `configWrite: serialMode && (series === 3 || series === 4)`; `reasons.configWrite: 'By serial only: Preview, then Send (audited).'`
- `settingsFormFields(st) -> Array<{field, label, kind, value, unit?, min?, max?, choices?, maxlength?, readonly?}>`: from `st.detail.editable`, in that order.
- `settingsChanges(fields, edited) -> object`: only fields whose edited value differs. Numbers compare as numbers; read-only fields are ignored.
- `settingsPreviewRows(body) -> Array<[label, old, new]>`, from `body.plan.fields`.
- `settingsBlockedText(body) -> string`: `body.plan.blocked` joined; `''` if none.
- `settingsResultRows(body) -> Array<[label, old, new, now]>`, from `body.detail.snapshot.fields`.
- **Page behaviour** (`sfm_webapp.js` glue; HTML ids `cfg-edit`, `cfg-preview-btn`, `cfg-send-btn`, `cfg-preview`, `cfg-result`):
- The serial-mode Config pane heading reads **"On the unit <SERIAL> — read <HH:MM>"**.
- The form is built from `settingsFormFields`.
- **Preview** POSTs a dry run and shows old → new, warnings and blocked reasons. It keeps `revision` and enables **Send** only when nothing is blocked and something changes.
- **Send** asks `confirm()` naming the serial and the fields, then POSTs live with the kept revision and shows "the unit now holds" rows. Errors go through `changeErrorText`.
- Editing any field after a preview disables **Send** until the next preview.
- The by-host legacy form loses its write button. Its read stays.
- No inline script; listeners via `addEventListener`.
- [ ] **Step 1: Write the failing Node-run cases** in `tests/test_webapp_device_routing.py`:
- `controlsFor` gives `configWrite` true by serial for both series, and false by host;
- `settingsChanges` returns only differing fields and compares `0.30` with `0.3` as equal;
- `settingsPreviewRows` / `settingsResultRows` / `settingsBlockedText` on bodies shaped as Task 6 returns them;
- `deviceUrl('settings_change', unit)` → `/device/settings/change?serial=…`;
- `config_write` is no longer a route.
In `tests/test_webapp_static.py`, assert the page has no inline `<script>` body and loads both static files.
- [ ] **Step 2: Run them.** `…pytest tests/test_webapp_device_routing.py tests/test_webapp_static.py -q`. Expected: FAIL (`settingsChanges` is not a function).
- [ ] **Step 3: Implement** the Produces block and the page behaviour.
- [ ] **Step 4: Run them.** Expected: PASS. Then run the page under the jsdom harness pattern from phase 4 (`smoke/page_files_load.js` in the scratchpad): the page loads with no console error, and a stubbed dry-run body renders the preview rows.
- [ ] **Step 5: Update `CLAUDE.md`** and the spec status line. **Run the full suite** and compare with the baseline. **Commit:** `feat(webapp): edit a unit's settings by serial: preview, send, read back`.
---
## After the build: final review, then the bench
The bench is not a task: it runs after the whole-branch review and its fixes, with Brian at the units, and **each send needs his explicit go**. Run SFM with `ringkit/sfm_parity.py` (port 8299; never 8200). Order:
1. **Read-only, both units:**
- `GET /device/settings` by serial; Brian matches it against each unit's screen.
- UM20147: `read_schedule` (measure what a unit with no schedule answers, and whether `0x08` shows the scheduler switch).
2. **Dry runs** of a trigger change on each unit. Read the preview with Brian.
3. **One field per unit**, with Brian's go:
- the trigger (UM20147 0.5 → 0.3; BE9441 0.04 → 0.05);
- read back; Brian checks the unit's menu;
- change it back, with another go.
4. **A notes change** on each (go).
5. **A several-field "backup unit" change** on each (go).
6. **Refusals:**
- a dry run while monitoring (expect the refusal);
- UM20147 with a schedule naming another setup, if Brian sets one up in THOR (expect the block).
7. **Alarm level (Series 3):**
- one write with Brian's go, read back and checked on BE9441's menu;
- only then flip `S3_ALARM_WRITE_MEASURED`, in its own commit naming the bench result.
Record everything in the spec's bench section and both protocol references (measured), then the devlog.
@@ -0,0 +1,655 @@
# Monitor logs (.MLG) and each unit's monitoring timeline — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** SFM reads Blastware `.MLG` files, stores them, and answers "was unit X monitoring at
time T?" and "when was it not, and why?" from each unit's monitoring timeline.
**Architecture:**
- **Codec library:** a pure reader and writer in `minimateplus/mlg_file.py`.
- **SFM:**
- two new tables, plus the original files kept in the waveform store
- one ingest function shared by the HTTP route and the bulk-import script
- the timeline as a pure function over stored rows, computed on each request
**Tech Stack:** Python 3.10, FastAPI, SQLite (`sfm/database.py`), pytest.
**Spec:** `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`. Read it first: the
measured format, session shapes and anti-goals are there and are not repeated here.
## Global Constraints
- **Where to work:** worktree `~/seismo-relay-mlg`, branch `feat/mlg-import`.
- Never commit to `dev` or `main`.
- Do not touch `CHANGELOG.md` (it is written on `dev` at merge).
- **Do not edit** `minimateplus/event_file_io.py`, `decode_check.py`, `histogram_codec.py` or
`waveform_codec.py`. Another session owns them; import from them only.
- **Running tests:** `cd ~/seismo-relay-mlg && ~/seismo-relay/.venv/bin/python -m pytest …`.
- The worktree has no venv. The tests put the worktree first on `sys.path`.
- `httpx` is not installed, so `starlette.testclient` tests skip silently. Test routes by
calling the route functions directly.
- **Baseline:** 1,659 passed, 63 skipped, 0 failed. Every commit keeps 0 failed. Read the
summary line, not just the exit code.
- That baseline needs the main checkout's git-ignored fixtures in the worktree. They were
copied on 2026-11-13; without them, 13 `idf`/`save_shape` tests fail.
- If they are missing: `rsync -a --ignore-existing ~/seismo-relay/tests/fixtures/ tests/fixtures/`
- **The codec library stays pure:** `minimateplus/` never imports `sfm`, never touches a DB,
and does no I/O beyond reading a path it was given.
- **The checksum:** CRC-16/AUG-CCITT (poly `0x1021`, init `0x1D0F`, no reflection), over
`record[0:288]`, stored little-endian at `record[290:292]`. Bytes `[288:290]` are `00 00`.
- **The format:**
- prefix `10 00 01 80 00 00 "Instantel\0" 07 2c` (18 bytes), then whole 292-byte records
- each record starts with its length `22 01` (290 LE)
- id `0e a0` is the header record (always first), `0e 80` a log record
- year little-endian in every timestamp
- **Time:** unit times are naive `datetime`s on the unit's own clock, stored with
`.isoformat()` and never converted. File times are aware UTC `datetime`s.
- **Fixtures:** `tests/fixtures/` is git-ignored, so new fixtures need `git add -f`.
- **Docs:** `docs/instantel_protocol_reference.md` is LF (enforced by `tests/test_line_endings.py`).
- **Commit messages** end with:
```
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
```
## Review Focus
1. **An empty file whose name prefix matches two known serials** (`BE11010304.MLG` with both
`BE1101` and `BE11010` known) resolves to the longest, `BE11010`. Test: Task 4,
`test_empty_file_takes_the_longest_known_serial`.
2. **One request with a good file and a corrupted one** stores the good file and refuses the bad
one per file. Nothing of the bad one lands: no row, no file in the store. Test: Task 6,
`test_import_route_stores_good_file_and_refuses_bad_one`.
3. **The same open "monitoring started" record arriving in a second file** (a re-forward, or a
cable download) is stored once, despite its NULL stop. Test: Task 3,
`test_open_record_is_stored_once`.
4. **A serial with no `.MLG` data** gets an empty timeline and `unknown`, never a 500 or a
"not monitoring". Test: Task 6, `test_timeline_routes_for_unknown_serial`.
5. **`at` exactly on a session's start or stop, or inside the repeated hour after the
clock step back,** gives a defined answer: boundaries count as monitoring, and the repeated
hour is `ambiguous`. Tests: Task 5, `test_monitoring_at_boundaries_are_inclusive`,
`test_clock_step_back_is_not_a_negative_gap`.
---
### Task 1: The reader, and one shared CRC
**Files:**
- Create: `minimateplus/crc.py`, `minimateplus/mlg_file.py`, `tests/test_mlg_file.py`
- Modify: `minimateplus/models.py` (add `MlgRecord`, `MlgFile` after `MonitorLogEntry`)
- Modify: `micromate/setup_block.py:63-69` (`_crc16_aug_ccitt` calls the shared function)
- Fixtures: `tests/fixtures/mlg-11-9-26/` (force-added)
**Interfaces:**
- Produces:
- `minimateplus.crc.crc16_aug_ccitt(data: bytes) -> int`
- `models.MlgRecord`, with fields:
- `index: int`: position in the file; 0 is the header record
- `start: datetime`, `stop: Optional[datetime]`
- `flags: int`, `trigger_source: int`, `serial: str`
- `text_raw: bytes`: exactly `record[34:288]`
- `event_time: Optional[datetime]`
- `text: str`, `trigger_level: Optional[str]`, `description: str`
- `crc_ok: bool`
- property `is_start` (`flags == 0xFFFF`)
- `models.MlgFile`:
- fields `serial: Optional[str]`, `records: list[MlgRecord]` (log records only, file order)
- properties `empty` (no records and no serial) and `crc_failures -> list[int]` (the indexes)
- `mlg_file.MlgFormatError(ValueError)`, `mlg_file.MLG_PREFIX: bytes`,
`mlg_file.RECORD_SIZE = 292`
- `mlg_file.parse_mlg(data: bytes) -> MlgFile`, `mlg_file.read_mlg(path) -> MlgFile`
- [ ] **Step 1: Copy the fixtures and force-add them**
Copy into `tests/fixtures/mlg-11-9-26/` with `cp -p`:
- from `~/dl2-archive/mlg/mlg-slice/`: `BE128443065.MLG`, `BE128443067.MLG`,
`BE128443068.MLG`, `BE128443155.MLG`, `BE128443156.MLG`, `BE6907750.MLG`, `BE6907751.MLG`
- from `~/dl2-archive/mlg/mlg-slice2/`: `BE8081.MLG`, `BE8081321.MLG`
- from `~/seismo-relay/example-events/ach-vs-manual/`: `BE11529.MLG`, `BE115292.MLG`
- from `~/seismo-relay/example-events/10-26-26/`: `BE94412.MLG`
Then `git add -f tests/fixtures/mlg-11-9-26`. Expected: 12 files, about 14 KB.
- [ ] **Step 2: Write the failing tests** in `tests/test_mlg_file.py`
Use `FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"` and
`dt = datetime.datetime`.
```python
def test_crc_matches_the_micromate_rule():
from micromate.setup_block import _crc16_aug_ccitt
assert crc16_aug_ccitt(b"123456789") == _crc16_aug_ccitt(b"123456789") == 0xE5CC
def test_every_fixture_record_passes_its_checksum():
for p in FIX.glob("*.MLG"):
assert parse_mlg(p.read_bytes()).crc_failures == [], p.name
def test_closed_records(): # BE128443065
m = read_mlg(FIX / "BE128443065.MLG")
assert m.serial == "BE12844" and len(m.records) == 2
r1, r2 = m.records
assert (r1.index, r1.start, r1.stop, r1.flags, r1.trigger_source) == (
1, dt(2026, 9, 5, 18, 47, 26), dt(2026, 9, 5, 20, 0, 0), 0x0010, 0)
assert r1.description == "Timer Stop"
assert r1.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (r2.start, r2.stop, r2.description) == (
dt(2026, 9, 6, 6, 0, 13), dt(2026, 9, 6, 18, 45, 0), "Modem Exit")
def test_monitoring_started_and_an_event(): # BE128443067
m = read_mlg(FIX / "BE128443067.MLG")
start, ev = m.records[1], m.records[2]
assert start.is_start and start.stop is None and start.description == "Monitoring started"
assert start.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (ev.flags, ev.trigger_source, ev.description) == (0x0001, 0x0001, "Event Recorded")
assert ev.event_time == dt(2026, 9, 8, 13, 38, 22)
assert ev.text == "Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s"
assert ev.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
def test_histogram_with_a_waveform_event(): # BE8081.MLG
r = read_mlg(FIX / "BE8081.MLG").records
assert (r[1].flags, r[1].trigger_source, r[1].description) == (
0x0021, 0x0400, "Event Recorded Modem Exit")
assert r[1].trigger_level == "Histogram"
assert (r[2].trigger_source, r[2].trigger_level) == (0x0002, "Geo: 0.300 in/s")
def test_trigger_level_with_or_without_a_space_before_the_colon():
a = read_mlg(FIX / "BE11529.MLG").records[0]
b = read_mlg(FIX / "BE115292.MLG").records[0]
assert a.text == "Trigger Level: Histogram" and b.text == "Trigger Level : Histogram"
assert a.trigger_level == b.trigger_level == "Histogram"
def test_empty_file():
m = read_mlg(FIX / "BE6907751.MLG")
assert m.serial is None and m.records == [] and m.empty
def test_a_flipped_byte_fails_only_its_record():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF # inside record 1's text
m = parse_mlg(bytes(data))
assert m.crc_failures == [1]
assert m.records[0].crc_ok is False and m.records[1].crc_ok is True
@pytest.mark.parametrize("mangle", [
lambda d: d[:-1], # not 18 + 292·n
lambda d: b"\x00" + d[1:], # wrong prefix
lambda d: d[:18] + b"\x23" + d[19:], # header length field not 290
])
def test_structure_errors_raise(mangle):
with pytest.raises(MlgFormatError):
parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes()))
```
- [ ] **Step 3: Run them to verify they fail**
Run: `~/seismo-relay/.venv/bin/python -m pytest tests/test_mlg_file.py -q`
Expected: collection error, `ModuleNotFoundError: minimateplus.crc`.
- [ ] **Step 4: Implement**
**The shared CRC.** `crc16_aug_ccitt` uses the same bitwise loop as `setup_block`. Point
`setup_block._crc16_aug_ccitt` at it, keeping the name, since its tests import it.
**Timestamps.** A timestamp is `day, month, year LE (2 bytes), 0, hour, minute, second`, and
all-zero means `None`.
**`parse_mlg` raises `MlgFormatError`, naming the record, when:**
- `len < 18`, or the prefix differs
- `(len - 18) % 292 != 0`
- any record's length field is not 290
- record 0's id is not `0e a0`, or a later record's id is not `0e 80`
- a start time cannot be decoded
**A checksum failure does not raise.** It only sets `crc_ok=False`.
**The text:**
- If `text_raw[0] == 0x08`, then `event_time` is `text_raw[1:9]` and the text starts at
`text_raw[9]`.
- `text` is the bytes up to the first NUL, latin-1.
- `trigger_level` is `text`'s first line (split on `\r`), with a leading `Trigger Level :` or
`Trigger Level:` removed and stripped. An empty result is `None`.
**`description`** is `"Monitoring started"` for `is_start`. Otherwise it is
`event_file_io.monitor_log_description(flags).strip()`.
**The header record** gives `MlgFile.serial` (`record[24:34]`, NUL-stripped ASCII).
- [ ] **Step 5: Run the tests, then the whole suite**
Run: `~/seismo-relay/.venv/bin/python -m pytest tests/test_mlg_file.py tests/test_micromate_setup.py -q`
Expected: all pass.
Then the full suite. Expected: `0 failed`.
- [ ] **Step 6: Commit**
```bash
git add minimateplus/crc.py minimateplus/mlg_file.py minimateplus/models.py micromate/setup_block.py tests/test_mlg_file.py
git commit -m "feat(mlg): read Blastware .MLG files, every record's checksum verified"
```
---
### Task 2: The writer, and the old MLG code retired
**Files:**
- Modify: `minimateplus/mlg_file.py` (add the writer)
- Modify: `minimateplus/blastware_file.py`:
- delete `_build_mlg_header`, `_build_mlg_record`, the old `write_mlg`, the `read_mlg` stub,
`_MLG_*` and `MLG_FLAGS_*`
- the module docstring's MLG sections become one line pointing at `minimateplus/mlg_file.py`
- ⚠ **Do not re-export from `blastware_file`.** `event_file_io` imports `blastware_file`
and `mlg_file` imports `event_file_io`, so a re-export makes an import cycle. Nothing outside
`blastware_file.py` uses the old names (checked 2026-11-13).
- Test: `tests/test_mlg_file.py`
**Interfaces:**
- Consumes: `MlgFile`, `MlgRecord` (Task 1)
- Produces:
- `mlg_file.mlg_bytes(mlg: MlgFile) -> bytes`
- `mlg_file.write_mlg(mlg: MlgFile, path) -> None`
- [ ] **Step 1: Write the failing tests**
```python
@pytest.mark.parametrize("name", sorted(p.name for p in FIX.glob("*.MLG")))
def test_rebuilds_every_fixture_byte_for_byte(name):
raw = (FIX / name).read_bytes()
assert mlg_bytes(parse_mlg(raw)) == raw
def test_old_mlg_code_is_gone():
import minimateplus.blastware_file as bw
assert not hasattr(bw, "read_mlg") and not hasattr(bw, "MLG_FLAGS_TRIGGER")
```
- [ ] **Step 2: Run them to verify they fail** (`ImportError: mlg_bytes`)
- [ ] **Step 3: Implement `mlg_bytes`**
Write the prefix, then for a non-empty file the header record:
- length, id `0e a0`, zeros, the serial at `[24:34]`, zeros, then the CRC
Every other byte of the header record is zero on all 1,273 DL2 files (measured).
Then each log record, from its fields:
- length, id `0e 80`, both times, flags and source LE, the serial
- `text_raw`, then `00 00`, then the CRC
An empty `MlgFile` is the prefix alone. Confirm nothing else imports the deleted names:
`grep -rn "MLG_FLAGS_\|_build_mlg\|_MLG_" --include=*.py .`
- [ ] **Step 4: Run the tests and the full suite.** Expected: 12 rebuilds pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): write .MLG files as Blastware does; retire the old writer"`
---
### Task 3: Storage
**Files:**
- Modify: `sfm/database.py`: the two tables appended to `_SCHEMA`, and the methods below.
- The docstring's table list gains both tables.
- No migration: `CREATE … IF NOT EXISTS` runs on every start.
- Modify: `sfm/waveform_store.py`: add `save_mlg`
- Test: `tests/test_mlg_storage.py`
**Interfaces:**
- Consumes: `MlgRecord` (Task 1)
- Produces:
- `WaveformStore.save_mlg(serial: Optional[str], file_name: str, data: bytes) -> str`.
- Writes `<root>/<serial or "_unresolved">/mlg/<file_name>` and returns that path
relative to the root (posix).
- If that path already holds different bytes, it uses `<stem>.<sha256[:8]><suffix>`.
- If it holds the same bytes, it reuses the path.
- `SeismoDb.mlg_file_exists(file_name: str, sha256: str) -> bool`
- `SeismoDb.insert_mlg(*, serial, file_name, sha256, size, empty, call_in, file_mtime, stored_path, records) -> tuple[Optional[str], int, int]`
- One transaction; returns `(file_id, inserted, skipped)`.
- Returns `(None, 0, 0)` when `(file_name, sha256)` already exists.
- `SeismoDb.query_mlg_records(serial: str, from_dt=None, to_dt=None) -> list[dict]`:
- ascending by `start_time`, then `seq`
- keys: `id, serial, start_time, stop_time, flags, trigger_source, text, trigger_level,
event_time, file_id, seq`
- `SeismoDb.query_mlg_files(serial: str) -> list[dict]`:
- ascending by `COALESCE(file_mtime, received_at)`
- keys: `id, serial, file_name, sha256, size, record_count, empty, call_in, file_mtime,
received_at, stored_path`
- `SeismoDb.get_mlg_file(file_id: str) -> Optional[dict]`
- `SeismoDb.known_serials() -> set[str]`: distinct non-null serials from `events`,
`mlg_files` and `mlg_records`
Schema:
```sql
CREATE TABLE IF NOT EXISTS mlg_files (
id TEXT PRIMARY KEY, serial TEXT, file_name TEXT NOT NULL, sha256 TEXT NOT NULL,
size INTEGER NOT NULL, record_count INTEGER NOT NULL, empty INTEGER NOT NULL,
call_in INTEGER NOT NULL DEFAULT 1, file_mtime TEXT,
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
stored_path TEXT, UNIQUE(file_name, sha256));
CREATE TABLE IF NOT EXISTS mlg_records (
id TEXT PRIMARY KEY, serial TEXT NOT NULL, start_time TEXT NOT NULL, stop_time TEXT,
flags INTEGER NOT NULL, trigger_source INTEGER NOT NULL, text TEXT, trigger_level TEXT,
event_time TEXT, file_id TEXT NOT NULL REFERENCES mlg_files(id), seq INTEGER NOT NULL);
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial);
```
- [ ] **Step 1: Write the failing tests**
- `test_insert_and_query_round_trip`: insert BE128443067's records; query returns 3 rows in
start order, with the open record's `stop_time` None.
- `test_same_file_twice_is_a_duplicate`: the second `insert_mlg` returns `(None, 0, 0)` and
there is still one file row.
- `test_open_record_is_stored_once`: insert the same `MlgFile` under two names (as a cable
download would arrive). The second returns `inserted == 0, skipped == 3`.
- `test_records_differing_only_in_text_are_the_same_record`: `BE11529.MLG`, then
`BE115292.MLG`. The second is `(id, 0, 3)`.
- `test_known_serials`, and `test_save_mlg_keeps_both_when_names_collide`: same name,
different bytes, two paths.
- [ ] **Step 2: Run them to verify they fail** (`AttributeError: insert_mlg`)
- [ ] **Step 3: Implement** the schema and the methods above. `record_count` is
`len(records)`.
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): store .MLG files and records, each record once"`
---
### Task 4: Ingest
**Files:**
- Create: `sfm/mlg_ingest.py`, `tests/test_mlg_ingest.py`
**Interfaces:**
- Consumes: `parse_mlg`, `MlgFormatError` (Task 1); `insert_mlg`, `mlg_file_exists`,
`known_serials`, `save_mlg` (Task 3)
- Produces:
- `resolve_serial(file_name: str, header_serial: Optional[str], hint: Optional[str], known: set[str]) -> Optional[str]`
- `ingest_mlg(db, store, file_name: str, data: bytes, *, serial_hint=None, file_mtime: Optional[datetime]=None, call_in: bool=True) -> dict`
Keys: `filename, status ("ok" | "duplicate" | "error"), detail, serial, serial_unresolved,
empty, records, inserted, skipped, file_id`.
**Rules:**
- **Serial:** the header serial wins. Otherwise the hint. Otherwise the longest known serial
that the name starts with (case-insensitive), as long as only digits follow it before
`.MLG`. Otherwise `None`.
- **Order of work:**
1. parse
2. a `MlgFormatError`, or any checksum failure, is `status "error"`, with `detail` naming
the record (e.g. `"record 1 fails its checksum"`); nothing is written
3. `mlg_file_exists` gives `"duplicate"`
4. `save_mlg`
5. `insert_mlg`
- [ ] **Step 1: Write the failing tests** (a tmp `SeismoDb` and `WaveformStore`, as
`tests/test_db_snapshot_endpoints.py::_client` builds them)
- `test_ingest_ok`: BE128443067 gives `status "ok"`, serial `BE12844`, `records 3`,
`inserted 3`. The file exists in the store under `BE12844/mlg/`.
- `test_ingest_twice_is_duplicate`
- `test_corrupted_file_stores_nothing`: flip byte `18+292+40`. Expect `"error"`, `"record 1"`
in `detail`, no `mlg_files` row, and no `mlg/` directory in the store.
- `test_truncated_file_is_an_error`
- `test_empty_file_takes_known_serial`: ingest `BE6907750` then `BE6907751`. The second is
`serial "BE6907"`, `empty True`.
- `test_empty_file_without_known_serial_is_unresolved`: serial `None`,
`serial_unresolved True`, stored under `_unresolved/mlg/`.
- `test_empty_file_takes_the_longest_known_serial`:
- `resolve_serial("BE11010304.MLG", None, None, {"BE1101", "BE11010"}) == "BE11010"`
- `resolve_serial("XY123.MLG", None, None, {"BE1101"}) is None`
- `resolve_serial("BE6907751.MLG", "BE12844", "BE6907", {"BE6907"}) == "BE12844"` (the
header wins)
- `test_file_mtime_and_call_in_are_stored`
- [ ] **Step 2: Run them to verify they fail**
- [ ] **Step 3: Implement `sfm/mlg_ingest.py`**
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): ingest one .MLG: verify, resolve the serial, keep the original"`
---
### Task 5: The timeline
**Files:**
- Create: `sfm/mlg_timeline.py`, `tests/test_mlg_timeline.py`
**Interfaces:**
- Consumes: rows from `query_mlg_records` and `query_mlg_files` (Task 3)
- Produces:
- `build_timeline(records: list[dict], files: list[dict]) -> dict`, with keys `sessions`,
`gaps`, `clock_steps`, `call_ins`. All times are ISO strings.
- **a session:** `start, stop, end_after, end_before, ended_by, kind ("histogram" |
"monitoring"), trigger_level, running_at_last_report, events`
- **an event:** `start, stop, trigger_source, trigger_level, description`
- **a gap:** `start, stop, minutes, meaning`
- **a clock step:** `previous_stop, next_start, minutes` (negative)
- **a call-in:** `kind ("delivered" | "no_file" | "nothing_new"), unit_time, file_time,
file_name`
- `monitoring_at(timeline: dict, at: datetime) -> dict`, with keys `status ("monitoring" |
"not_monitoring" | "unknown"), ambiguous, sessions, gap, trigger_level, reason`
**Rules.** These are the spec's §4 rules, made exact.
- **Sort:** records by `(start_time, 0 if flags == 0xFFFF else 1, seq)`.
- **Record kinds:**
- **start:** `flags == 0xFFFF`
- **histogram:** `flags & 1` and `trigger_source == 0x0400`
- **event:** `flags & 1` and any other non-zero source
- **closed:** everything else
- **Building sessions, walking the sorted records:**
- **A start record opens a pending session.** Close any pending one first, with
`end_after` = its last event's stop (or its own start) and `end_before` = this start.
- **A histogram record joins the pending session** when its start is ≤ 2 s after the pending
start, giving the session `stop` and `kind "histogram"`. Otherwise it is a session of its
own.
- **An event record:**
- joins the last session if its start lies within that session's `[start, stop]`
- otherwise it joins the pending session
- an event carrying an end bit closes a pending (non-histogram) session at its stop
- with no session to join, it opens one at its own start
- **A closed record** first closes any pending session (as above, `end_before` = its start),
then is a session `[start, stop]`.
- **A session still pending at the end** has `running_at_last_report True` and
`end_after` = its last event's stop, or its start.
- **`ended_by`** is `monitor_log_description(flags & ~1).strip()` of the record that set
`stop`, or `None`. `trigger_level` is the start record's, else the stop record's.
- **Gaps:** from a session's end (`stop`, else `end_after`) to the next session's start.
- If the next start is earlier than that end, it is a clock step, not a gap.
- The meaning comes from `ended_by`:
- Modem Exit: "call-in"
- Timer Stop: "scheduled off"
- Battery Low Exit: "lost power"
- Keyboard Exit and Remote Exit: "stopped by a person"
- Memory Full Exit: "memory full"
- anything else: "unknown"
- **Call-ins**, per file in `query_mlg_files` order (`file_time` = `file_mtime`, else
`received_at`):
- **An empty file** gives `nothing_new`.
- **A `call_in` file with records** gives `delivered`, with `unit_time` = the stop of the
file's last record (by `seq`). Each Modem Exit (`flags & 0x20`, not a start) that is not
the file's last record gives `no_file`, with `unit_time` = its stop and `file_time` None.
- **Non-call-in files** give nothing.
- **`monitoring_at`:**
- **monitoring:** `start ≤ at ≤ stop`, or `≤ end_after` when the stop is unknown. Two or more
matches set `ambiguous True`.
- **unknown:** inside an unknown end window, or after `end_after` of a session running at the
last report.
- **not_monitoring:** inside a gap, with the gap.
- **unknown:** anything else, including no data.
- [ ] **Step 1: Write the failing tests.** Ingest fixtures into a tmp DB with explicit
`file_mtime` values, then call `build_timeline(db.query_mlg_records(s), db.query_mlg_files(s))`.
- `test_sessions_gaps_and_an_event_session` (BE128443067 + 068):
- three sessions: `09-07 18:47:27 → 20:00:00 "Timer Stop"`; `09-08 06:00:13`, stop None,
`end_after 13:38:25`, `end_before 13:41:16`, 1 event; `13:41:16 → 18:45:00 "Modem Exit"`
- gaps: `"scheduled off"`, `minutes ≈ 600.217`; then `"unknown"`, `≈ 2.85`
- `test_monitoring_at`, on the same data:
- `09-08 10:00` is `monitoring`, trigger level `"Geo: 0.0500 in/s Mic: 125.0 dB(L)"`
- `09-08 13:40:00` is `unknown`
- `09-07 23:00` is `not_monitoring` with meaning `"scheduled off"`
- `2027-01-01` is `unknown`
- `test_monitoring_at_boundaries_are_inclusive`: `09-07 18:47:27` and `09-07 20:00:00` are
both `monitoring`.
- `test_clock_step_back_is_not_a_negative_gap` (BE128443155 + 156):
- no gap with negative minutes
- one clock step: `previous_stop 2026-11-01T18:45:00`, `next_start 2026-11-01T17:47:25`,
`minutes ≈ -57.58`
- `monitoring_at(11-01 18:00)` is `monitoring`, `ambiguous True`, 2 sessions
- `test_weekend_battery_outage_and_missed_calls` (BE8081321 alone):
- sessions start at `04-12 17:17:59` (histogram, from the start record),
`04-12 18:38:14`, `04-13 07:05:15` ("Battery Low Exit") and `04-15 12:47:05`
- the gap `04-13 10:47:15 → 04-15 12:47:05` is `"lost power"`, `minutes ≈ 2999.83`
- two `"call-in"` gaps of `≈ 5.23`
- call-ins: `no_file` at `2019-04-12T18:33:00`, `no_file` at `2019-04-13T07:00:01`,
`delivered` at `2019-04-15T17:15:00`, with `file_name "BE8081321.MLG"`
- `monitoring_at(2019-04-14 12:00)` is `not_monitoring`, `"lost power"`
- `test_histogram_session_keeps_its_waveform_event` (BE8081.MLG):
- one session `2018-02-16 15:15:31 → 15:15:49`, `kind "histogram"`,
`trigger_level "Histogram"`
- one event with `trigger_source 2` and `trigger_level "Geo: 0.300 in/s"`
- `test_event_with_an_end_bit_inside_a_histogram` (BE94412):
- the histogram session `16:06:34 → 16:07:21` keeps its stop and `"Keyboard Exit"`
- it holds the Memory Full event
- the `17:00:36` histogram is a session of its own
- `test_call_in_kinds` (BE6907750 + 751): `no_file` at `2026-08-22T18:30:00`, `delivered` at
`2026-08-23T18:30:00`, then `nothing_new`.
- [ ] **Step 2: Run them to verify they fail**
- [ ] **Step 3: Implement `sfm/mlg_timeline.py`** (pure: no DB, no I/O)
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): each unit's monitoring timeline, and was it monitoring at T"`
---
### Task 6: Routes
**Files:**
- Modify: `sfm/server.py`: the routes go after `db_import_idf_file`
- Create: `tests/test_mlg_routes.py`
**Interfaces:**
- Consumes: `ingest_mlg` (Task 4); `build_timeline`, `monitoring_at` (Task 5); Task 3's queries
- Produces:
- `POST /db/import/mlg_file` → `db_import_mlg_file(files: list[UploadFile] = File(...), serial: Optional[str] = Query(None), call_in: bool = Query(True), mtimes: Optional[str] = Form(None))`.
`mtimes` is JSON `{filename: unix_seconds_utc}`. Returns `{"count", "results": [ingest
dicts]}`.
- `GET /db/units/{serial}/timeline?from_dt=&to_dt=` → `db_unit_timeline(...)`: the full
timeline, with sessions, gaps and call-ins filtered to those overlapping the window.
- `GET /db/units/{serial}/monitoring_at?at=` → `db_unit_monitoring_at(...)`
- `GET /db/mlg_records?serial=&from_dt=&to_dt=` → `db_mlg_records(...)`
- `GET /db/mlg_files/{file_id}` → `db_mlg_file(...)`: the original bytes as a `FileResponse`
with the original `file_name`; 404 if unknown.
- [ ] **Step 1: Write the failing tests.** Set up as `_client` does (monkeypatch `srv._db` and
`srv._store`). Call the route functions directly: `asyncio.run(...)` for the import, with
`UploadFile(file=io.BytesIO(data), filename=name)`.
- `test_import_route_stores_good_file_and_refuses_bad_one`:
- two files, BE128443065 and a corrupted copy named `BE128443099.MLG`
- results: `["ok", "error"]`
- one `mlg_files` row; only the good file under the store's `mlg/`
- `test_import_route_reads_mtimes`: `mtimes='{"BE128443065.MLG": 1788734760}'` stores
`file_mtime` `2026-09-06T22:46:00+00:00`.
- `test_timeline_and_monitoring_at_routes`, with BE8081321 imported: the timeline has 4
sessions, and `monitoring_at` at `2019-04-14T12:00:00` is `not_monitoring`.
- `test_timeline_routes_for_unknown_serial`: `BE0000` gives empty `sessions`, `gaps` and
`call_ins`, and `monitoring_at` is `unknown`.
- `test_mlg_file_route_returns_original_bytes`, and a 404 for an unknown id.
- [ ] **Step 2: Run them to verify they fail**
- [ ] **Step 3: Implement the routes.** They stay thin: parse the query, call Tasks 3–5.
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): /db routes: import .MLG, a unit's timeline, monitoring at T"`
---
### Task 7: Bulk import and the cross-check
**Files:**
- Create: `scripts/import_mlg_dir.py`, `scratch/check_mlg_vs_events.py`,
`tests/test_import_mlg_dir.py`
**Interfaces:**
- Consumes: `ingest_mlg` (Task 4), `parse_mlg` (Task 1), `crc16_aug_ccitt` (Task 1)
- Produces:
- **`scripts/import_mlg_dir.py <dir> --db-path P --store-root S [--dry-run] [--not-call-in]`**
- `main(argv) -> int`, following `scripts/backfill_event_shape.py`
- walks `*.MLG` (case-insensitive) recursively
- **two passes:** files with records first, then the empty ones, each oldest file time
first. Every unit's serial is then known before its empty files arrive, whatever the
folder order.
- `file_mtime` from `os.stat` as UTC
- prints counts: files, ok, duplicate, error, empty, unresolved, inserted, skipped
- dry run: parse and checksums only, nothing written
- **`scratch/check_mlg_vs_events.py <mlg dir> <event dir>`**
- matches every non-start record with the Event Recorded bit to an event file by
`(serial, stop, flag word, trigger source)`
- an event file's serial number comes from its name, via
`sfm.waveform_store._serial_number_from_bw_filename`, compared with the MLG serial's
digits
- only event files inside each serial's MLG period count (its first record's start to its
last record's stop). DL2 holds years of event files from before the `.MLG`s.
- reads each event file's footer straight from its last 28 bytes: `00 1a 0e 08`, both times
with a big-endian year, flag word and source BE. It checks the footer's CRC with
`crc16_aug_ccitt` too.
- prints matched / record-only / file-only per serial, with up to 5 examples each
- [ ] **Step 1: Write the failing test.** `test_import_dir_counts`:
- copy the fixture dir to `tmp_path`
- the dry run prints `files 12`, writes no DB file and returns 0
- a real run imports 12 files with 0 errors, and a second run reports 12 duplicates
- [ ] **Step 2: Run it to verify it fails**
- [ ] **Step 3: Implement both tools**
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Run both tools on the real data, on the dev box only**
```bash
~/seismo-relay/.venv/bin/python scripts/import_mlg_dir.py ~/dl2-archive/mlg --db-path /tmp/claude-1000/mlg-check.db --store-root /tmp/claude-1000/mlg-check-store
~/seismo-relay/.venv/bin/python scratch/check_mlg_vs_events.py ~/dl2-archive/mlg ~/dl2-archive/files
```
Expected:
- 1,273 files, 0 errors, 231 empty, 0 unresolved
- BE8081: 785 matched, 0 record-only, 0 file-only
- BE6907: 6 matched, 5 record-only, 0 file-only
- BE12844: 19 matched, 37 record-only, 0 file-only
- every record-only one stops after 2026-08-25, where the DL2 copy ends
Put the numbers in the commit message.
- [ ] **Step 6: Commit**
`git commit -m "feat(mlg): bulk import, and a cross-check against the event files"`
---
### Task 8: Documentation
**Files:**
- Modify: `docs/instantel_protocol_reference.md`:
- D.4 to D.4.3 rewritten from the spec's "What was measured", each claim graded
- the old D.4.2 table kept under a ⚠ RETRACTED banner (its CRC position, BE timestamps
and flag table)
- a row in the Changelog table at the top
- Modify: `CLAUDE.md`:
- the "SFM REST API" `/db` list gains the five routes
- one line under "Where things stand" pointing at the spec
- Modify: `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md` §8: the footer CRC
note becomes "recorded on dev, `8544e9c`"
- [ ] **Step 1: Edit the three files**
- [ ] **Step 2: Run `tests/test_line_endings.py` and the full suite.** Expected: `0 failed`.
- [ ] **Step 3: Commit**
`git commit -m "docs: the .MLG format measured (reference D.4), and the new /db routes"`
@@ -560,7 +560,39 @@ Each safety piece arrives with its first real use, so nothing sits untested.
experiment.
- **Refuse writes unless this connection's responses carried Micromate
flags** (0xC5/0x03), alongside the serial identity check.
4. **Call-home enable/disable** (row 9).
4. **Call-home enable/disable** (row 9). **Built 2026-11-02** (plan
`docs/superpowers/plans/2026-11-02-sfm-phase4-call-home.md`): `run_change` takes a
`ChangeKind` (`1dd5bfa`); Series 4 reads bit 0 of `0x2C` content[5] and sends
`plan_call_home_enabled` (`eeb55ef`; `ENABLEABLE_WRITES` gains `0x7E`/`0x7F`);
Series 3 reads byte 5 of the *unescaped* block and sends `call_home_image`
(`8612cd9`). The Series-3 frame was gated until reproduced from Blastware: its
2026-04-20 enable and disable writes (BE11529) are rebuilt byte for byte from the
unit's own reads (`453d42e`), so the gate is open. Routes `GET
/device/call_home/state`, `POST /device/call_home/{enable,disable}`, serial
required (`06fa56d`); the page's Call Home tab by serial (`84c142f`). The
read-back judges the edited bit; the snapshot keeps both blocks and every changed
offset (Series 4's `[118:120]` always moves). The final review, before any send,
caught the Series-3 send path unescaping the built image a second time -- a
16:02-16:04 call-in time would have been refused as 'sent' or sent shifted --
fixed with a test through the real protocol (`bdd76b8`), plus a pre-wire refusal
audited as nothing sent, an unknown Series-4 run state refused, and the snapshot
kept on a lost ack (`9e03b3f`). **Benched 2026-11-03** (UM20147 and BE9441,
each on its own modem; one send per go):
- **Idle, both series:** a no-op, off, and on were each acked and read back,
and each unit's own menu agreed. UM20147 accepts `0x00` at `[5]`.
- **Monitoring, neither series can change call-home:**
- A MiniMate answers the `0x2C` read with its device-info block, so SFM
refuses with "stop monitoring first" (`5326e99`).
- A Micromate returns the real block and acks the write, but ignores it
("Feature disabled while monitoring" on its own menu). SFM now refuses
up front, and edits only a block whose header is its own length
(`f35845d`).
- **Series 4 `[118:120]`:** a function of the block's content (a fixed XOR of
`0x6D7D` per bit-0 flip, on two units).
- **Batch 1's #9 reconnect worked live:** BE9441's line dropped in the sensor
check, and the start was verified.
- Details: `docs/micromate_protocol_reference.md` (Bench 2026-11-03) and the
Series-III reference's 2026-11-03 row.
5. **Setup push** (row 10): one field first, then several.
Each phase is its own implementation plan. **All phases land on
@@ -664,39 +696,77 @@ From the page bench on BE9441 (MiniMate, modem `63.43.212.233`) and UM20147
(Micromate, RX55 `63.45.161.30`). Numbers as given at the bench. Fixes wait for
a short plan; #14 waits for the line-hold decision above.
1. **S3 settings decode reads before escapes are removed** -- BE9441 showed 0 sps
1. ✅ **Fixed `b320a53`**; the write encoder refuses a patch that would not read back
(`a72d3a9`) -- its raw offsets are 1024-sps ones and need rewriting on unescaped
bytes (#46). (The four anchor fields read after `unescape_reply`; mode −7,
rate −6, interval −4, record time +6; the channel block stays on raw bytes).
**S3 settings decode reads before escapes are removed** -- BE9441 showed 0 sps
and a 68.3-min interval (true: Histogram, 4096 sps, 2 s, per the 10-26 fixture
README); while monitoring the `1A` anchor is not found at all. Old bug, the
same family as #46's C1. Fix: decode after unescaping; this reply is the
fixture.
2. **A 1.7 KB mic-off histogram is refused** -- this branch lacks #47/#49 (`dev`
2. ✅ **Fixed by the `dev` merge `342c696`** (#47/#49 came in).
**A 1.7 KB mic-off histogram is refused** -- this branch lacks #47/#49 (`dev`
decodes `K441LTOK.QZ0`, this branch does not). Bring them over before merge.
3. ✅ The 71 KB histogram crossing two 64 KB pages downloaded over the modem
byte-identical to Blastware's (`f10f39a8…`).
4. List vector sum 0 / −0 for three events whose peaks reach 1.08 in/s --
suspected escapes in the `0C` record (not checked).
5. Stored S3 event: client "Terra-Mechanic" (last letter missing) -- unexplained.
6. Page: the Config tab shows the empty write form until Read in serial mode.
6. ✅ **Fixed 2026-11-02 (Batch 2):** by serial the edit form stays hidden and the settings
box shows from the start ("Not read yet"); another unit's settings are cleared.
Page: the Config tab shows the empty write form until Read in serial mode.
7. `/db/events` 500 "database is locked" on the first page load against a new DB.
8. **S3 downloads are stored from the live waveform decoder** (`store.save`), not
8. ✅ **Fixed `9492e49`**, plus `3a1d34a` ("already stored" also matches the Blastware
name: a histogram's row sits a second off its 0C time). The download carries the assembled Blastware file and is
stored through `save_imported_bw` (`source.kind` "sfm-live"). Since 2026-11-02
(after the checker's fixes for the histogram vector sum 625bc39, the mic psi
5644dbd and the file's geophone range 4844135) the row and samples are the
file's: peaks, vector sum, mic, and the range the event was recorded at (the live
1A is the unit's setting *now*, a fallback only when the file's range does not
read). The unit's 0C summary is the download check, and fills in peaks only when
the file's range does not read and the unit is not confirmed Normal. Until then
the unit's 0C values were overlaid (`9492e49`, narrowed `0a87d85`). The label
came with #41 (`a1d2b61`).
**S3 downloads are stored from the live waveform decoder** (`store.save`), not
the file reader that Series 4 uses (`save_imported_idf`): a histogram gets no
samples and is labelled Waveform. Fix: store S3 downloads through the
file-import path (also aligns event times with v0.32.0).
9. **S3 start over a modem:** the line dropped during the sensor check, the
9. ✅ **Fixed `ce441a0`**, plus `dbd8a91` (the reconnect wakes the unit before its
identity read). (One reconnect on an `OSError`, TCP only, identity checked,
nothing re-sent).
**S3 start over a modem:** the line dropped during the sensor check, the
read-back hit `Broken pipe` and did not reconnect → 503 though the start
worked. Fix: reconnect for the read-back (reads only; the send stays single).
10. Page: "Start monitoring failed:" on a sent-but-unconfirmed change -- wording.
10. ✅ **Fixed 2026-11-02 (Batch 2):** the start/stop route adds `sent` + `audit_id` to a
ChangeUnconfirmed (same status and message); the page says "… not confirmed:".
Page: "Start monitoring failed:" on a sent-but-unconfirmed change -- wording.
11. S3 stop ~19 s, 11.6 s of it the identity check (a full connect) vs ~1 s for a
serial-only read. **Identified only** (speed is secondary to reliability).
12. Page, serial mode: the Device tab's empty legacy compliance table; S4
12. ✅ **Fixed 2026-11-02 (Batch 2):** by serial the legacy tables are hidden behind a
pointer to the Config tab; a Micromate's Firmware reads "Thor line (version not read)".
Page, serial mode: the Device tab's empty legacy compliance table; S4
Firmware "—" (should say Thor line).
13. S4 mic in the event's peaks "0.0 dBL" vs 96.54 dB(L) in the file -- the
`0x0C` mic denormal parked above, now visible.
14. **After hanging up for a RADIO RING, SFM called the unit straight back up**
(the page's post-change status read). Part of the line-hold decision.
15. **Audit:** the UM20147 stop's record says `sent: null` although `0x97` went out.
16. Page: a 504 on a unit THOR holds should say "connected, but no reply --
15. ~~**Audit:** the UM20147 stop's record says `sent: null` although `0x97` went out.~~
**RETRACTED 2026-10-29: not a bug.** `sent` is documented as 1 acknowledged, 0
nothing sent, NULL unknown (`sfm/database.py`, `change.py`); a frame answered by a
ring instead of its ack is exactly unknown, and the row's `error` says it was sent.
16. ✅ **Fixed 2026-11-02 (Batch 2):** a 504 with nothing sent adds "the connection opened,
so the modem is reachable — another program (THOR or Blastware) may be holding
this unit's line, or the unit is busy".
Page: a 504 on a unit THOR holds should say "connected, but no reply --
another program may be holding this unit's line".
17. ✅ **Range part fixed 2026-11-02:** a MiniMate downloaded *while monitoring*
answers 1A with its device-info block, so no range was read and the stored
`.h5` samples assumed Normal -- 8x off on a sensitive-range unit. The range now
comes from the event file itself (measured: K557J1KB.RQ0W stores 0.019 / 0.055 /
0.019, Blastware's report, with the settings unread). Still open: the same reply
decodes a setup name of `:S338.17`, and live S3 downloads no longer keep the
`.a5.pkl` wire record.
- **Same-second collisions (SDM).** Two events of one unit in the same second collide on (serial, timestamp) — a DB-wide dedup property, not 1b's.
- **423 without `Retry-After` (1c).** Add `Retry-After` to the 423 a request gets while a download holds the unit.
- **A lost `0C` during a Series-3 list (1c).** The strict walk raises on a lost `0A`
@@ -0,0 +1,268 @@
# Series 3 decode checker — design
**Date:** 2026-10-29 · **Branch:** `feat/s3-decode-checker` · **Status:** design
## Why this exists
SFM is meant to replace Blastware. Today, when a Series 3 event arrives with
Blastware's ASCII report, SFM takes many of its values from the report: ZC
frequency, acceleration, the sensor check and so on. Two of the four ways
events will reach SFM, its own serial/modem download and its future call-in
server, never have a report. So SFM must produce **everything Blastware
reports, from the event file alone**, and we need proof that it does.
The checker is that proof, and the to-do list for getting there. It decodes
each event file the way SFM ingest does, with no report, and compares every
field with Blastware's own report of the same event. Then it says what
matches, what doesn't, and what SFM can't produce yet.
It is the first of four pieces, agreed with Brian on 2026-10-29:
1. **This checker.**
2. Completing SFM's file-only decode, one field group at a time, each slice
done when the checker shows it matching. Slice 1, the setup fields and
notes (#44/#45), merged to dev as `42fe35f`.
3. Flipping ingest to file-only. Reports are kept for checking only. This
happens only when piece 2 leaves no blanks and the checker proves it.
Prod keeps its current behaviour until then.
4. The watcher: it forwards the XML report while we verify, then stops
forwarding reports.
## The reference: Blastware's XML event reports
Every Blastware ACH machine keeps, in `Sent/`, a full XML event report for each
event: `<stem>_<ext>_XML.XML` next to the binary `<stem>.<ext>`. DL2's backup
holds **70,042 of them for Series 3 events, from 2016 to 2026**. Its ASCII
reports, by contrast, cover only 2025–26.
Local copies on the dev box (`tmi-dev`, 10.0.0.44):
| what | where | count |
|---|---|---|
| event binaries (Series 3) | `~/dl2-archive/files/` (root + `Sent/` mirror, dedupe by basename) | 70,112 distinct |
| XML reports | `~/dl2-archive/xml/` (flat) | 75,958 = 70,042 Series 3 + 5,916 Micromate (`UM…_IDF?_XML.XML`) |
| ASCII reports | `~/dl2-archive/files/` | 14,338 (2025–26 only) |
What the Series 3 XML contains (surveyed across all 75,958 on 2026-10-29):
- **Identity:** `EventType` (`Full Waveform` 6,524, `Full Histogram`
63,518), `SerialNumber`, `Version` (`V 10.72-8.17 MiniMate Plus` or
`… BlastMate III`), `FileName`.
- **Time:** waveform `EventDate`/`EventTime`; histogram
`HistogramStart*`/`HistogramStop*`.
- **Setup:** `Channels`, `Trigger`, `GeoTriggerLevel`, `MicTriggerLevel`,
`Pre-triggerLength`, `RecordTime`, `RecordStopMode` (only `Fixed` occurs),
`SampleRate`, `IntervalSize` (2 s / 5 s / 15 s / 1 min / 5 min),
`NumberofIntervals`, `GeoRange` (10.000: 75,923; 1.250: 35), `Units` (`in/s
and dB(L)` / `psi(L)` / `dB(A)` / `in/s`), `Microphone` (weighting).
- **Unit:** `BatteryLevel`, `Calibration` (date + by whom), `MicCalibration`.
- **Notes:** `JobNumber`, then up to four user notes. Each is tagged with its
operator-editable label (`Project`, `Location`, `Seis.Loc`, `SeisLocation`,
`SeismographLoc`, `Company`, `General`, …), and empty notes are omitted.
They sit between the top-level `</Units>` and `<GeoRange>`.
- **Results:** per channel `PPV`, `ZCFreq`, `TimeofPeak`, `PeakAcceleration`,
`PeakDisplacement` (waveform) or `PeakDate`/`PeakTime` (histogram);
`PeakVectorSum` with its time; mic `PSPL`, time, `ZCFreq` (dB(A)
histograms carry `MicA*` fields instead).
- **Sensor check:** per geophone `TestFreq`, `TestRatio`, `TestResults`; mic
`TestFreq`, `TestAmplitude`, `TestResults`.
- **`MonitorLog`:** the session's start, stop and status text.
- **Data:** waveform `WaveformDataChannels/Data/Row/Cell` (4 cells per
sample: Tran, Vert, Long in in/s, MicL in the event's mic units); histogram
`HistogramDataIntervals` (a `Time` and a 10-cell `Row` per interval:
Tran/Vert/Long peak + freq, geo PVS, MicL psi, dB and freq).
Value forms the parser must handle: numbers with units in the text (`6.7
Volts`, `7.6 Hz.`, `3.0 sec.`, `-0.250 sec`); `&gt;100` (ZC frequency above
range; 71,823 files), `N/A` (37,293 files), `OORANGE` (59 files: the channel
clipped), `Check` (2,193 files), and XML entities. Two `_XML.XML` details
matter:
- Blastware prints each number to a fixed number of decimals and **rounds
halves away from zero** (−0.0625 s prints as −0.063).
- The small `<stem>_<ext>.XML` summary next to it uses **decimal commas**.
It is not the reference; the `_XML.XML` is.
## Goals
- For every Series 3 event file with an XML report, compare **every field the
XML carries**, plus every waveform sample and every histogram interval,
against SFM's file-only decode.
- Give each comparison one verdict: **match**, **mismatch**, **SFM blank**
(SFM produced nothing), **accepted difference** (covered by a written
carve-out), **no reference** (the XML lacks the field), or **error** (the
decode or parse failed).
- Produce two outputs:
- **A short summary for Brian:** per field, the counts of each verdict and
how far we are from done.
- **A detailed report for Claude** that groups failures by what the failing
events share, so 17,000 mismatches read as "one bug on 2048 sps
histograms". It gives example files with Blastware's value and SFM's, and
a one-line command to re-run a single event.
- **Run again and again.** Each run is compared with the previous one, so a
fix shows as numbers moving, and anything that used to match and stops is
called out.
- Keep the comparison as library code, so ingest can later run it on one
event as it arrives (piece 3/4).
## What counts as "SFM's side"
The SFM side is **what SFM produces from the event's bytes alone**:
- **The `Event` that `decode_blastware_bytes` returns when given the bytes and
no filename.**
- SFM's own download and call-in paths never have a Blastware name.
- Today the event type comes only from the filename's extension, so every
histogram decodes as "Waveform". The checker reports that as it is: a
mismatch until the decoder reads the type from the file (#41). It must
not borrow the name to make it match.
- **Anything else SFM reads from those bytes outside the decoder**, such as the
serial.
- Ingest's `sfm/waveform_store._serial_from_bw_bytes` uses the filename to
validate what it finds.
- Whatever SFM can't get from the bytes alone is "SFM blank".
- **Values the codec computes but never puts on the `Event`** count as SFM
blank until they are wired through (piece 2). For example, histogram
half-periods in `histogram_codec.decode_histogram_body_full` give the
per-interval frequency.
- **SFM's assumptions included.**
- SFM cannot yet read the geophone range from the file, and assumes Normal
(10 in/s): `_peaks_from_samples` does, and ingest writes `.h5` with
`geo_range="normal"`.
- The checker compares what SFM actually produces under that assumption.
The range field itself is SFM blank.
- So the 35 events recorded on the 1.250 in/s range show as 8× mismatches,
not blanks. Example: `T438L713.QP0W` gives PPV 0.015/0.02/0.015 against
Blastware's 0.002.
- The range is never taken from the reference.
So the comparison takes an SFM-side record plus the parsed reference. The
runner assembles that record from the decoder and any SFM helpers. The
comparison itself stays pure codec-library code; only the runner (a lab tool)
may import from `sfm/`.
## The rule for disagreements (decided by Brian)
**Every mismatch is an SFM bug until shown otherwise.** A mismatch becomes an
"accepted difference" only through a written carve-out that names the fields
it covers and the rule it applies. Its evidence must not rest on SFM's own
output: Blastware contradicting itself, the instrument's own data (counts
in the file, the unit's embedded record), a third source (another instrument,
a known signal), or Instantel documentation. Each run reports how many events
each carve-out covers.
The carve-out list starts with one entry, already proven in
`scratch/verify_against_ascii.py`: **saturation**. On a clipped channel,
Blastware clamps its numbers to the range maximum and writes `OORANGE`, while
the file holds counts past full scale. Rounding to Blastware's printed
precision is a comparison rule, not a carve-out.
## Non-goals
- **Series 4 / Micromate.** Thor's IDF decode has its own CSV-based check, and
the 5,916 Micromate XMLs are noted for a later Series 4 checker.
- **Changing what SFM decodes.** The checker reports gaps; filling them is
piece 2.
- **Wiring the check into ingest, the watcher or Terra-View.** That's pieces
3/4. Nothing on prod changes.
- **ASCII reports as a reference.** The XML covers every year, including the
2025–26 events that have ASCII. The reference is parsed into a shape another
report format could fill later, but no ASCII adapter is built now.
## Anti-goals (would make it a failure even if it runs)
- **Comparing SFM with Blastware's own numbers.** The SFM side must come only
from the event file, through `decode_blastware_bytes` with no report
overlay. Nothing from the XML or ASCII report may reach the SFM side.
- **Hiding mismatches:** a carve-out without evidence, a tolerance looser
than Blastware's printed precision, or blanks counted as matches.
- **Wrong conversions:** counts converted to in/s with a range or scale that
came from the reference rather than the file. If SFM can't read the range
from the file yet, that is a gap to report, not something to borrow.
- **A report that only says "N mismatches"** without grouping and examples.
It must be usable to find the cause.
- **A full run so slow it isn't run after every fix.**
## Constraints
- **Hardware:** runs on the dev box (4 cores, ~17 GB free disk after the
22 GB XML copy; Brian can add space).
- **Read-only:** it never writes to the corpus folders and needs no network.
- **Speed:** a full run over all 70,042 events in **under an hour**. A
partial run (by serial, year, event type or field group, or a random sample)
in **a few minutes**. The setup/notes harness covering ~6 fields took ~4
minutes with 4 processes. Samples and intervals add parsing 22 GB of XML.
The standard library parses at ~45 MB/s per core (`lxml` is not
installed), which fits the budget.
- **Codec library purity (ADR 0003):** the codec library stays pure. Bench and
lab tools stay out of the production image.
- **Results contain customer project names**, so run output is kept outside
the repo and never committed.
## What's decided, and by whom
**Brian:**
- SFM's data comes only from the binary; reports are for checking.
- The disagreement rule and carve-outs above.
- The two outputs: a summary for him, a detailed report for Claude to diagnose.
- Repeated runs with run-to-run comparison.
- It lives in seismo-relay, and the comparison is library code.
- Series 3 only. Nothing on prod or in Terra-View changes.
**Claude's calls (correct if wrong):**
- The XML is the single reference.
- **Placement:**
- The XML report parser belongs in the codec library, a sibling of
`minimateplus/bw_ascii_report.py`.
- The comparison (one decoded `Event` + one parsed report → verdicts per
field) is pure and belongs in the codec library too.
- The batch runner is a lab tool (`scratch/`), per ADR 0003.
- The carve-out list lives in the repo next to the comparison, as code or
data the comparison reads, with each entry's evidence written beside it.
- **Grouping attributes for the detailed report:**
- device model (from `Version`), serial
- event type, event year
- sample rate, geophone range, mic units/weighting, interval size
- whether the setup is named "Standard Recording Setup"
- which decoder path produced the samples, where the decoder exposes it
- `scratch/verify_bw_fields_against_xml.py` (committed `f46afaf`) is the
starting point. It already handles the notes/job-number layout and the
rounding rule. The checker replaces it.
**Left to the builder:**
- module, function and file names; the output file formats
- how runs are stored and compared
- parallelism and any caching of decode or parse results
- the CLI shape, as long as the partial-run filters and single-event re-run
exist
## What success looks like
- **One command** produces the summary and the detailed report for all 70,042
events within the time budget.
- **The first run reproduces what is known**, which is how we tell the
checker is honest:
- sample rate, record time, pre-trigger and notes match everywhere
- `T438HGTZ.B30W` matches. Its Tran, Vert and MicL end 3 samples before
Long, and Blastware's own table does the same: its last rows carry only
the Long cell. An earlier harness that compared one channel's length with
the table's row count called this a decoder truncation; it was not.
- samples and histogram intervals match on the 2025–26 events, as
`verify_against_ascii.py` showed, **except the events on the 1.250 in/s
range**, which are 8× high (5 of them in 2025–26, 35 in all)
- event type mismatches on every histogram, because no filename is given
(#41)
- job number and the calculated values (ZC frequency, acceleration,
displacement, time of peak, sensor check, battery, calibration, trigger
levels, range, units, monitor log) show up as SFM blank
- the three `#53` files fail loudly as waveform time mismatches, 4 s off.
The decoder picks an earlier, false footer and records no
`decode_problems`. The `#53` description in
`docs/instantel_protocol_reference.md`, which says they decode as
histograms, is out of date.
- Every non-match group in the detailed report carries example files and a
re-run command.
- Tests cover the XML parser on real fixture reports with literal expected
values, every comparison rule (rounding, `&gt;100`, `N/A`, `OORANGE`,
units), carve-out accounting, and a guard that the SFM side never sees the
reference.
@@ -0,0 +1,403 @@
# Phase 5: changing a unit's settings by serial (design)
**Date:** 2026-11-03. **Status:** approved by Brian 2026-11-03; built 2026-11-03
(plan `docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md`); **benched 2026-11-04** on both
series (results at the end). Phase 5 of
`docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` (row 10, "change
recording settings"; build phase 5, "setup push: one field first, then several").
**Branch:** `feat/series4-sfm-parity`.
## Intent (Brian, 2026-11-03)
Change **any** of a unit's settings from SFM, and make it as easy and reliable as
possible. The goal is to fix what makes Blastware finicky. Three real cases:
- **One wrong number on a deployed unit.** UM6047 was out monitoring with its
geophone trigger at 0.03 instead of 0.300. Brian remoted into the THOR PC,
stopped it (it called in), changed the setup, made sure it was *sent*, then
restarted monitoring.
- **A typo in the notes.**
- **A backup unit.** The unit set up at the office fails in the field, so a backup
from the truck goes in with blank or stale notes and settings. There is no
computer in the field, so the office re-does the whole setup remotely, by hand,
while the person in the field stands by to press Start or power-cycle if the
link breaks.
What is wrong with THOR, as Brian and his dad experience it:
- The same screen edits a setup on disk and views a unit's setup.
- Setups get saved under random number strings.
- Editing a setup does not change the unit; you verify separately that it was sent.
Saved setups as templates would be acceptable. Not knowing whether you are
changing the unit or a file is not.
## Goals, non-goals, anti-goals
**Goals**
- Edit the unit's **live** settings, both series.
- Show exactly what will change, **old → new**, before anything is sent.
- After sending, **re-read the unit** and show what it now holds.
- Make every refusal say why, in plain words.
**Non-goals (this phase)**
- Templates, saved setups, copying from another unit.
- Restarting monitoring. **Brian presses Start**, as today; SFM never restarts on
its own.
- Setting the unit's clock. That is a later call-home receiver rule.
- **Writing the Micromate scheduler.** Next project, agreed 2026-11-03:
"record during work hours" as a plain, **configurable** setting on the unit's
page, both series, no schedule library and no setup files. On the Micromate,
it relies on the firmware's setup-less scheduler start (found in the firmware,
never sent; one bench session). On the MiniMate, its own timer setting
(undecoded). Brian's dad despises THOR's scheduler; Brian is willing to retire
it in SFM.
- Fields not yet decoded. "Any and all" grows as decoding grows.
**Anti-goals: things that would make it a failure even if it "works"**
- Any doubt about whether the unit changed.
- A screen where a file and a unit look alike, or a name SFM made up.
- Writing a byte SFM did not just read. Every byte SFM does not deliberately change
goes back exactly as read. The one exception is a byte that Blastware's (or
THOR's) own writes always set to a fixed value. Each such byte is named in the
codec with its evidence (so far: Series 3 `[26:28]` → `00 00`; my call, below).
- Sending to a monitoring unit.
- A retry. A write is sent once; what happened is read back.
## Measured basis
**1. Series 4 (Micromate): the `0x1A` setup content map.** Measured from 47
keypad snapshots on UM20147 and checksum-verified. `micromate/setup_block.py`
(`decode_setup`) reads it, with 69 tests on 15 fixtures.
| content | field |
|---|---|
| `[5]` | record mode |
| `[6:8]` | sample rate |
| `[8:10]` | histogram interval |
| `[12:16]` | pre-trigger, f32, negative |
| `[17]` | stop mode |
| `[18:22]` | record time, f32 |
| `[23]` | auto-stop |
| `[25]` | active sensors |
| `[29]` | trigger sources |
| `[30:34]` | distance |
| `[34:38]` | charge |
| `[39]` | report flags |
| `[40:42]` | job number |
| `[42:86]` | setup name |
| `[122+64n]` / `[144+64n]` | notes (label / value) |
| from `[1708]` | 48-byte channel blocks: sensor code `+4:8`, trigger `+30` (geo in/s, mic psi) |
The CRC-16/AUG-CCITT over `[0:2088]` is stored at `[2090:2092]`; THOR's write
omits it and the unit recomputes it.
- **The push sequence (from THOR's captures)** is `0xDA` (name) → `0x68`/`0x73`
(`0x08` preferences) → `0x82`/`0x83` (`0x2E` trigger) → `0x71`/`0x72` (`0x1A`
setup). `micromate.writes.plan_setup_push` reproduces THOR's frames (phase 2).
- **Not yet mapped on Series 4:** alarm level, geophone range, GPS, aux I/O, SLM
options.
**2. Series 3 (MiniMate) uses the same layout. Measured 2026-11-03.** The
compliance image as Blastware writes it is logical (unescaped), 2,092 bytes, with
`N = 2090` at `[0:2]` and the channel block "Tran" at `[1708]`.
`micromate.setup_block.decode_setup` reads it correctly:
- **BE9441's 10-26 write** (`tests/fixtures/minimate-bench-10-26-26-histogram`,
two whole sends): name, mode, 4096 sps, interval, record time 20 s, trigger
0.04 in/s, mic linear, job number and the notes all decode. Only the CRC fails
(Series 3's tail goes out stale).
- **BE11529's nine 2026-04-20 Blastware writes** (`bridges/captures/4-20-26/`,
every one with a whole image) each changed exactly the expected bytes:
| Blastware changed | bytes that moved |
|---|---|
| histogram interval (×4) | `[8:10]` |
| recording mode (×3) | `[5]` |
| geophone range | `1737` / `1785` / `1833`, the range byte at each geophone channel label `+29` |
- **The live `SUB 1A` read starts the same block.** Measured on the first data
frame of each of the four recorded reads (`_settings_replies` in
`tests/test_s3_compliance_anchor_fields.py`): unescaped, each carries `N = 2090`
12 bytes before the old "anchor", and content `[5]` reads 1 / 4 / 3 / 3. That
anchor (`be 80 00 00 00 00`) is content `[12:18]`, pre-trigger −0.25 plus stop
mode Fixed. So Series 3 can be read by content offset rather than by anchor
search, which survives an Auto-stop unit (the open question of 2026-10-17).
- **A whole `1A` read assembles to exactly the 2,090 content bytes** (measured
2026-11-03 on BE9441's 10-26 recording, 12 reads). Unescape each data frame and
take `data[11:]`. Every frame but the last then starts with one `00` byte that is
not content; drop it. This holds for Blastware's read (four 512-byte frames plus
42) and SFM's (two 1024-byte frames plus 42).
- **The round trip is exact.** Blastware re-read the block after each of its two
writes, and each re-read equals the image it had just written, all 2,090 bytes.
- **While monitoring**, the read returns `0e 'BE9441' …` (the device-info block),
as the 10-29 finding says. The unit was monitoring for 5 of the 12 reads.
- **Bytes `[26:28]`: Blastware always writes `00 00`** (all 11 writes), though the
unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19).
The unit sets them again by itself. Meaning unknown.
- **The two bytes after the block are Blastware's own.** Blastware sends a per-unit
constant: `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's.
It is not the block's CRC-16/AUG, and no reply in BE9441's three-hour session
contains it. SFM's `write_image` sends `00 00` there. Since a read never returns
those bytes, the read-back cannot show what the unit did with them.
- **The mode byte is shared, but its codes are not.** Series 3: `00` Single Shot,
`01` Continuous, `03` Histogram, `04` Histogram + Continuous. Series 4: `01`
Waveform, `02` Manual, `03` Histogram, `04` Combo.
- **Rules from the checker's file-side work** (seismo-relay-b6, 2026-11-03; it
measured the same content offsets on 70,042 event files and found nothing that
contradicts one shared map):
- A bitmask byte is patched **bit by bit, never rebuilt**. The trigger-sources
byte `[29]` showed an unidentified `0x80` bit on one unit.
- On Series 3, stop mode (`0` Fixed) and mic type (`2` linear) are proven for
one value each. They are not offered for writing.
- An event file's `[12:16]` is that event's captured pre-trigger, not the
setting. SFM writes only from a live read, so this matters only to anyone
tempted to build a write from a file.
- **Series-3-only fields** (measured on Series 3, not Series 4): the geophone range
byte at channel `+29`; the alarm level at channel `+38` (checker-measured on
event files; live raw `+42`).
**3. Series 3 write frames are measured (#46).** Writes use uniform escaping with
a length field. The compliance image goes in 512-byte addressed chunks. `0x68` is
written as read plus `02 00`, `0x82` plus `00 00`. The sequence is
`68→73 | 71×n→72 | 82→83 | 69→74→72`. `push_config_raw` refuses any block that
is not whole. `tests/test_minimate_write_frames.py` rebuilds Blastware's frames
byte for byte.
**4. Monitoring.**
- **Series 3:** while monitoring, the unit answers `1A` (and `0x2C`) with its
device-info block (measured 10-29 and 11-03).
- **Series 4:** it refuses call-home setup while monitoring ("Feature disabled
while monitoring", measured 11-03).
- **A stop with call-home on makes the unit call in** (measured 10-25, 10-29,
11-03).
**5. Series 4 specifics.**
- `0x1A` reads the keypad's edit buffer live: unsaved keypad edits show in the
read, and a push would commit them.
- Loading a `.MMB` replaces the active config byte for byte. The push writes
under the active setup's name (`0xDA`).
## The flow
1. **Read.** `GET /device/settings?serial=…` (it exists) returns the unit's
settings. The page shows them on the Config tab under **"On the unit BE9441 —
read 14:03"**, never anything that looks like a file.
2. **Edit and preview.** The operator changes fields, then **Preview**: a dry run.
SFM re-reads the unit's blocks on the same line, builds the new blocks, and
returns one row per field: **old → new**, plus any warnings. Nothing is sent.
3. **Send.** The same request, live, is an audited change:
- identity check, audit row, one send, never retried, read back;
- **refused with "stop monitoring first"** if the unit is monitoring, noting
that the stop makes it call in when call-home is on;
- **refused** if the unit's settings changed since the preview. The preview
carries a revision (a hash of the blocks read), and the live call must
match it.
4. **Verify.** Re-read the blocks. Every changed field must read its new value.
Every other decoded field, and every byte SFM did not deliberately change, must
read as before. The page shows **"the unit now holds"**: field, old, new, now.
Known unit-maintained bytes (the Series-4 CRC) are compared as the unit's own
checksum (`crc_ok`), not byte for byte.
5. **Start** stays the operator's button.
## Fields in the first version (Brian approved the list)
| field | Series 3 | Series 4 |
|---|---|---|
| geophone trigger level | yes (channel `+30`) | yes (channel `+30`) |
| alarm level | yes (channel `+38`; measure live) | not mapped, so not offered |
| notes: the four note slots, by the unit's own labels | yes (`Project:`, `Client:`, `User Name:`, `Seis. Loc:` on BE9441) | yes (`Location`, `Client`, `Company`, `General Notes`) |
| recording mode | yes (`[5]`; values as measured on Series 3) | yes (`[5]`; Series-4 codes) |
| sample rate | yes | yes |
| record time | yes | yes |
| histogram interval | yes | yes |
| geophone range | yes (channel `+29`) | not mapped, so not offered |
| job number (+ shown on report) | yes | yes |
A field is offered only where it is measured for that series. Values are refused
unless they are among the measured choices: sample rates 1024/2048/4096,
intervals 2/5/15/60/300/900 s, and each series' measured mode codes.
- **Numbers: the units' own limits (Brian, 2026-11-03: "I want to use the actual
unit limits, not just what we have done in the past").** From Instantel's
operator manuals in `~/seismo-relay/manuals/`:
- **Geophone trigger:** 0.005–10 in/s in steps of 0.001 (MiniMate Plus manual
716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual
721U0201 Rev 06, *Geophone Trigger Level*). It is also capped at the range's
full scale (10 / 1.25 in/s). When range and trigger change in one request,
check the trigger against the **new** range.
- **Record time:**
- Micromate: 1–90 s (*Record Time*).
- MiniMate: from 1 s to the manual's §4.4 *Maximum Record Times* for a
1 MB unit, four channels, at the chosen sample rate: 104 s at 1024 sps,
52 s at 2048, 26 s at 4096. In Histogram Combo, 13 s (§3.8.9). The units
measured report about 960 KB in total memory (BE11529: 983,026 bytes), the
1 MB model.
- **Job number:** 1–9999 (both manuals).
- **The read-back is the safety net.** A unit that does not take a value (for
instance, cuts a record time to what its memory allows) shows as not taken,
with what it actually holds.
- Values seen across 75,958 Blastware reports (2016–2026) sit well inside these
limits: trigger 0.005–0.500 in/s, record time 1–10 s, job number 1.
- **Units:** refuse a level write unless the channel's unit string reads the
measured one (`in.` for a geophone). A unit set to Metric is unmeasured.
- **Notes:** edited by slot, under the label the unit itself shows (labels can be
renamed and are not identifiers). The value is at most its field width less
one byte, printable ASCII.
- Not in v1: Series 3's fifth slot, `Extended Notes` (value `\n` on BE9441).
Blastware's extended notes are unmeasured and may live elsewhere.
- Not in v1: Series 4's 16-byte field at content `[1064]` (`Loc 1` on
UM12947), undecoded.
## Architecture
- **One setup-block codec for both series.** Keep `micromate/setup_block.py` as
the field map and add `encode_setup(content, changes) -> content`: field patches
only, every other byte as given. It stays a pure codec library: no I/O, no
`sfm` imports, no import cycle with `minimateplus`. Series-specific fields (the
Series-3 range and alarm) are marked by series.
- **Series 3 read.** Assemble the `1A` read into the logical 2,090-byte block:
unescape, strip the 12-byte reply prefix and the inter-frame headers
(`read_compliance_config`). Decode it by content offset.
- **Series 3 write.** The patched logical block plus the tail becomes the
compliance image for `push_config_raw`. Event index (`0x08`), trigger (`0x2E`)
and waveform data (`0x09`) are echoed as read, in Blastware's sequence.
- On `0x09`, Blastware echoed the unit's bytes on all nine April writes
(`[200:202]` = `8c 76` read and written). Only BE9441's 10-26 writes changed
them (`17 17` read, `78 76` written, and read back so). The meaning is
unknown, so SFM echoes.
- **The raw-offset `_encode_compliance_config` is retired.**
- **The legacy write (`/device/config`, `/device/config/project`) is retired (my
call).** It retries a whole write on a TCP error, is not audited, does no
read-back, does not refuse a monitoring unit, and needs no serial: every
anti-goal at once. Its only user is the webapp's by-host Config form, and
Terra-View does not call it. Its routes answer with a pointer to the by-serial
change, and the by-host form becomes read-only.
- **Series 4 write.** `plan_setup_push(prefs, trigger, patched_setup, name)`.
- **No setup files in the operator's view (Brian, 2026-11-03).** "We treat the
Micromate setups just like Minimate setups … the unit just has its settings,
and we change it based on the job. We don't send setups to the unit." A
backup unit is usually on whatever setup its previous job left. So SFM
rewrites the setup the unit is running, in place, under its own name. It
never asks for a file or a name, and never creates one. The name may show as
a read-only detail, since the unit's screen shows it.
- **The scheduler can undo a change (Brian, 2026-11-03, with THOR's Manage
Schedules screen).** Work-hours Micromates run a THOR schedule, e.g. Start
Monitoring 07:00 with setup `Mele-PWSA-Carroll -Loc 4`, stop 18:30, repeat
daily. THOR sends the schedule with its setup, and each scheduled start loads
the setup it names. So the preview and the send read `schedule.dat` (format
decoded, reference *The schedule record format*), read-only. A start action
naming a setup other than the one being changed blocks the send: "this unit's
schedule loads <name> at 07:00, which would replace this change." When the
schedule names the active setup (the usual case after a scheduled start), the
change survives, and the preview says when the next scheduled start is.
SFM never writes the schedule in this phase.
- The name comes from the `0x41` read, unstripped.
- Refuse `factory.MMB` and any target that is not the active setup (spec). The
refusal says it plainly: "this unit is running its factory setup; load any
other setup on its keypad, then try again." Brian says the team does not use
the factory setup, so this should be rare.
- `ENABLEABLE_WRITES` gains `0xDA 0x68 0x73 0x82 0x83 0x71 0x72`.
- The keypad edit buffer: warn in the preview that a unit with someone in its
menu would have those edits committed. The check the spec names, `0x1A`
against the active `.MMB` via `0x94`/`0x48`, is a bench question first.
- **The change path.** It keeps run_change's guarantees: identity, audit, one
send, read back, `ChangeUnconfirmed` with `sent`/`audit_id`. The "state" is a
set of fields, so either `run_change` takes a verify function or a sibling core
shares its parts. The builder decides; the guarantees do not change. The audit
row keeps the per-field changes, both blocks (hex) and the verdict.
- **Routes.** `POST /device/settings/change?serial=…` (serial required) with body
`{changes: {field: value}, revision}` and `dry_run`, `caller`. The response is
per-field `old` / `new` / `now`, through `_change_response`. A dry run needs no
revision and returns one. **A live call without the revision of a preview is
refused** (my call): nothing reaches a unit unless someone saw old → new.
- **Page.** The Config tab by serial becomes the unit's edit form: Preview → Send
(confirm) → "the unit now holds". New logic goes in
`sfm/static/device_routing.js` with Node tests, and glue in
`sfm/static/sfm_webapp.js` (no inline JS).
## Verification
- **Series 3, byte for byte.** For each of the 11 Blastware compliance writes,
apply the new encoder to the read before it (or the previous image), with the
fields Blastware changed. It must reproduce Blastware's content `[0:2090]`. The
two trailing bytes are compared separately, since they are Blastware's constant.
Ten writes change one field. BE9441's 16:26 write changes five things: mode,
sample rate 2048 → 4096, interval, the mic in the sensors byte `[25]`, and
`[26:28]`. That one is tested with all of them, through the codec, though v1's
page does not offer the sensors byte.
The frames rebuild through `push_config_raw`'s path (the #46 tests).
- **Series 3, read side.** The assembly rule above, pinned as a test on the 12
reads of BE9441's 10-26 recording. Each read-back equals the write before it.
- **Series 4.** THOR's setup-push captures still reproduce, with no field changed.
Any capture where THOR changed a field becomes a byte-for-byte test.
- **Bench, with Brian's go per send, per series:**
1. A dry run of a trigger change, then send, read back, check the unit's menu,
and change it back.
2. A notes change.
3. A several-field "backup unit" change.
4. A dry run while monitoring, expecting the refusal.
## Bench 2026-11-04 (results)
Brian at BE9441 and UM20147, each on its own modem; every send with his go.
Notes: `~/bench-logs/2026-11-04-sfm-settings/`.
- **Both series change correctly.** Each change was acknowledged, read back as
sent, and confirmed on the unit's own screen; both units ended byte for byte as
found.
- BE9441: trigger each way, a note, several fields at once, the alarm, a full
restore.
- UM20147: trigger, several fields (two notes, job number and its flag, record
time), a full restore. The unit's recomputed CRC equalled SFM's.
- **Fixed at the bench (`9992b25`):** the first live MiniMate read came back one
byte long. An escaped checksum byte leaves its `0x10` behind (about 1 frame in
85; the recordings never had it). The read now takes exactly the lengths it
asked for, and so does the waveform read (`c790e20`).
- **🔑 The keypad menu wins.** A MiniMate change sent while its setup menu is
open is acknowledged and read back, then lost when the operator presses Cancel
or Save: the menu writes its copy of the whole block back. SFM cannot see this
happen; the MiniMate preview now warns. Rule for the field-plus-office routine:
nobody in the unit's menus while the office sends.
- **The MiniMate alarm write is measured**, so it is now writable (`55c7b7b`).
- **Refused while recording, both series, nothing sent.** A recording MiniMate
sometimes leaves a preview at "no answer" rather than the refusal.
- **The Micromate scheduler switch is in no block SFM reads.** UM20147 carries a
leftover THOR schedule (Fay setup, 07:00 daily) with the switch Off; SFM blocks
it, a false alarm here. The bench used a scratch-only override.
- Next: a THOR bridge recording to find the switch (parked for work hours).
- Meanwhile, worth considering: let the operator confirm "scheduler off" in the
preview.
## Calls I made (Claude), for Brian to check
- **Series 3 `[26:28]` goes out as `00 00`, as Blastware writes it**, rather than
the `01 7f` the unit may read. Measured beats inferred: Blastware's value is on
11 accepted writes, and writing back `01 7f` has never been tried.
- **The two bytes after the Series 3 block stay `00 00`**, as `write_image` sends
them (a unit accepted that in the April 2026 test). Blastware's per-unit
constant cannot be derived from anything SFM reads. The first bench write checks
that the unit takes the block, and its menu shows the change.
- **The `0x09` block is echoed as read**, as Blastware did on all nine April writes.
- **Level writes are refused unless the channel's unit string is the measured
`in.` / `in`** (a unit set to Metric is unmeasured).
- **Notes are edited by slot under the unit's own labels**, four slots on each
series. Series 3 extended notes and Series 4's separate location field wait.
- **The legacy by-host write is retired**; the by-host form becomes read-only.
- **A live send needs a preview's revision.**
- **Preview re-reads the unit** rather than trusting the page's copy, and Send
refuses if the unit changed since the preview.
- **The edit form lives on the Config tab, by serial**, replacing the legacy
read-modify-write form for units reached by serial.
## Left to the builder
- The module layout for the shared codec, within the no-cycle, pure-codec rule.
- `run_change` generalised versus a sibling core.
- The exact revision hash.
- Page layout details.
@@ -0,0 +1,333 @@
# Monitor logs (.MLG) and each unit's monitoring timeline — design
**Date:** 2026-11-09 · **Branch:** `feat/mlg-import` (worktree `~/seismo-relay-mlg`) ·
**Status:** design, for review
## Why this exists
Every Series-3 unit sends a Blastware monitor log, an `.MLG` file, at every call-in, whatever mode
it is recording in. It lists each time the unit started monitoring, each event, and each time it
stopped and why. Event files cannot replace it: a unit in continuous (waveform) mode sends an event
file only when something triggers, so a quiet day leaves no file at all.
Brian named two uses (2026-11-09):
1. **Shot reports.** Every event from every unit on a site goes in the report. A unit that did not
trigger (often the farthest one) is listed as "did not trigger", with its printed `.MLG`
attached as proof it was monitoring at the time of the blast. Example: BE6907 and BE12844
monitored the same job, June to November 2026, both in continuous mode. BE6907 is much farther
away and recorded 10 events to BE12844's 55.
2. **Outage history.** It is good to know when a unit was not recording, for how long, and why. A
unit on solar and battery can die for a weekend and nobody would notice. Most units keep
recording when they cannot call in; only losing the power and then the internal battery stops
them. So this is history seen once the unit calls in again, not a live alarm.
The `.MLG` is also what the watcher's heartbeat sniffs today to show that a unit is still calling
in. SFM holding the files would later let it answer that itself.
## Goals
1. Read a Blastware `.MLG` into its records, with every record's checksum verified.
2. Accept forwarded `.MLG`s through a new import route, storing each record once.
3. Keep each unit's monitoring timeline, derived from its records: when it was recording, how each
session ended, the events inside, and the call-ins. It must answer two questions:
- was unit X monitoring at time T, and with what trigger level?
- when was it not monitoring, for how long, and why?
4. Serve the records and the timeline through `/db/*`, for Terra-View to use later.
5. Bulk-import a directory of `.MLG`s (DL2 holds about 86,000), and cross-check the records against
the event files' footers.
## Non-goals
- **The watcher forwarding `.MLG`s.** That is a change in `../series3-watcher`, Brian's call, and a
separate piece. Until it lands, `.MLG`s reach SFM only through the import route and the bulk tool.
- **Anything in Terra-View:** the timeline view, the shot report, taking "last call-in" from SFM
instead of the heartbeat. Later pieces.
- **Live "missed its call-in" alerts.** A dead unit sends nothing; this timeline shows the gap
once it is back.
- **Series 4.** Thor writes no `.MLG`.
- **Editing the event decoders** (`event_file_io.py`, `decode_check.py`, `histogram_codec.py`,
`waveform_codec.py`). Another session owns them; this project imports from them only.
## Anti-goals (would make it a failure even if it works)
- **Claiming monitoring the data does not show.** A session still open at the last call-in is
"running at the last call-in", never "running now". Where a session's end is not recorded, the
timeline says so and gives the window it lies in.
- **Dropping a damaged file or record silently.** A record that fails its checksum is reported,
never half-read into the timeline.
- **Taking the serial from the file name when the file carries it.** Names are `<serial><counter>`
with nothing between, so `BE11010304` cannot be split by reading it.
- **Mixing clocks.** Record times are the unit's own local clock. File times are the PC's. They are
stored and labelled separately.
## What was measured
Grades: **measured** means checked on the files named; **inferred** means a reading of them that
has not been tested.
**Files examined:** 1,273 `.MLG`s from DL2's `C:\Blastware 10\Event\autocall home` (BE6907 369 and
BE12844 197, from 2026; BE8081 707, 2018–19), in `~/dl2-archive/mlg/`. Also the 9 bench files in
`example-events/`. Analysis scripts used for this section are in the session scratchpad and are
not part of the build.
### The file format (measured on all 1,282 files)
- **Layout:** an 18-byte prefix `10 00 01 80 00 00 "Instantel\0" 07 2c`, then whole 292-byte
records. The size is always `18 + 292·n`.
- **Every record** is `[length uint16 LE = 0x0122 (290)][id 2 bytes] … [CRC 2 bytes]`. Id `0e a0` is
the header record (one, first, carrying the serial). Id `0e 80` is a log record.
- **Checksum:** CRC-16/AUG-CCITT (poly 0x1021, init 0x1D0F, no reflection) over the record's bytes
`[0:288]`, stored little-endian at `[290:292]`. Bytes `[288:290]` are `00 00` and not covered.
This is the rule the Micromate setup blocks use (`micromate.setup_block`). It matches **3,329 of
3,329** records, with no failures.
- The reference (D.4.2) put a CRC at the *start* of each record. That was the previous record's
tail, which is also why every file had 2 unexplained bytes at its end.
- **A log record** (offsets from its length field):
| offset | field |
|---|---|
| `[4:12]` | start: day, month, year **LE**, 0, hour, min, sec |
| `[12:20]` | stop, same format; all zeros = no stop |
| `[20:22]` | monitor-log flag word, uint16 LE: the same word as the event footer's (D.6.14) |
| `[22:24]` | trigger source, uint16 LE: `0x0001`–`0x0008` a channel, `0x0400` a histogram |
| `[24:34]` | serial, null-padded ASCII |
| `[34:…]` | text, null-padded (below) |
- **Text:**
- a "monitoring started" record: `Trigger Level : Geo: 0.0500 in/s Mic: 125.0 dB(L)`, or
`Trigger Level : Histogram`
- an event record: `08`, then the event time in 8 bytes (LE year), then
`Geo: 0.0500 in/s Mic: 125.0 dB(L)`
- a closed session: `Geo: 0.0500 in/s Mic: 125.0 dB(L)`
- **Empty files:** some files are the 18-byte prefix alone, with no records and so no serial inside.
### How Blastware writes them (measured on the 3 DL2 units)
- **One file per call-in**, named `<serial><counter>.MLG`, the counter going up by one each time.
- **No record appears in two files.** Each holds what happened since the previous call-in.
- **A file is written 1–2 minutes after the unit stops for its call-in** ("Modem Exit"). The unit's
clock and DL2's agree to within those 2 minutes.
- ⚠ Dates of files that came through a Windows zip read an hour early from March to October.
Windows converts with the offset in force at zip time, not the one at the file's date. A
robocopy copy keeps the true time.
- **BE6907 writes two empty files 2–3 minutes after nearly every real one** (230 of its 369).
BE12844 never does; BE8081 did once in 707 (`BE80811.MLG`, 2018-02-19; corrected 2026-11-13
by the final review). Inferred: the unit calls back in and has nothing new.
- **Some files hold more than one Modem Exit:** 38 files (BE8081 33, BE6907 3, BE12844 2). A
file is written just after its *last* Modem Exit. The earlier ones are calls that left no file.
Example: `BE8081321` holds Modem Exits on 2019-04-12 18:33, 04-13 07:00 and 04-15 17:15.
- Inferred: the call failed, or the PC did not take it.
- Either way, this is the "missed call-in" history Brian asked about.
- **The unit's clock steps back an hour at the first call-in after daylight saving ends.** On
2026-11-01 BE12844 ran `06:00:13 → 18:45:00` (unit still on EDT). It called in at 17:46 EST,
and its next session is `17:47:25 → 18:45:00`. BE6907 shows the same. So local times on that day
overlap. Inferred: Blastware sets the unit's clock at the call-in, and in spring the clock
steps forward the same way.
- **Blastware writes the text, not the unit.** The two bench copies of the same records
(`ach-vs-manual/BE11529.MLG`, `BE115292.MLG`) differ only in `Trigger Level: Histogram` vs
`Trigger Level : Histogram`. A record's identity must not include its text or its checksum.
- **Cable or direct downloads are cumulative.** The bench `4-3-26-multi/BE11529.MLG` repeats the
4-1 records. Only the call-in files hold "only what is new".
### How a session appears (measured on the 3 DL2 units)
- **A session with no events** is one closed record: start, stop and why it stopped. BE12844's day:
`06:00:13 → 18:45:00` "Modem Exit" (its call-in), then `18:47 → 20:00` "Timer Stop" (a
work-hours timer).
- **A session with events** is an open "monitoring started" record (flag word `ffff`, no stop),
then one record per event (`0x0001` + the channel). The unit calls in minutes after each event,
and monitoring resumes as a *new* session minutes later. Example, BE12844 on 9-8:
- `06:00:13` started, then an event `13:38:22 → 13:38:25` (Tran)
- a file written about a minute later
- next file: `13:41:16 → 18:45:00` "Modem Exit"
The first session's end is not written anywhere. It lies between the last event's stop and the
next session's start (inferred: the call-in after the event ended it).
- **A histogram session** is a "monitoring started" record at T, then a histogram record from T+1 s
to the stop, carrying the stop reason (`0x0021` = Event Recorded + Modem Exit, source `0x0400`).
- **A histogram + waveform session** also has waveform event records whose start falls inside the
histogram record's span (BE8081, 5 in 2018). Example: histogram `15:15:32 → 15:15:49`, with a
Vert event `15:15:47 → 15:15:49`. Its trigger-level text says only "Histogram". The geophone
level appears only on its event records.
### Cross-check against the event files (measured)
Each "Event Recorded" record was matched to DL2's event files by **stop time + flag word + trigger
source**:
- **BE8081:** 785 / 785 records match an event file, and all 785 of its DL2 event files in that
period have a record. 714 histogram footers start exactly at the session's "monitoring started"
record; the other 71 start where the record does.
- **BE6907 / BE12844:** 25 / 25 event files have a record. The 42 records with no file all stop
after 2026-08-25, where the DL2 copy ends.
- On 2026-08-27 both units triggered at 13:00:42 / 13:00:43, the same blast.
## Design
### 1. The reader (codec library: pure, no I/O beyond the file)
`read_mlg(path)` replaces the stub in `minimateplus/blastware_file.py` and returns a new model
(`MlgFile`, `MlgRecord` in `models.py`). It does not reuse `MonitorLogEntry`, which is the live
0x0A shape. Per record:
- start, stop (None when open), flag word, trigger source
- Blastware's words, from `event_file_io.monitor_log_description()` (imported, not copied)
- the text, plus the trigger level and the event time parsed from it
- whether the checksum passed
Per file: the serial (from the header record; None for an empty file), the records, whether the
file is whole. A file whose size is not `18 + 292·n`, or with a bad prefix, raises. A record that
fails its checksum is returned flagged; the caller decides.
### 2. `write_mlg()` (last, small)
Fix it to write what Blastware writes: little-endian times, the length-led framing and the CRC.
Test: rebuild bench and DL2 files byte for byte from what the reader returns. If the header
record's unread bytes stop that, say so and leave the writer as it is.
### 3. Storage (`sfm/database.py`)
- **The original file is kept, byte for byte,** in the waveform store beside the unit's event
files. Files are tiny (18 bytes to a few KB). It is the shot-report proof, and Blastware can
open and print it. Rows alone cannot rebuild it, because Blastware's text varies.
- **`mlg_files`:** one row per file received:
- serial, file name, size, SHA-256, record count, an empty flag
- received time, and the file's modified time (UTC, when the sender gives it)
- whether it is a call-in file (default yes; a cable download is not)
The same name with the same bytes is a re-send and is skipped. Empty files all share one
hash, so the name keeps them apart. Some names have no counter (`BE8081.MLG` was DL2's first),
so name alone is not enough. This table is the call-in history, and the only trace of an empty
file.
- **`mlg_records`:** one row per log record: serial, start, stop, flag word, trigger source, text,
and the file it first came in. Stored once:
- unique on `(serial, start, stop, flag word, trigger source)`
- ⚠ an open record's stop is NULL, and SQLite treats NULLs as distinct in a UNIQUE constraint.
The key must handle that, for example with an index on `COALESCE(stop, '')`.
- **The existing `monitor_log` table is left alone.** It holds live 0x0A rows from
`bridges/ach_server.py`, which is not in production. A future SFM call-in server would write
`.MLG`-shaped records into `mlg_records` instead.
### 4. The timeline (computed when asked, not stored)
From a unit's records in time order:
- **A closed record** with no event bit is a session `[start, stop]`, ended for its reason.
- **A histogram record** is a session from its "monitoring started" record (or its own start, when
there is none) to its stop, ended for its reason.
- **A "monitoring started" record followed by events** is a session from that start. Its end is
"between the last event's stop and the next session's start".
- **A "monitoring started" record with nothing after it yet** is "running at the last call-in".
Gaps between sessions take the reason the previous session ended with:
| previous session ended with | the gap means |
|---|---|
| Modem Exit | a call-in |
| Timer Stop | scheduled off |
| Battery Low Exit | lost power |
| Keyboard Exit / Remote Exit | stopped by a person |
| Memory Full Exit | memory full |
| none known | unknown |
- **Waveform events inside a histogram session** belong to that session. They are not sessions
of their own.
- **Trigger level is reported as logged:** the session's text, plus any geophone level its event
records carry. It is never borrowed from a neighbouring session. A histogram session with no
events says "Histogram", geophone level not logged.
- **Clock steps:** a session that starts before the previous one stopped is a clock step, not an
overlap. The timeline shows it as such, with no negative gap. Times are the unit's local clock,
as SFM's event times are; `at`, `from_dt` and `to_dt` are in that clock. If `at` falls in a
repeated hour and matches two sessions, `monitoring_at` returns both and says so. The spring
step forward will show as a gap an hour too long on that one day; that is accepted.
**Call-ins** are listed by the call each file came from:
- **Delivered:** a call-in file's last Modem Exit (unit clock), paired with the file (PC clock).
- **No file:** the earlier Modem Exits in the same file. Calls that left no file.
- **Nothing new:** an empty file, at its file time.
Cable-download files are not call-ins.
### 5. Routes (`sfm/server.py`)
- `POST /db/import/mlg_file`: one or more files, an optional serial hint, each file's modified
time when the sender has it, and `call_in` (default true).
- Mirrors `/db/import/blastware_file`: each file gets its own status, and good files are stored
even when another in the same request is not.
- Per file it returns the serial, records inserted and skipped, and whether it was empty.
- A file with any failed checksum, or that is not whole, stores nothing of itself. Its status
names the record.
- `GET /db/mlg_files/{id}`: the original file, for printing or opening in Blastware.
- `GET /db/units/{serial}/timeline?from_dt=&to_dt=`: sessions (start, end or end window, how it
ended, its events, its trigger level), gaps with their meaning, and call-ins.
- `GET /db/units/{serial}/monitoring_at?at=`: `monitoring` / `not_monitoring` / `unknown`, with the
session and records that say so, and the trigger level. This is the shot report's question.
- `GET /db/mlg_records?serial=&from_dt=&to_dt=`: the raw records.
### 6. Serial of an empty file
An empty file holds no serial. Take, in order:
1. the request's serial hint
2. the longest serial SFM already knows (units, events, `.MLG` headers) that the name starts with
3. otherwise store the file with no serial and report it as unresolved
### 7. Tools
- **`scripts/import_mlg_dir.py <dir>`:** imports a directory tree of `.MLG`s straight into the DB,
with a dry run that prints the counts. Same pattern as the backfill scripts. For DL2's ~86,000.
- Every file it reads is a call-in file (it is pointed at the ACH folder's copy).
- It records file times as found, but they matter only for empty files. A zipped copy's times
are an hour early from March to October.
- The full DL2 import should come from a robocopy copy, which keeps true times.
- **`scratch/check_mlg_vs_events.py <mlg dir> <event dir>`:** the cross-check above, in both
directions, for the whole archive.
### 8. Documentation
- Rewrite the reference's D.4 (`docs/instantel_protocol_reference.md`) with the measured framing,
checksum, fields and file behaviour, keeping the old text as a retraction. Mark D.4.3 solved.
The file is CRLF: edit it with the Edit tool.
- 🔑 **The event-file footer's checksum** (D.3.3, open since April) is the same rule:
AUG-CCITT over the footer record from its length `00 1a` through byte 24, stored big-endian,
**70,041 / 70,041** DL2 files. Recorded on `dev` by the decoder session (`8544e9c`,
2026-11-11). Inferred: every record in the event file's tail chain (D.6.13) carries one.
## Testing
TDD. Fixtures go in a dated `tests/fixtures/` directory (force-added if ignored). A small set
covering each shape:
- a closed-records day (BE12844)
- a session with an event (BE12844 #3067–#3068)
- a histogram day (BE8081)
- a Battery Low Exit (BE8081)
- an empty 18-byte file (BE6907)
- a file with calls that left no file (`BE8081321`)
- the clock step back (BE12844 #3155–#3156)
- a histogram + waveform session (`BE8081.MLG`, 2018-02-16)
- the 4 bench files, including the `ach-vs-manual` pair whose text differs
Plus one file with a byte flipped, for the checksum.
The reader, the storage (including that an open record imported twice is stored once), the
timeline cases above and the routes each get tests. The full suite has 16 known failures; read the
failure list before committing.
## Left to the builder
- Model and helper names; the exact JSON shapes of the routes.
- Whether `read_mlg` moves into its own module later.
- What the header record's other bytes hold (all zero on the files seen).
- **Not in this project:** linking a session's events to SFM's stored event ids. Terra-View may
want that later. It needs a matcher, because the events table stores neither the stop time nor
the flag word, and its times moved in 0.32.0 and 0.34.0.
## Later pieces (not this project)
- **The watcher** forwards `.MLG`s with their modified time, and the heartbeat stops sniffing them.
- **Terra-View** shows each unit's timeline, puts "monitoring during the blast" on shot reports,
and takes "last call-in" from SFM.
- **BE6907's extra call-ins:** worth a look at its modem and call-home settings.
-107
View File
@@ -60,7 +60,6 @@ from minimateplus.framing import build_bw_frame, SESSION_RESET
from minimateplus.client import (
MiniMateClient,
_decode_compliance_config_into,
_encode_compliance_config,
)
from minimateplus.models import DeviceInfo
@@ -462,111 +461,6 @@ def exp_fewer_polls(host: str, port: int) -> tuple[str, str, dict]:
t.disconnect()
# ══════════════════════════════════════════════════════════════════════════════
# EXP6 — Compliance-only write (71×3→72), skip event index + trigger + waveform
# ══════════════════════════════════════════════════════════════════════════════
#
# Blastware's full write sequence: 68→73 | 71×3→72 | 82→83 | 69→74→72
# We want to know: can we write ONLY the compliance block (71×3→72)?
#
# Test procedure:
# 1. Read current compliance config (SUB 1A)
# 2. Patch the "notes" field to a test marker
# 3. Write ONLY 71×3→72 (skip 68, 73, 82, 83, 69, 74, final 72)
# 4. Read back (SUB 1A) and verify the change was written
# 5. Restore original value
#
# If PASS: we can push individual config fields without touching event index,
# trigger config, or waveform data — huge simplification.
# If FAIL: the device needs the full write sequence (may reject partial write).
#
# SAFETY: We restore original data in a finally block. If the restore write
# fails, the device will have the test marker in "notes" — harmless but visible.
_EXP6_MARKER = "[exp6-test]"
def exp_compliance_only(host: str, port: int) -> tuple[str, str, dict]:
"""Write compliance block alone (71×3→72), verify, and restore."""
client, info = connect_client(host, port)
original_raw: Optional[bytes] = None
try:
proto = client._proto
if proto is None:
return "FAIL", "Could not get protocol handle from client", {}
# 1. Read current compliance
print(" Reading current compliance config (SUB 1A)…")
original_raw = proto.read_compliance_config()
print(f" Got {len(original_raw)} bytes of compliance config")
# Find current notes value for display
info_obj = DeviceInfo()
_decode_compliance_config_into(original_raw, info_obj)
cc = info_obj.compliance_config
orig_notes = cc.notes if cc else "(unknown)"
print(f" Current notes field: {orig_notes!r}")
# 2. Build modified payload with test marker in notes
test_notes = _EXP6_MARKER
modified_raw = _encode_compliance_config(
original_raw,
notes=test_notes,
)
print(f" Encoded modified compliance payload ({len(modified_raw)} bytes)")
print(f" Patching notes: {orig_notes!r} → {test_notes!r}")
# 3. Write ONLY the compliance block: 71×3 → 72
print(" Writing compliance ONLY (71×3→72) — skipping 68/73/82/83/69/74…")
proto.write_compliance_config_raw(modified_raw)
print(" Write complete — device acked 71×3→72")
# 4. Read back and verify
print(" Reading back compliance config to verify…")
readback_raw = proto.read_compliance_config()
readback_info = DeviceInfo()
_decode_compliance_config_into(readback_raw, readback_info)
rb_cc = readback_info.compliance_config
readback_notes = rb_cc.notes if rb_cc else "(decode failed)"
print(f" Read-back notes: {readback_notes!r}")
write_worked = (readback_notes == test_notes)
print(f" Write verified: {write_worked}")
details = {
"original_notes": orig_notes,
"written_notes": test_notes,
"readback_notes": readback_notes,
"write_verified": write_worked,
}
if write_worked:
return "PASS", "Compliance-only write works! No event index or trigger writes needed.", details
else:
return "FAIL", f"Write was not reflected in read-back (got {readback_notes!r})", details
except ProtocolError as exc:
return "FAIL", f"Protocol error: {exc}", {}
finally:
# Restore original compliance data regardless of outcome
if original_raw is not None:
print(" Restoring original compliance config…")
try:
proto2 = client._proto
if proto2:
proto2.write_compliance_config_raw(
_encode_compliance_config(original_raw) # no-op patch = verbatim
)
print(" Restore complete")
else:
print(" WARNING: protocol handle gone — could not restore")
except Exception as exc_r:
print(f" WARNING: restore failed: {exc_r}")
client.close()
# ══════════════════════════════════════════════════════════════════════════════
# Registry + main
# ══════════════════════════════════════════════════════════════════════════════
EXPERIMENTS = {
@@ -575,7 +469,6 @@ EXPERIMENTS = {
"no_5a": ("EXP3", exp_no_5a, "Event record (0C) without bulk waveform (5A)"),
"skip_1e": ("EXP4", exp_skip_1e, "0A/0C with cached key — skip initial 1E"),
"fewer_polls": ("EXP5", exp_fewer_polls, "1 POLL before 5A instead of Blastware's 3"),
"compliance_only": ("EXP6", exp_compliance_only, "Compliance-only write (71×3→72), no other blocks"),
}
+28
View File
@@ -48,6 +48,7 @@ from .models import (
MicromateState,
)
from .protocol import MicromateProtocol, ProtocolError
from .schedule import SCHEDULE_PATH
from .setup_block import decode_setup
log = logging.getLogger(__name__)
@@ -333,6 +334,28 @@ class MicromateClient:
"""`SUB 0x41` — the loaded `.MMB` file name, e.g. `TEST1.mmb`."""
return _cstring(_content(self._proto.read_active_setup_name()))
def get_active_setup_raw(self) -> str:
"""The `0x41` name exactly as stored, up to its NUL -- NOT stripped, so a
setup push writes back the very name the unit holds."""
return _content(self._proto.read_active_setup_name()).split(b"\x00")[0].decode("ascii", "replace")
def get_prefs_content(self) -> bytes:
"""`SUB 0x08` -- the preferences block's content (a setup push sends it back)."""
return _content(self._proto.read_event_index())
def get_trigger_content(self) -> bytes:
"""`SUB 0x2E` -- the trigger block's content (a setup push sends it back)."""
return _content(self._proto.read_trigger_config())
def get_setup_content(self) -> bytes:
"""`SUB 0x1A` -- the setup block's content, undecoded (2,092 B, CRC last).
⚠ The keypad's edit buffer: unsaved menu edits come back too."""
return _content(self._proto.read_compliance_config())
def read_schedule(self) -> bytes:
"""`schedule.dat`, read-only (`micromate.schedule.parse_schedule` reads it)."""
return self._proto.read_file(SCHEDULE_PATH)
def get_setup(self, *, verify: bool = True) -> MicromateSetup:
"""`SUB 0x1A` — what the unit is set to, decoded. One read.
@@ -388,6 +411,11 @@ class MicromateClient:
# Anything else reads unknown(0x..): the safe default, which the change path refuses.
_RUN_STATES = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
def get_call_home_content(self) -> bytes:
"""The `0x2C` call-home block's 126-byte content (bit 0 of [5] is the
enable, [6:46] the dial string; [118:120] is unit-maintained)."""
return _content(self.protocol.read_call_home_config())
def read_run_state(self) -> MicromateRunState:
"""`SUB 0x49` -> the unit's run state, with the in-call-home value kept
(connect()'s `monitoring` bool flattens 0x03 into True)."""
+92 -33
View File
@@ -42,6 +42,7 @@ The full reverse-engineering writeup lives in
from __future__ import annotations
import datetime
import math
import struct
from dataclasses import dataclass
from pathlib import Path
@@ -66,7 +67,7 @@ from typing import Optional, Union
# error. Do not re-pin it.
from minimateplus.waveform_codec import _MODES, decode_waveform_v2, is_record
from .models import IdfEvent, IdfPeaks, IdfReport
from .models import IdfEvent, IdfPeaks, IdfProjectInfo, IdfReport
# Genuine Series IV / Thor IDF binary signature: 6 bytes, then ASCII "Instantel".
@@ -170,8 +171,46 @@ class IdfBinaryMetadata:
serial: Optional[str] = None
event_datetime: Optional[datetime.datetime] = None
sample_rate: Optional[int] = None
record_time_sec: Optional[float] = None
record_time_sec: Optional[float] = None # waveforms only
pre_trigger_sec: Optional[float] = None # waveforms only; this event's own, positive
calibration_date: Optional[datetime.date] = None
# The four notes, as Thor's report maps them (TitleString1..4).
project: Optional[str] = None
client: Optional[str] = None
operator: Optional[str] = None
notes: Optional[str] = None
# The event's settings record: `[00 2a][04 00 00][mode][rate u16 BE][…]
# [pre-trigger f32 BE, negative s at +12][…][record time f32 BE at +18]`, the
# same field offsets as the head of the live 0x1A setup block (setup_block.py).
# Found at 0x910, 0x946, 0x98e or 0x9c4 depending on the header's shape, so it is
# located by its signature, not its offset (measured on 2,384 files, 2026-11-20).
_SETTINGS_SIG = b"\x00\x2a\x04\x00\x00"
_SETTINGS_WINDOW = (0x800, 0xC00)
_SETTINGS_RATES = {256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536}
_EVENT_TIME_AFTER_SETTINGS = 0x34
# Four notes, each a 22-byte label then its 42-byte value, 64 bytes apart: the
# live setup block's note layout, at a fixed offset in every file seen.
_NOTES_AT, _NOTE_LABEL_LEN, _NOTE_VALUE_LEN, _NOTE_STRIDE = 0x23C, 22, 42, 64
_NOTE_FIELDS = ("project", "client", "operator", "notes")
def _settings_record(buf: bytes) -> Optional[int]:
"""Offset of the event's settings record, or None. Every field must be
plausible, which rejects a chance match of the signature."""
start, stop = _SETTINGS_WINDOW
o = buf.find(_SETTINGS_SIG, start, stop)
while o >= 0 and o + 22 <= len(buf):
rate = int.from_bytes(buf[o + 6 : o + 8], "big")
pre, = struct.unpack(">f", buf[o + 12 : o + 16])
rt, = struct.unpack(">f", buf[o + 18 : o + 22])
if (1 <= buf[o + 5] <= 4 and rate in _SETTINGS_RATES
and math.isfinite(pre) and -600.0 <= pre <= 0.0
and math.isfinite(rt) and rt >= 0.0):
return o
o = buf.find(_SETTINGS_SIG, o + 1, stop)
return None
def _read_ascii_z(buf: bytes, off: int, maxlen: int = 64) -> Optional[str]:
@@ -199,44 +238,47 @@ def _decode_8byte_timestamp(buf: bytes, off: int) -> Optional[datetime.datetime]
return None
def extract_binary_metadata(buf: bytes) -> IdfBinaryMetadata:
"""Pull serial/timestamp/sample_rate/record_time/calibration from the
sig-A binary header.
def extract_binary_metadata(buf: bytes, *, histogram: bool = False) -> IdfBinaryMetadata:
"""Pull serial, event time, sample rate, record time, pre-trigger,
calibration date and the four notes from a Thor binary (no .txt needed).
Field positions confirmed against UM11719_20231219162723.IDFW; stable
across the 151-file sig-A corpus.
Measured 2026-11-20 on 2,027 corpus files against Thor's own reports:
sample rate 2,027 / 2,027; record time and pre-trigger 291 / 291 waveforms
(the report rounds the pre-trigger to 0.01 s; the file holds this event's
exact value, e.g. 193 samples); the notes 2,027 / 2,027; the event time
equals the filename's on 2,384 / 2,384 files.
A histogram's settings record holds the sample rate but no record time or
pre-trigger (its [18:22] varies file to file), so `histogram=True` leaves
those None. Before 2026-11-20 the settings were found by the bytes
`be 80 00 00 00 00`, which are a -0.25 s pre-trigger and Fixed stop mode:
any other pre-trigger left them all None (#44, #45).
"""
md = IdfBinaryMetadata()
# Serial: null-terminated ASCII at 0x14E.
md.serial = _read_ascii_z(buf, 0x14E, maxlen=16)
# Sample rate + record time live in a BW-compatible compliance block.
# Locate the 6-byte anchor `be 80 00 00 00 00` and read offsets relative
# to it: anchor-6 = sample_rate uint16 BE; anchor+6 = record_time float32 BE.
anchor = buf.find(b"\xbe\x80\x00\x00\x00\x00", 0x800, 0xA00)
if anchor > 0:
sr_bytes = buf[anchor - 6 : anchor - 4]
if len(sr_bytes) == 2:
sr = int.from_bytes(sr_bytes, "big")
if sr in (256, 512, 1024, 2048, 4096):
md.sample_rate = sr
rt_bytes = buf[anchor + 6 : anchor + 10]
if len(rt_bytes) == 4:
try:
rt = struct.unpack(">f", rt_bytes)[0]
if 0.1 <= rt <= 600.0:
md.record_time_sec = float(rt)
except struct.error:
pass
rec = _settings_record(buf)
if rec is not None:
md.sample_rate = int.from_bytes(buf[rec + 6 : rec + 8], "big")
if not histogram:
md.pre_trigger_sec = -struct.unpack(">f", buf[rec + 12 : rec + 16])[0] + 0.0
md.record_time_sec = float(struct.unpack(">f", buf[rec + 18 : rec + 22])[0])
md.event_datetime = _decode_8byte_timestamp(buf, rec + _EVENT_TIME_AFTER_SETTINGS)
# Event timestamp: 8 bytes. Position differs between IDFW (0x97A) and
# IDFH (0x9F8); scan a small range and accept the first valid decode.
for off in (0x97A, 0x9F8):
ts = _decode_8byte_timestamp(buf, off)
if ts is not None:
md.event_datetime = ts
break
# Event timestamp fallback: the two positions seen before the record was
# known (record + 0x34 in its two commonest places).
if md.event_datetime is None:
for off in (0x97A, 0x9F8):
ts = _decode_8byte_timestamp(buf, off)
if ts is not None:
md.event_datetime = ts
break
for n, name in enumerate(_NOTE_FIELDS):
value_at = _NOTES_AT + n * _NOTE_STRIDE + _NOTE_LABEL_LEN
setattr(md, name, _read_ascii_z(buf, value_at, maxlen=_NOTE_VALUE_LEN))
# Calibration date: day, month, year_be at 0x194-0x197.
if len(buf) > 0x197:
@@ -251,6 +293,17 @@ def extract_binary_metadata(buf: bytes) -> IdfBinaryMetadata:
return md
def _notes_and_pretrigger(md: IdfBinaryMetadata) -> dict:
"""The file's own pre-trigger and notes, for an IdfReport built with no .txt."""
return {"pre_trigger_sec": md.pre_trigger_sec, "project": md.project,
"client": md.client, "operator": md.operator, "notes": md.notes}
def _project_info(md: IdfBinaryMetadata) -> IdfProjectInfo:
return IdfProjectInfo(project=md.project, client=md.client,
operator=md.operator, notes=md.notes)
# ─── Sample decoder + unit conversion ───────────────────────────────────────
@@ -615,7 +668,7 @@ def read_idf_file(
raise ValueError(f"{p.name}: unknown IDF signature {sig_prefix.hex()}")
is_histogram = p.suffix.upper() == ".IDFH"
md = extract_binary_metadata(buf)
md = extract_binary_metadata(buf, histogram=is_histogram)
if is_histogram:
intervals = decode_idfh_body(buf)
@@ -642,6 +695,7 @@ def read_idf_file(
filename=p.name,
sample_rate=md.sample_rate,
record_time_sec=md.record_time_sec,
**_notes_and_pretrigger(md),
)
peaks = IdfPeaks(
transverse_ips=peak_tran,
@@ -658,6 +712,8 @@ def read_idf_file(
filename=p.name,
sample_rate=md.sample_rate,
record_time_sec=md.record_time_sec,
pre_trigger_sec=md.pre_trigger_sec,
project_info=_project_info(md),
peaks=peaks,
report=rep,
)
@@ -681,6 +737,7 @@ def read_idf_file(
filename=p.name,
sample_rate=md.sample_rate,
record_time_sec=md.record_time_sec,
**_notes_and_pretrigger(md),
)
def _peak_ips(ch: str) -> float:
@@ -711,6 +768,8 @@ def read_idf_file(
filename=p.name,
sample_rate=md.sample_rate,
record_time_sec=md.record_time_sec,
pre_trigger_sec=md.pre_trigger_sec,
project_info=_project_info(md),
peaks=peaks,
report=rep,
)
+4
View File
@@ -402,6 +402,10 @@ class IdfEvent:
project_info=pi,
record_type=self.kind,
rectime_seconds=self.record_time_sec,
# The .h5 stores the pre-trigger in samples; it was 0 for every
# Micromate event, report or not (#45).
pretrig_samples=(round(self.pre_trigger_sec * self.sample_rate)
if self.pre_trigger_sec is not None and self.sample_rate else None),
)
ev._waveform_key = waveform_key
return ev
+6 -2
View File
@@ -84,8 +84,12 @@ READ_SUBS: Mapping[int, str] = MappingProxyType(_READ_SUBS)
# The write SUBs any code may transmit at all -- through MicromateProtocol.execute,
# one call at a time. Raising this is a spec change, reviewed like one: delete
# (0xA8/0xAA), raw file writes (0x8D/0x8E -- they could reach the modem
# settings) and 0xA2 never belong here without one.
ENABLEABLE_WRITES = frozenset({0x96, 0x97})
# settings) and 0xA2 never belong here without one. Phase 4 (2026-11-02) added
# the call-home write and its confirm (spec row 9: enable/disable only).
# Phase 5 (2026-11-03) added the setup push -- name, preferences, trigger and setup
# blocks with their confirms -- for changing a unit's settings by serial (spec row 10).
ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F,
0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72}) # + the setup push (phase 5)
class OpcodeRefused(RuntimeError):
+31
View File
@@ -93,6 +93,8 @@ SUB_STATE = 0x49
SUB_BULK_DOWNLOAD = 0x5A
SUB_POLL = 0x5B
SUB_ARM_EVENT = 0x93
SUB_FILE_READ_NEXT = 0x48 # file transfer: next page of the file opened by 0x94
SUB_FILE_OPEN_READ = 0x94 # file transfer: open a file by path, for reading
# ⚠ Reads are SINGLE-STEP. Series III probes at offset 0 to learn the length,
# then reads again at that length; a Micromate returns the whole block when
@@ -102,6 +104,10 @@ READ_ALL = 0xFFFF
# The two commands that do NOT use READ_ALL, and the data length each returned
# on UM12947 (firmware 11.0CB).
_FILE_OPEN_PARAMS = bytes([0, 0, 0, 1, 0, 0, 0, 0, 0, 0])
_FILE_FIRST_PAGE_PARAMS = bytes([0, 0, 0, 0, 0, 0, 0, 1, 0, 0])
_MAX_FILE_PAGES = 64
_OFFSETS = {
SUB_POLL: 0x0030, # 59 B — the one offset THOR treats as a constant
SUB_SERIAL: 0x000A, # 21 B
@@ -376,6 +382,31 @@ class MicromateProtocol:
"""
return self._read(SUB_SETUP_NEXT)
# ── Files, by path (read-only) ────────────────────────────────────────────
def read_file(self, path: str) -> bytes:
"""A file off the unit, by full path: `0x94` + the path opens it, then
`0x48` pages follow until an all-zero reply. The first `0x48` reply is a
descriptor, not file content. Frames are THOR's exactly (UM12947 reading
`schedule.dat`, 2026-09-24): `0x94` carries `params[3] = 1` and the path,
unpadded, as data with offset = its length; the first `0x48` carries
`params[7] = 1`, the rest none. Returns the content (each page's data
after its 11-byte prefix), joined.
"""
raw = path.encode("ascii")
self._request(build_request(SUB_FILE_OPEN_READ, len(raw), _FILE_OPEN_PARAMS, raw),
0xFF - SUB_FILE_OPEN_READ)
body = bytearray()
for page in range(_MAX_FILE_PAGES):
f = self._exchange(SUB_FILE_READ_NEXT,
params=_FILE_FIRST_PAGE_PARAMS if page == 0 else bytes(10))
if page == 0:
continue # the descriptor
if not any(f.data):
return bytes(body)
body += f.data[11:]
raise ProtocolError(f"{path}: no end of file after {_MAX_FILE_PAGES} pages")
# ── Event chain ───────────────────────────────────────────────────────────
def arm_event(self) -> MicromateFrame:
+75
View File
@@ -0,0 +1,75 @@
"""schedule.py -- a Micromate's schedule file, parsed. Pure; read-only by design.
THOR's scheduler lives in a file on the unit, `\\system\\schedule\\schedule.dat`,
read by path (`MicromateProtocol.read_file`). The format is decoded in
docs/micromate_protocol_reference.md, *The schedule record format* (measured on
UM12947, 2026-09-24/25): 260-byte records,
[0] record 0 only: 3 = repeat on, 2 = repeat off
[4] half-hour slot, 0-47
[5] day (3 in every record seen -- undetermined)
[6] action bitmask: 2 start monitoring with setup, 4 stop, 8 self-check,
16 auto call home
[7] setup-name length
[8:260] setup name (empty for actions that take none)
Why SFM reads it (phase 5): each scheduled start LOADS the setup it names. A
settings change to any other setup would be replaced at the next start, so SFM
refuses that change -- `schedule_conflicts`. SFM never writes the schedule.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Tuple
SCHEDULE_PATH = "\\system\\schedule\\schedule.dat"
_RECORD = 260
_NAME_MAX = _RECORD - 8
_ACTIONS = ((0x02, "start_with_setup"), (0x04, "stop"), (0x08, "self_check"), (0x10, "call_home"))
_KNOWN_BITS = sum(bit for bit, _ in _ACTIONS)
@dataclass(frozen=True)
class ScheduleEntry:
index: int
time: str # "HH:MM", from the half-hour slot
day: int # the raw byte; undetermined
action_bits: int
actions: Tuple[str, ...] # named bits; any other set bit as "unknown(0xNN)"
setup: str # "" when the action takes no setup
def _actions(bits: int) -> Tuple[str, ...]:
named = tuple(name for bit, name in _ACTIONS if bits & bit)
unknown = tuple(f"unknown(0x{1 << i:02x})" for i in range(8)
if bits & (1 << i) and not (1 << i) & _KNOWN_BITS)
return named + unknown
def parse_schedule(body: bytes) -> List[ScheduleEntry]:
"""The entries in a schedule file body. A record with nothing in [4:8] and
no name ends the list (the file is padded with zeros)."""
out: List[ScheduleEntry] = []
for i in range(len(body) // _RECORD):
r = body[i * _RECORD:(i + 1) * _RECORD]
n = min(r[7], _NAME_MAX)
name = r[8:8 + n].decode("ascii", "replace") if n else ""
if not any(r[4:8]) and not name:
break
slot = r[4]
out.append(ScheduleEntry(index=i, time=f"{slot // 2:02d}:{(slot % 2) * 30:02d}", day=r[5],
action_bits=r[6], actions=_actions(r[6]), setup=name))
return out
def _same_setup(a: str, b: str) -> bool:
return a.strip().casefold() == b.strip().casefold()
def schedule_conflicts(entries: List[ScheduleEntry], active_setup: str) -> List[ScheduleEntry]:
"""The scheduled starts that would load a setup other than `active_setup`
(compared ignoring case and surrounding spaces: THOR and the keypad disagree
on case, e.g. `factory.MMB` / `test2.mmb`)."""
return [e for e in entries
if "start_with_setup" in e.actions and e.setup and not _same_setup(e.setup, active_setup)]
+16 -10
View File
@@ -15,6 +15,8 @@ from __future__ import annotations
import struct
from minimateplus.crc import crc16_aug_ccitt as _crc16_aug_ccitt
from .models import MicromateSetup
from .protocol import ProtocolError
@@ -23,8 +25,6 @@ class SetupChecksumError(ProtocolError):
"""A config block's trailing CRC does not match its contents."""
_CRC_POLY = 0x1021
_CRC_INIT = 0x1D0F # CRC-16/AUG-CCITT
_CONTENT_SIZE = 2092 # = content[0:2] (2090) + the 2-byte CRC
# ── Head of the block ─────────────────────────────────────────────────────────
@@ -60,14 +60,6 @@ _ACTIVE_MIC = 3 # block index (0-based)
_MIC_TYPES = {2: "linear", 9: "sound_level"}
def _crc16_aug_ccitt(data: bytes) -> int:
c = _CRC_INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _CRC_POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def crc_ok(content: bytes) -> bool:
"""True if a config block's trailing checksum matches its contents.
@@ -88,6 +80,20 @@ def crc_ok(content: bytes) -> bool:
return _crc16_aug_ccitt(content[: n - 2]) == int.from_bytes(content[n : n + 2], "big")
def with_crc(content: bytes) -> bytes:
"""`content` with its trailing checksum recomputed: CRC-16/AUG-CCITT over
``[0:N-2]``, stored big-endian at ``[N:N+2]`` (the rule `crc_ok` checks).
THOR's write omits the checksum and the unit computes its own; this keeps a
patched block self-consistent so a plan's integrity check still means
something."""
n = int.from_bytes(content[0:2], "big")
if n < 2 or len(content) < n + 2:
raise ValueError(f"block header says {n} but the block is {len(content)} B")
out = bytearray(content)
out[n : n + 2] = _crc16_aug_ccitt(content[: n - 2]).to_bytes(2, "big")
return bytes(out)
def _f32(c: bytes, offset: int) -> float:
return struct.unpack_from(">f", c, offset)[0]
+439
View File
@@ -0,0 +1,439 @@
"""setup_fields.py -- the settings an operator can change, for both series (phase 5).
Pure byte interpretation: no I/O, no device, no `sfm` and no `minimateplus`
imports. Every offset is into the settings block's CONTENT:
* Series 4: the `0x1A` content, 2,092 bytes (N = 2090, then its CRC).
* Series 3: the 1A read assembled by `minimateplus.protocol.
assemble_compliance_content`, 2,090 bytes (N = 2090, no CRC in the read).
**One layout.** Measured 2026-11-03: Blastware's MiniMate compliance image IS
Series IV's `0x1A` content layout (`decode_setup` reads it), and each of
BE11529's nine 2026-04-20 Blastware writes moved exactly the bytes of the field
it changed. Series 4's offsets are from the 47-snapshot keypad pass on UM20147
(2026-10-17/19). Fields measured on one series only are offered on that series
only.
**Limits are the units' own, from Instantel's manuals** (Brian, 2026-11-03: "I
want to use the actual unit limits, not just what we have done in the past"):
* geophone trigger 0.005-10 in/s in steps of 0.001 -- MiniMate Plus manual
716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual
721U0201 Rev 06, *Geophone Trigger Level* -- and at most the range's full
scale;
* record time: Micromate 1-90 s (*Record Time*); MiniMate up to §4.4's
*Maximum Record Times* for a 1 MB unit, channels 1-4, at the sample rate,
and 13 s in Histogram Combo (§3.8.9);
* job number 1-9999 (both manuals).
What a unit does not take, the read-back shows (`settings_state`).
tests/test_setup_fields.py holds this to Blastware's writes and the keypad
fixtures byte for byte.
"""
from __future__ import annotations
import hashlib
import math
import struct
from typing import Any, Dict, List, Optional, Set
from .setup_block import crc_ok, with_crc
class SettingsValueError(ValueError):
"""A requested change SFM will not make, said plainly. Nothing is sent."""
# ── Layout ──────────────────────────────────────────────────────────────────
_MODE = 5
_SAMPLE_RATE = slice(6, 8) # u16 BE
_HIST_INTERVAL = slice(8, 10) # u16 BE seconds
_RECORD_TIME = 18 # f32 BE seconds
_REPORT_FLAGS = 39 # bit 0x02 = job number on the report (measured both series)
_JOB_SHOWN = 0x02
_JOB_NUMBER = slice(40, 42) # u16 BE
_NOTE_LABEL, _NOTE_VALUE, _NOTE_STRIDE, _NOTES = 122, 144, 64, 4
_NOTE_LABEL_WIDTH, _NOTE_WIDTH = 22, 42
NOTE_MAX = _NOTE_WIDTH - 1 # a NUL always ends the value
_CHANNELS, _CHANNEL_SIZE, _GEOPHONES = 1708, 48, (0, 1, 2)
_CH_RANGE = 29 # u8: 0 Normal (10 in/s), 1 Sensitive (1.25 in/s) -- Series 3, measured
_CH_TRIGGER = 30 # f32 BE, in/s for a geophone
_CH_UNIT = slice(34, 38) # "in." / "in" (the keypad re-renders it); NOT an identifier
_CH_ALARM = 38 # f32 BE -- Series 3; write measured at the bench 2026-11-04
_FULL_SCALE = {0: 10.0, 1: 1.25}
_RANGES = {"normal": 0, "sensitive": 1}
# Blastware writes these bytes as a fixed value on every write on record (11 of 11,
# both units); the unit reads `01 7f` there after a monitoring session. Meaning
# unknown -- SFM writes what Blastware writes. Series 3 only.
S3_BLASTWARE_FIXED = {26: b"\x00\x00"}
# Measured at the bench 2026-11-04 (BE9441, Brian's go): 1.0 -> 1.5 -> 1.0 in/s,
# each acknowledged, read back, and shown in the unit's own setup menu; the write
# moved exactly channel +39 of the three geophones (the f32 at +38).
S3_ALARM_WRITE_MEASURED = True
MODES = {
3: {"single_shot": 0x00, "continuous": 0x01, "histogram": 0x03, "histogram_continuous": 0x04},
4: {"waveform": 0x01, "manual": 0x02, "histogram": 0x03, "combo": 0x04},
}
_MODE_LABELS = {
"single_shot": "Single Shot", "continuous": "Continuous", "histogram": "Histogram",
"histogram_continuous": "Histogram + Continuous", "waveform": "Waveform", "manual": "Manual",
"combo": "Combo",
}
SAMPLE_RATES = (1024, 2048, 4096)
INTERVALS = (2, 5, 15, 60, 300, 900)
TRIGGER_MIN, TRIGGER_MAX, TRIGGER_STEP = 0.005, 10.0, 0.001
RECORD_MIN_S = 1.0
S4_MAX_RECORD_S = 90.0
S3_MAX_RECORD_S = {1024: 104.0, 2048: 52.0, 4096: 26.0}
S3_COMBO_MAX_RECORD_S = 13.0
JOB_MIN, JOB_MAX = 1, 9999
_SERIES_FIELDS = {
3: ("record_mode", "sample_rate", "histogram_interval_s", "record_time_s", "geo_trigger_ips",
"geo_range", "geo_alarm_ips", "job_number", "job_number_shown",
"note_1", "note_2", "note_3", "note_4"),
4: ("record_mode", "sample_rate", "histogram_interval_s", "record_time_s", "geo_trigger_ips",
"job_number", "job_number_shown", "note_1", "note_2", "note_3", "note_4"),
}
_LEVELS = ("geo_trigger_ips", "geo_alarm_ips")
def _ch(k: int) -> int:
return _CHANNELS + _CHANNEL_SIZE * k
def _f32(c: bytes, offset: int) -> float:
return struct.unpack_from(">f", c, offset)[0]
def _shown(v: float) -> float:
"""An f32 as an operator typed it: 0.30000001192 is 0.3."""
return round(v, 6)
def _note_offsets(n: int) -> tuple:
label = _NOTE_LABEL + n * _NOTE_STRIDE
value = _NOTE_VALUE + n * _NOTE_STRIDE
return label, value
def _note_label(c: bytes, n: int) -> str:
start, _ = _note_offsets(n)
raw = c[start:start + _NOTE_LABEL_WIDTH].split(b"\x00")[0]
text = raw.decode("ascii", "replace").strip().rstrip(":").strip()
return text or f"Note {n + 1}"
def _note_value(c: bytes, n: int) -> str:
_, start = _note_offsets(n)
return c[start:start + _NOTE_WIDTH].split(b"\x00")[0].decode("ascii", "replace")
def field_bytes(series: int) -> Dict[str, Set[int]]:
"""Every byte each field may move, by content offset."""
def chans(rel: int, width: int) -> Set[int]:
return {_ch(k) + rel + i for k in _GEOPHONES for i in range(width)}
out = {
"record_mode": {_MODE},
"sample_rate": set(range(6, 8)),
"histogram_interval_s": set(range(8, 10)),
"record_time_s": set(range(_RECORD_TIME, _RECORD_TIME + 4)),
"geo_trigger_ips": chans(_CH_TRIGGER, 4),
"geo_range": chans(_CH_RANGE, 1),
"geo_alarm_ips": chans(_CH_ALARM, 4),
"job_number": set(range(40, 42)),
"job_number_shown": {_REPORT_FLAGS},
}
for n in range(_NOTES):
_, v = _note_offsets(n)
out[f"note_{n + 1}"] = set(range(v, v + _NOTE_WIDTH))
return {f: out[f] for f in _SERIES_FIELDS[series]}
# ── Reading ─────────────────────────────────────────────────────────────────
def _mode_name(c: bytes, series: int) -> str:
code = c[_MODE]
for name, value in MODES[series].items():
if value == code:
return name
return f"unknown(0x{code:02x})"
def _range_code(c: bytes) -> int:
return c[_ch(0) + _CH_RANGE]
def _full_scale(c: bytes, series: int, range_name: Optional[str] = None) -> Optional[float]:
if series == 4:
return _FULL_SCALE[0] # Series 4's range byte is not mapped; 10 in/s is the hardware's
code = _RANGES[range_name] if range_name is not None else _range_code(c)
return _FULL_SCALE.get(code)
def _s3_max_record(rate: int, mode: str) -> Optional[float]:
top = S3_MAX_RECORD_S.get(rate)
if top is None:
return None
return min(top, S3_COMBO_MAX_RECORD_S) if mode == "histogram_continuous" else top
def _unit_string(c: bytes) -> List[str]:
return [c[_ch(k) + _CH_UNIT.start:_ch(k) + _CH_UNIT.stop].replace(b"\x00", b"")
.replace(b".", b"").decode("ascii", "replace") for k in _GEOPHONES]
def editable_fields(content: bytes, series: int) -> List[Dict[str, Any]]:
"""The fields an operator can change, described for a form: field, label,
kind ("number" / "choice" / "text" / "bool"), value, and as relevant unit,
min, max, step, choices [{value, label}], maxlength, readonly."""
c = content
rate = int.from_bytes(c[_SAMPLE_RATE], "big")
mode = _mode_name(c, series)
out: List[Dict[str, Any]] = [
{"field": "record_mode", "label": "Record mode", "kind": "choice", "value": mode,
"choices": [{"value": n, "label": _MODE_LABELS[n]} for n in MODES[series]]},
{"field": "sample_rate", "label": "Sample rate", "kind": "choice", "value": rate, "unit": "sps",
"choices": [{"value": r, "label": f"{r} sps"} for r in SAMPLE_RATES]},
{"field": "histogram_interval_s", "label": "Histogram interval", "kind": "choice",
"value": int.from_bytes(c[_HIST_INTERVAL], "big"),
"choices": [{"value": s, "label": f"{s} s" if s < 60 else f"{s // 60} min"} for s in INTERVALS]},
{"field": "record_time_s", "label": "Record time", "kind": "number", "unit": "s",
"value": _shown(_f32(c, _RECORD_TIME)), "min": RECORD_MIN_S,
"max": S4_MAX_RECORD_S if series == 4 else _s3_max_record(rate, mode)},
{"field": "geo_trigger_ips", "label": "Geophone trigger", "kind": "number", "unit": "in/s",
"value": _shown(_f32(c, _ch(0) + _CH_TRIGGER)), "min": TRIGGER_MIN,
"max": min(TRIGGER_MAX, _full_scale(c, series) or TRIGGER_MAX), "step": TRIGGER_STEP},
]
if series == 3:
code = _range_code(c)
name = next((n for n, v in _RANGES.items() if v == code), f"unknown(0x{code:02x})")
out.append({"field": "geo_range", "label": "Geophone range", "kind": "choice", "value": name,
"choices": [{"value": "normal", "label": "Normal (10 in/s)"},
{"value": "sensitive", "label": "Sensitive (1.25 in/s)"}]})
out.append({"field": "geo_alarm_ips", "label": "Geophone alarm", "kind": "number",
"unit": "in/s", "value": _shown(_f32(c, _ch(0) + _CH_ALARM)),
"min": TRIGGER_MIN, "max": _full_scale(c, 3) or TRIGGER_MAX,
"step": TRIGGER_STEP, "readonly": not S3_ALARM_WRITE_MEASURED})
out.append({"field": "job_number", "label": "Job number", "kind": "number",
"value": int.from_bytes(c[_JOB_NUMBER], "big"), "min": JOB_MIN, "max": JOB_MAX, "step": 1})
out.append({"field": "job_number_shown", "label": "Job number on report", "kind": "bool",
"value": bool(c[_REPORT_FLAGS] & _JOB_SHOWN)})
for n in range(_NOTES):
out.append({"field": f"note_{n + 1}", "label": _note_label(c, n), "kind": "text",
"value": _note_value(c, n), "maxlength": NOTE_MAX})
return out
def field_values(content: bytes, series: int) -> Dict[str, Any]:
return {d["field"]: d["value"] for d in editable_fields(content, series)}
def field_rows(before: bytes, written: bytes, series: int, fields, now: Optional[bytes] = None) -> Dict[str, Dict[str, Any]]:
"""For each changed field: its label, the value the unit had (old), the value
sent (new) and, given a read-back, what the unit now holds (now)."""
a, w = field_values(before, series), field_values(written, series)
n = field_values(now, series) if now is not None else None
labels = {d["field"]: d["label"] for d in editable_fields(written, series)}
out: Dict[str, Dict[str, Any]] = {}
for f in fields:
row: Dict[str, Any] = {"label": labels[f], "old": a[f], "new": w[f]}
if n is not None:
row["now"] = n[f]
out[f] = row
return out
# ── Checking ────────────────────────────────────────────────────────────────
def _number(field: str, v: Any) -> float:
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
raise SettingsValueError(f"{field} must be a number, not {v!r}")
return float(v)
def _integer(field: str, v: Any) -> int:
if isinstance(v, bool) or not isinstance(v, int):
raise SettingsValueError(f"{field} must be a whole number, not {v!r}")
return v
def check_changes(content: bytes, series: int, changes: Dict[str, Any]) -> Dict[str, Any]:
"""The changes, normalised -- or SettingsValueError naming the first one SFM
will not make, and why. Checks names, types and the units' own limits, then
what depends on this unit's block: its unit strings and its range."""
if series not in _SERIES_FIELDS:
raise SettingsValueError(f"Series {series} has no settings SFM can change")
if not isinstance(changes, dict) or not changes:
raise SettingsValueError("no settings to change")
allowed = _SERIES_FIELDS[series]
out: Dict[str, Any] = {}
for field, v in changes.items():
if field not in allowed:
raise SettingsValueError(f"{field} is not a setting SFM can change on a Series {series} unit")
if field == "record_mode":
if v not in MODES[series]:
raise SettingsValueError(f"record_mode must be one of {', '.join(MODES[series])}, not {v!r}")
out[field] = v
elif field == "sample_rate":
if _integer(field, v) not in SAMPLE_RATES:
raise SettingsValueError(f"sample_rate must be one of {SAMPLE_RATES}, not {v}")
out[field] = v
elif field == "histogram_interval_s":
if _integer(field, v) not in INTERVALS:
raise SettingsValueError(f"histogram_interval_s must be one of {INTERVALS} s, not {v}")
out[field] = v
elif field == "geo_range":
if v not in _RANGES:
raise SettingsValueError(f"geo_range must be normal or sensitive, not {v!r}")
out[field] = v
elif field in ("geo_trigger_ips", "geo_alarm_ips"):
if field == "geo_alarm_ips" and not S3_ALARM_WRITE_MEASURED:
raise SettingsValueError("the alarm level is shown but not changed yet: a MiniMate "
"alarm write has never been measured (the bench measures it)")
x = _number(field, v)
if not TRIGGER_MIN <= x <= TRIGGER_MAX:
raise SettingsValueError(f"{field} must be {TRIGGER_MIN}-{TRIGGER_MAX} in/s, not {x}")
if abs(x - round(x, 3)) > 1e-9:
raise SettingsValueError(f"{field} must be in steps of {TRIGGER_STEP} in/s, not {x}")
out[field] = round(x, 3)
elif field == "record_time_s":
out[field] = _number(field, v)
elif field == "job_number":
if not JOB_MIN <= _integer(field, v) <= JOB_MAX:
raise SettingsValueError(f"job_number must be {JOB_MIN}-{JOB_MAX}, not {v}")
out[field] = v
elif field == "job_number_shown":
if not isinstance(v, bool):
raise SettingsValueError(f"job_number_shown must be true or false, not {v!r}")
out[field] = v
else: # note_1 .. note_4
if not isinstance(v, str):
raise SettingsValueError(f"{field} must be text, not {v!r}")
if any(not 0x20 <= ord(ch) <= 0x7E for ch in v):
raise SettingsValueError(f"{field} must be plain printable ASCII (no accents, tabs or "
"line breaks)")
if len(v) > NOTE_MAX:
raise SettingsValueError(f"{field} is {len(v)} characters; the unit holds {NOTE_MAX}")
out[field] = v
# What depends on this unit's block, with the NEW mode / rate / range if they change
# too -- checked on the block that would RESULT, so a one-field change (the range,
# the rate, the mode) cannot leave a value the unit already holds over its limit
# (final review, 2026-11-03).
c = content
if any(f in out for f in ("record_time_s", "sample_rate", "record_mode")):
t = out.get("record_time_s", _shown(_f32(c, _RECORD_TIME)))
held = "" if "record_time_s" in out else f" (the unit holds {t:g} s; change the record time too)"
if series == 4:
top: Optional[float] = S4_MAX_RECORD_S
else:
rate = out.get("sample_rate", int.from_bytes(c[_SAMPLE_RATE], "big"))
top = _s3_max_record(rate, out.get("record_mode", _mode_name(c, series)))
if top is None:
raise SettingsValueError(f"this unit's sample rate ({rate}) has no record-time limit "
"in the manual -- set the sample rate too")
if not RECORD_MIN_S <= t <= top:
raise SettingsValueError(f"record_time_s must be {RECORD_MIN_S}-{top:g} s here, not {t}{held}")
if any(f in out for f in (*_LEVELS, "geo_range")):
units = _unit_string(c)
if any(u != "in" for u in units):
raise SettingsValueError(f"this unit's geophone channels read {units}, not in/s -- only "
"in/s is measured, so SFM will not change a level or the range")
full = _full_scale(c, series, out.get("geo_range"))
if full is None:
raise SettingsValueError("this unit's geophone range byte is not a value ever measured")
held_levels = {"geo_trigger_ips": _CH_TRIGGER, "geo_alarm_ips": _CH_ALARM}
for f in _LEVELS:
if f not in _SERIES_FIELDS[series]:
continue
v = out.get(f, _shown(_f32(c, _ch(0) + held_levels[f])))
if v > full:
held = "" if f in out else " (the unit holds it)"
raise SettingsValueError(f"{f} {v} in/s is above the range's full scale ({full} in/s){held}")
return out
# ── Writing ─────────────────────────────────────────────────────────────────
def encode_setup(content: bytes, series: int, changes: Dict[str, Any]) -> bytes:
"""`content` with only the changed fields' bytes moved. `changes` should
come from check_changes; this patches, it does not judge. Bit fields are
patched bit by bit. Series 3 also writes Blastware's fixed bytes; Series 4
gets its checksum recomputed."""
out = bytearray(content)
for field, v in changes.items():
if field == "record_mode":
out[_MODE] = MODES[series][v]
elif field == "sample_rate":
out[_SAMPLE_RATE] = int(v).to_bytes(2, "big")
elif field == "histogram_interval_s":
out[_HIST_INTERVAL] = int(v).to_bytes(2, "big")
elif field == "record_time_s":
struct.pack_into(">f", out, _RECORD_TIME, float(v))
elif field == "geo_trigger_ips":
for k in _GEOPHONES:
struct.pack_into(">f", out, _ch(k) + _CH_TRIGGER, float(v))
elif field == "geo_alarm_ips":
for k in _GEOPHONES:
struct.pack_into(">f", out, _ch(k) + _CH_ALARM, float(v))
elif field == "geo_range":
for k in _GEOPHONES:
out[_ch(k) + _CH_RANGE] = _RANGES[v]
elif field == "job_number":
out[_JOB_NUMBER] = int(v).to_bytes(2, "big")
elif field == "job_number_shown":
out[_REPORT_FLAGS] = (out[_REPORT_FLAGS] | _JOB_SHOWN) if v else (out[_REPORT_FLAGS] & ~_JOB_SHOWN)
elif field.startswith("note_") and field[5:].isdigit() and 1 <= int(field[5:]) <= _NOTES:
_, start = _note_offsets(int(field[5:]) - 1)
out[start:start + _NOTE_WIDTH] = v.encode("ascii").ljust(_NOTE_WIDTH, b"\x00")
else:
raise SettingsValueError(f"{field} is not a setting SFM can change")
if series == 3:
for offset, value in S3_BLASTWARE_FIXED.items():
out[offset:offset + len(value)] = value
return bytes(out)
return with_crc(bytes(out))
# ── Reading back ────────────────────────────────────────────────────────────
_COMPARED = 2090
def settings_state(before: bytes, written: bytes, now: bytes, *, series: int) -> str:
"""What a read of the unit says about a change, from the bytes alone:
"as asked" (it holds what was written), "unchanged" (it holds what it had),
or "differs". Floats are never compared -- 0.3 is the same f32 both ways.
Series 4 also needs the unit's own checksum to hold. Series 3 bytes that
differ only in Blastware's fixed bytes count as as asked: nothing the operator
asked for is different."""
a, w, n = before[:_COMPARED], written[:_COMPARED], now[:_COMPARED]
if series == 4 and not crc_ok(now):
return "differs"
if n == w:
return "as asked"
if series == 3:
fixed = {o + i for o, v in S3_BLASTWARE_FIXED.items() for i in range(len(v))}
if len(n) == len(w) and all(n[i] == w[i] for i in range(len(n)) if i not in fixed):
return "as asked"
if n == a:
return "unchanged"
return "differs"
def revision(blocks: List[bytes]) -> str:
"""A short fingerprint of the blocks a preview read; a live change must match it."""
return hashlib.sha256(b"".join(bytes(b) for b in blocks)).hexdigest()[:16]
def changes_bytes(changes: Dict[str, Any]) -> bytes:
"""The normalised changes, canonically: part of a preview's revision, so a live
change must ask for exactly what was previewed (final review, 2026-11-03)."""
import json
return json.dumps(changes, sort_keys=True, separators=(",", ":")).encode("ascii")
+19 -6
View File
@@ -22,6 +22,7 @@ from .opcodes import CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused
from .setup_block import crc_ok
_CONFIRM = 0xFFFF
_CALL_HOME_OBSERVED = (0x00, 0x01, 0x04, 0x05) # content[5] values units have held
# block content sizes THOR's offsets were observed at (all on UM12947 / 11.0CB)
_PREFS_LEN, _TRIGGER_LEN, _SETUP_LEN, _CALL_HOME_LEN = 90, 28, 2092, 126
@@ -101,26 +102,38 @@ def plan_stop_monitoring() -> WritePlan:
return WritePlan("stop monitoring", (WriteStep(0x97, _CONFIRM, what="stop monitoring"),))
def is_call_home_content(block: bytes) -> bool:
"""Whether 126 bytes are the 0x2C call-home content: its header is its own
length (00 7C, N = 124 -- 00 7C DC on every read on record, UM12947 and
UM20147). A bit is flipped only in a block that carries it."""
return len(block) == _CALL_HOME_LEN and int.from_bytes(block[0:2], "big") == _CALL_HOME_LEN - 2
def plan_call_home_enabled(call_home: bytes, enabled: bool) -> WritePlan:
"""Read `0x2C`, flip bit 0 of content[5], send the rest back byte for byte.
Bit 0 of `[5]` is the enable. 🔶 UM12947 (THOR's unit) read 0x05 enabled /
0x04 disabled, bit 2 set in both; UM20147 reads 0x01 (measured, phase-2 dry
run). So on UM20147 "off" writes 0x00, a value no capture shows being
written: the target value there is unobserved, and the plan's `warnings`
say so. `[118:120]` is unit-maintained and THOR echoes it.
run). So on UM20147 "off" writes 0x00 -- measured at the bench 2026-11-03
(and again 11-04): 0x01 <-> 0x00 acknowledged, read back, and matched in the
unit's own menu. A value outside those four still carries a warning.
`[118:120]` is unit-maintained and THOR echoes it.
"""
if len(call_home) != _CALL_HOME_LEN:
raise ValueError(f"call-home content must be {_CALL_HOME_LEN} B "
f"(the size THOR's offset was seen at), got {len(call_home)}")
if not is_call_home_content(call_home):
raise ValueError(f"call-home content's header is {call_home[0:2].hex()}, not its own length "
f"(00 {_CALL_HOME_LEN - 2:02x}) -- not the call-home block; nothing built")
b5 = (call_home[5] | 0x01) if enabled else (call_home[5] & 0xFE)
data = call_home[:5] + bytes([b5]) + call_home[6:]
what = "call-home " + ("enable" if enabled else "disable")
start = call_home[5]
warnings = []
if start not in (0x04, 0x05) or b5 not in (0x04, 0x05):
warnings.append(f"content[5] 0x{start:02X} -> 0x{b5:02X}: THOR was only ever "
"seen writing 0x04/0x05 (UM12947); this value is unobserved")
if start not in _CALL_HOME_OBSERVED or b5 not in _CALL_HOME_OBSERVED:
warnings.append(f"content[5] 0x{start:02X} -> 0x{b5:02X}: no unit has been seen "
"holding this value (0x04/0x05 UM12947 by THOR, 0x00/0x01 UM20147 "
"by SFM); it is unobserved")
if b5 == start:
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
" -- this write changes nothing")
+84 -283
View File
@@ -3,7 +3,8 @@ blastware_file.py — Blastware binary file codec for bidirectional interoperabi
Reads and writes the proprietary Instantel/Blastware file formats:
Waveform events (.CE0W, .VM0H, .440, .7M0, etc.) (extension encoding UNKNOWN — see below)
.MLG — Monitor log (monitoring session history)
Monitor logs (.MLG) live in minimateplus/mlg_file.py (reader and writer, 2026-11-13).
All waveform formats share a common 22-byte file header prefix and identical
internal binary structure (same type tag 00 12 03 00, same STRT record layout).
@@ -61,27 +62,6 @@ Waveform file structure (confirmed from example-events/4-3-26-multi/M529LIY6 (ex
Timestamp format (big-endian, 8 bytes):
[day] [month] [year_HI] [year_LO] [0x00] [hour] [min] [sec]
MLG (monitor log, confirmed from example-events/4-3-26-multi/BE11529.MLG):
[308B header] [N × 292B records]
Header (308 bytes):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 — fixed (16B)
Offset 0x10: ... (unknown structure, written as zeros + serial)
Offset 0x2A: serial number (8 bytes, null-padded ASCII, e.g. "BE11529")
... zero-padded to 308 bytes total
Record (292 bytes each):
[2B CRC] — unknown algorithm; written as 0x00 0x00
22 01 0e 80 — record marker
[ts1: 8B big-endian timestamp] — start time
[ts2: 8B big-endian timestamp] — stop time (zeros if no stop)
[4B flags] — see MLG_FLAGS_* constants below
[10B serial] — null-padded serial number ASCII
[text] — for trigger records: [0x08][8B ts1_copy] then ASCII "Geo: X.XXX in/s"
for monitoring records: b'' (or minimal separator)
[zero-padded to 292 bytes]
─── Critical implementation notes ──────────────────────────────────────────────
Waveform body reconstruction algorithm (confirmed 2026-04-21 from verification against
@@ -104,25 +84,11 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture):
DLE strip rule (applied AFTER slicing):
Strip any 0x10 byte that is immediately followed by 0x02, 0x03, or 0x04.
This undoes the DLE-escape that S3FrameParser preserves as literal pairs.
Applied to frame.data[skip:] + bytes([frame.chk_byte]) together, then
conditionally exclude the trailing chk_byte from the output.
chk_byte absorption:
When frame.data[-1] == 0x10 AND frame.chk_byte ∈ {0x02, 0x03, 0x04},
the last byte of frame.data is the DLE prefix of a split DLE+chk pair.
Including chk_byte in the strip buffer allows the pair to be stripped as
a unit. After stripping, the trailing chk_byte is ALWAYS removed — because
_strip_inner_frame_dles keeps the byte after the DLE (the chk_byte value),
and that value is the checksum, never payload. This applies to all three
cases (chk ∈ {0x02, 0x03, 0x04}) identically.
MLG CRC:
The algorithm that produces the 2-byte CRC at the start of each MLG record
is unknown. All examined records use non-zero values that do not match
CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), word sums, XOR variants, or
any of the 40+ polynomial/init combinations tested. The writer emits 0x0000.
This produces files that Blastware may reject or display without the CRC check —
the exact impact on BW import is unknown (TODO: test).
chk_byte absorption (retired 2026-11-06, #58):
The escape 0x10 of a checksum sent as `10 02/03/04` used to stay at the end
of frame.data, and this builder dropped it here. The parser now drops it,
so a 0x10 ending frame.data is real data (one A5 chunk in ten ends in one).
─── Public API ──────────────────────────────────────────────────────────────────
@@ -139,25 +105,19 @@ MLG CRC:
read_blastware_file(path) → Event
Parse a Blastware waveform file into an Event object with waveform data populated.
(Not yet implemented — placeholder raises NotImplementedError.)
write_mlg(entries, serial, path)
Create a .MLG file from a list of MonitorLogEntry objects.
read_mlg(path) → list[MonitorLogEntry]
Parse a .MLG file into MonitorLogEntry objects.
(Not yet implemented — placeholder raises NotImplementedError.)
"""
from __future__ import annotations
import datetime
import logging
import re
import struct
from pathlib import Path
from typing import Optional, Union
from .framing import S3Frame
from .models import Event, MonitorLogEntry, Timestamp
from .models import Event, Timestamp
log = logging.getLogger(__name__)
@@ -174,9 +134,6 @@ _FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 17 byt
# Waveform file type tag (4 bytes after common prefix) — shared by ALL waveform extensions
_WAVEFORM_TYPE_TAG = b"\x00\x12\x03\x00" # confirmed from M529LIY6 (example event) — same tag for .CE0W, .VM0H, etc.
# MLG type tag (4 bytes after common prefix)
_MLG_TYPE_TAG = b"\x22\x01\x0e\xa0" # confirmed from BE11529.MLG offset 0x11..0x14
# Total header sizes
_WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# From binary: first 22 bytes = header, then STRT at byte 22.
@@ -185,17 +142,6 @@ _WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# Re-count: b"\x10\x00\x01\x80\x00\x00" = 6B + b"Instantel\x00" = 10B + b"\x07\x2c" = 2B = 18B prefix.
_FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 18 bytes
_WAVEFORM_HEADER_SIZE = 22 # 18 + 4 = 22 bytes ✅
_MLG_HEADER_SIZE = 308 # confirmed from BE11529.MLG
# MLG record marker (4 bytes after 2-byte CRC at start of each record)
_MLG_RECORD_MARKER = b"\x22\x01\x0e\x80"
_MLG_RECORD_SIZE = 292 # bytes per record (confirmed from BE11529.MLG)
# MLG record flags (4 bytes at record[22:26])
# Confirmed from BE11529.MLG binary inspection:
MLG_FLAGS_START_ONLY = b"\xff\xff\x00\x00" # monitoring start with no stop
MLG_FLAGS_TRIGGER = b"\x01\x00\x02\x00" # triggered event (has ts1 + ts2)
MLG_FLAGS_INTERVAL = b"\x02\x00\x00\x00" # monitoring interval (has ts1 + ts2)
# ── Timestamp helpers ─────────────────────────────────────────────────────────
@@ -204,7 +150,8 @@ def _encode_ts_be(ts: Optional[datetime.datetime]) -> bytes:
"""
Encode a datetime as an 8-byte big-endian Blastware timestamp.
Format (waveform file and MLG record timestamps):
Format (event file timestamps; an .MLG stores the year little-endian,
see minimateplus/mlg_file.py):
[day][month][year_HI][year_LO][0x00][hour][min][sec]
Big-endian year confirmed from M529LIY6 (example event) footer:
@@ -296,29 +243,16 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes:
Extract the waveform body contribution from one A5 S3Frame.
The contribution is frame.data[skip:] with inner-frame DLE pairs stripped
per _strip_inner_frame_dles(). The chk_byte is temporarily appended before
stripping to handle the split-pair edge case where a DLE at the end of
frame.data is paired with chk_byte.
per _strip_inner_frame_dles().
Split-pair edge case (confirmed for A5[8] of M529LIY6 (example event), 2026-04-21):
S3FrameParser appends DLE+XX pairs as two literal bytes when XX ∉ {DLE, ETX}.
When the LAST occurrence of such a pair straddles the payload/checksum boundary
(i.e., DLE is the last byte of raw_payload and XX is the checksum), the parser
splits them:
- DLE ends up as the last byte of frame.data (frame.data[-1] == 0x10)
- XX is stored as frame.chk_byte
To strip the pair correctly, we reunite the bytes before calling the strip
function. Since chk_byte is the checksum (not payload data), it is excluded
from the final output regardless of whether it was part of a pair.
Post-strip chk_byte removal (ALL cases):
_strip_inner_frame_dles strips the 0x10 and KEEPS chk_byte in all cases.
Chk_byte is always the checksum (not payload), so always strip it off.
Until #58 (2026-11-06) an escaped checksum (`10 02/03/04`) left its 0x10 as
the last byte of frame.data, and this function dropped it by pairing it with
chk_byte (first seen on A5[8] of M529LIY6, 2026-04-21). The parser drops it
now, so a 0x10 here is data and is kept.
Args:
frame: S3Frame with frame.data and frame.chk_byte populated.
frame: S3Frame from S3FrameParser (or a store pickle loaded by
WaveformStore.load_a5, which converts pre-#58 frames).
skip: Number of leading bytes in frame.data to exclude (frame header).
Returns:
@@ -326,28 +260,7 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes:
"""
if skip >= len(frame.data):
return b""
relevant = frame.data[skip:]
# Detect split DLE+chk pair at the frame boundary.
has_split_pair = (
len(relevant) > 0
and relevant[-1] == 0x10
and frame.chk_byte in {0x02, 0x03, 0x04}
)
if has_split_pair:
# Reunite the split pair so the strip function sees both bytes together.
buf = relevant + bytes([frame.chk_byte])
stripped = _strip_inner_frame_dles(buf)
# _strip_inner_frame_dles strips the DLE (0x10) and KEEPS chk_byte.
# chk_byte is the received checksum — never payload — so remove it.
# This is correct for all values in {0x02, 0x03, 0x04}.
if stripped:
stripped = stripped[:-1]
return stripped
else:
return _strip_inner_frame_dles(relevant)
return _strip_inner_frame_dles(frame.data[skip:])
# ── Filename helper ───────────────────────────────────────────────────────────
@@ -416,6 +329,31 @@ def _make_stem(ts_local: datetime.datetime) -> str:
return s
_BW_NAME = re.compile(r"^[B-Z]\d{3}([0-9A-Z]{4})\.([0-9A-Z]{2})0[WH]?$")
def blastware_filename_time(name: str) -> Optional[datetime.datetime]:
"""The event time a Blastware filename encodes, or None for any other name.
The inverse of `blastware_filename`: `<prefix><serial3><stem 4>.<AB>0[W|H]`,
time = 1985-01-01 + stem*1296 + AB seconds. This is Blastware's own time
to the second -- it equals the report's Event Time on 1,330/1,330
report-paired waveforms (81 prod-store, 1,249 DL2) and the report's
Histogram Start Time on 13,089/13,089 histograms (measured 2026-10-26).
Only the V10.72 `AB0` form is decoded; anything else gives None.
"""
m = _BW_NAME.match((name or "").upper())
if not m:
return None
stem = 0
for c in m.group(1):
stem = stem * 36 + _STEM_CHARS.index(c)
ab = _STEM_CHARS.index(m.group(2)[0]) * 36 + _STEM_CHARS.index(m.group(2)[1])
if ab >= _STEM_UNIT_SEC:
return None
return _INSTANTEL_EPOCH + datetime.timedelta(seconds=stem * _STEM_UNIT_SEC + ab)
def blastware_filename(event: Event, serial: str, ach: bool = False) -> str:
"""
Return the correct Blastware filename for an event.
@@ -441,6 +379,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).
@@ -505,6 +446,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 `<stem>.<AB>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.
@@ -676,8 +643,18 @@ def write_blastware_file(
a5_frames: list[S3Frame],
path: Union[str, Path],
) -> None:
"""Write `blastware_file_bytes(event, a5_frames)` to `path`."""
Path(path).write_bytes(blastware_file_bytes(event, a5_frames))
def blastware_file_bytes(
event: Event,
a5_frames: list[S3Frame],
) -> bytes:
"""
Write a Blastware waveform file from a downloaded event.
The Blastware waveform file for a downloaded event, as bytes -- what
write_blastware_file writes, and what a live SFM download stores through the
file-import path (sfm.event_ingest).
Args:
event: Event object (populated by get_events() or download_waveform()).
@@ -686,23 +663,18 @@ def write_blastware_file(
(page_key=0x0000). Pass include_terminator=True to
read_bulk_waveform_stream() when collecting frames.
Must have at least 2 frames (probe + terminator).
path: Destination file path. Parent directory must exist.
Extension should be set via blastware_filename().
File layout:
[22B header] [21B STRT] [body bytes] [26B footer]
Raises:
ValueError: if a5_frames is empty or has no terminator (page_key=0).
OSError: if the file cannot be written.
Confirmed correct waveform body reconstruction against M529LIY6 (example event) (2026-04-21).
"""
if not a5_frames:
raise ValueError("a5_frames must not be empty")
path = Path(path)
# ── Extract STRT record from probe frame ────────────────────────────────
# The STRT record (21 bytes) lives verbatim inside A5[0].data[7:].
# It is stored as-is in the waveform file — do NOT reconstruct it from Event
@@ -897,12 +869,7 @@ def write_blastware_file(
+ b"\x00\x00"
)
# ── Write file ───────────────────────────────────────────────────────────
with open(path, "wb") as f:
f.write(header)
f.write(strt)
f.write(body)
f.write(footer)
return header + strt + body + footer
def read_blastware_file(path: Union[str, Path]) -> Event:
@@ -921,169 +888,3 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_blastware_file() is not yet implemented")
# ── MLG file writer ───────────────────────────────────────────────────────────
def _build_mlg_header(serial: str) -> bytes:
"""
Build the 308-byte MLG file header.
Header structure (confirmed from BE11529.MLG binary inspection):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 (22B)
Offset 0x16: ... (16B unknown — observed as zeros in BE11529.MLG)
Offset 0x2A: serial number (8 bytes, null-padded ASCII)
... rest zero-padded to 308 bytes
The serial string "BE11529" appears at offset 0x2A (42 decimal).
"""
buf = bytearray(_MLG_HEADER_SIZE)
# Common prefix + MLG type tag
prefix = _FILE_HEADER_PREFIX + _MLG_TYPE_TAG # 22 bytes
buf[0:len(prefix)] = prefix
# Serial number at offset 0x2A
serial_bytes = serial.encode("ascii", errors="replace")[:8]
serial_padded = serial_bytes.ljust(8, b"\x00")
buf[0x2A : 0x2A + 8] = serial_padded
return bytes(buf)
def _build_mlg_record(
entry: MonitorLogEntry,
serial: str,
) -> bytes:
"""
Build one 292-byte MLG record from a MonitorLogEntry.
Record layout (confirmed from BE11529.MLG binary inspection):
[0:2] CRC — 2-byte CRC (algorithm unknown; written as 0x0000)
[2:6] marker — 22 01 0e 80
[6:14] ts1 — 8B big-endian start timestamp
[14:22] ts2 — 8B big-endian stop timestamp
[22:26] flags — 4B record flags (see MLG_FLAGS_* constants)
[26:36] serial — 10B null-padded serial number
[36:] text — for triggered events: [0x08][8B ts1_copy]["Geo: X.XXX in/s"]
for monitoring intervals: b"" or minimal separator
[... zero-padded to 292 bytes]
Flags based on entry type:
- MonitorLogEntry with start_time only (no stop_time): MLG_FLAGS_START_ONLY
- MonitorLogEntry with both times and geo_threshold_ips set: MLG_FLAGS_TRIGGER
- MonitorLogEntry with both times (monitoring interval): MLG_FLAGS_INTERVAL
The triggered-event text block (flags = MLG_FLAGS_TRIGGER):
[0x08] [ts1: 8B] [ASCII "Geo: X.XXX in/s\x00"]
Confirmed from BE11529.MLG records at offset 0x0134 and 0x0258.
"""
buf = bytearray(_MLG_RECORD_SIZE)
start_dt = (
datetime.datetime(
entry.start_time.year, entry.start_time.month, entry.start_time.day,
entry.start_time.hour, entry.start_time.minute, entry.start_time.second,
)
if entry.start_time else None
)
stop_dt = (
datetime.datetime(
entry.stop_time.year, entry.stop_time.month, entry.stop_time.day,
entry.stop_time.hour, entry.stop_time.minute, entry.stop_time.second,
)
if entry.stop_time else None
)
# [0:2] CRC placeholder
buf[0:2] = b"\x00\x00"
# [2:6] Record marker
buf[2:6] = _MLG_RECORD_MARKER
# [6:14] ts1
buf[6:14] = _encode_ts_be(start_dt)
# [14:22] ts2
buf[14:22] = _encode_ts_be(stop_dt)
# [22:26] flags
if stop_dt is None:
flags = MLG_FLAGS_START_ONLY
elif entry.geo_threshold_ips is not None:
flags = MLG_FLAGS_TRIGGER
else:
flags = MLG_FLAGS_INTERVAL
buf[22:26] = flags
# [26:36] serial (10B null-padded)
serial_bytes = serial.encode("ascii", errors="replace")[:10]
buf[26 : 26 + len(serial_bytes)] = serial_bytes
# [36:] text content
pos = 36
if flags == MLG_FLAGS_TRIGGER:
# Extra ts1 copy: [0x08][ts1: 8B]
buf[pos] = 0x08
pos += 1
buf[pos : pos + 8] = _encode_ts_be(start_dt)
pos += 8
if entry.geo_threshold_ips is not None:
geo_text = f"Geo: {entry.geo_threshold_ips:.3f} in/s\x00".encode("ascii")
buf[pos : pos + len(geo_text)] = geo_text
pos += len(geo_text)
return bytes(buf)
def write_mlg(
entries: list[MonitorLogEntry],
serial: str,
path: Union[str, Path],
) -> None:
"""
Write a Blastware .MLG monitor log file.
Args:
entries: List of MonitorLogEntry objects (from get_monitor_log_entries()).
Each entry produces one 292-byte record in the file.
serial: Device serial number string (e.g. "BE11529").
Written to the file header and each record.
path: Destination file path. Extension is not enforced — use ".MLG".
File layout:
[308B header] [N × 292B records]
Note: The 2-byte CRC at the start of each record is written as 0x0000.
The CRC algorithm is unknown (see module docstring).
Raises:
OSError: if the file cannot be written.
"""
path = Path(path)
header = _build_mlg_header(serial)
with open(path, "wb") as f:
f.write(header)
for entry in entries:
record = _build_mlg_record(entry, serial)
f.write(record)
def read_mlg(path: Union[str, Path]) -> list[MonitorLogEntry]:
"""
Parse a Blastware .MLG file into a list of MonitorLogEntry objects.
NOT YET IMPLEMENTED.
Args:
path: Path to the .MLG file.
Returns:
List of MonitorLogEntry objects.
Raises:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_mlg() is not yet implemented")
+10 -3
View File
@@ -280,8 +280,15 @@ _MONTHS = {
def _parse_event_date(s: str) -> Optional[datetime.date]:
"""Parse "April 23, 2026" or "May 8, 2026" → date."""
"""Parse "April 23, 2026", "May 8, 2026" or "2026-08-14" → date.
Blastware writes whichever the PC's settings say: every one of the 81
report-paired waveforms in prod's store (2026-09-30 snapshot) is ISO, and
reading only the long form left their event time unread."""
s = s.strip()
iso = _parse_iso_date(s)
if iso is not None:
return iso
parts = s.replace(",", " ").split()
if len(parts) < 3:
return None
@@ -297,8 +304,8 @@ def _parse_event_date(s: str) -> Optional[datetime.date]:
def _parse_iso_date(s: str) -> Optional[datetime.date]:
"""Parse "2026-05-16" → date. Histograms use ISO format for their
Start Date / Stop Date / Peak Date fields; waveforms use the
"May 8, 2026" long form which `_parse_event_date` handles."""
Start Date / Stop Date / Peak Date fields; a waveform's Event Date may be
either form (see `_parse_event_date`)."""
s = s.strip()
try:
return datetime.date.fromisoformat(s)
+133
View File
@@ -0,0 +1,133 @@
"""
minimateplus/bw_xml_report.py — parse Blastware's `_XML.XML` event report.
Blastware's ACH keeps, in `Sent/`, a full XML report beside each event binary:
`<stem>_<ext>_XML.XML` for `<stem>.<ext>`. It carries every field of the event
report plus every waveform sample or histogram interval, and DL2's backup holds
one for 70,042 Series 3 events back to 2016 (its ASCII reports start in 2025).
SFM uses it only to check its own decode, never as data.
The small `<stem>_<ext>.XML` summary beside it writes decimal commas and is not
this file.
Layout (FileVersion 8.0), as the parser reads it:
- top-level simple elements, e.g. ``<SampleRate>1024 sps</SampleRate>``
- value elements, e.g. ``<TranPPV><Value>0.015</Value><Units>in/s</Units></TranPPV>``
- ``<Channels><Channel>Tran</Channel>...</Channels>``
- the job number and up to four user notes, between the top-level
``<Units>`` and ``<GeoRange>``; each note is tagged with its
operator-editable label (``Project``, ``Location``, ``Seis.Loc`` ...) and
an empty note is omitted
- waveform: ``WaveformDataChannels/Data/Row/Cell``. A row holds only the
channels still running: where channels end at different lengths, the last
rows have fewer cells
- histogram: ``HistogramData`` with ``HistogramDataColumnTitle/ColumnTitle``
and ``HistogramDataIntervals``, alternating ``Time`` and ``Row``
Cell and value text is kept exactly as printed (``">100"``, ``"N/A"``,
``"OORANGE"``, ``"6.7 Volts"``); interpreting it is the comparison's job.
Pure: no I/O beyond reading the file passed to `parse_xml_report_file`.
"""
from __future__ import annotations
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Union
@dataclass
class XmlReport:
scalars: dict[str, str]
units: dict[str, str]
event_units: Optional[str]
channels: list[str]
job_number: Optional[str]
notes: list[tuple[str, str]]
sample_rows: Optional[list[list[str]]]
interval_columns: Optional[list[str]]
intervals: Optional[list[tuple[str, list[str]]]]
def _text(el: ET.Element) -> str:
return (el.text or "").strip()
def _cells(row: ET.Element) -> list[str]:
return [_text(c) for c in row.findall("Cell")]
def parse_xml_report(data: bytes) -> XmlReport:
"""Parse the bytes of an `_XML.XML` event report. Raises ValueError when
they are not well-formed XML (a truncated file, for one)."""
try:
root = ET.fromstring(data)
except ET.ParseError as exc:
raise ValueError(f"not a well-formed XML report: {exc}") from exc
scalars: dict[str, str] = {}
units: dict[str, str] = {}
event_units: Optional[str] = None
channels: list[str] = []
job_number: Optional[str] = None
notes: list[tuple[str, str]] = []
sample_rows: Optional[list[list[str]]] = None
interval_columns: Optional[list[str]] = None
intervals: Optional[list[tuple[str, list[str]]]] = None
in_notes = False
for el in root:
tag = el.tag
if tag == "Units" and len(el) == 0:
event_units = _text(el)
scalars[tag] = event_units
in_notes = True
continue
if tag == "GeoRange":
in_notes = False
if in_notes and len(el) == 0:
# Job number and user notes: never scalars, so the comparison
# scores each once.
if tag == "JobNumber":
job_number = _text(el)
elif _text(el):
notes.append((tag, _text(el)))
continue
if tag == "Channels":
channels = [_text(c) for c in el.findall("Channel")]
elif tag == "WaveformDataChannels":
data_el = el.find("Data")
if data_el is not None:
sample_rows = [_cells(r) for r in data_el.findall("Row")]
elif tag == "HistogramData":
titles = el.find("HistogramDataColumnTitle")
interval_columns = ([" ".join(_text(t).split()) for t in titles.findall("ColumnTitle")]
if titles is not None else [])
body = el.find("HistogramDataIntervals")
intervals = []
time: Optional[str] = None
for child in (body if body is not None else []):
if child.tag == "Time":
time = _text(child)
elif child.tag == "Row":
intervals.append((time or "", _cells(child)))
time = None
elif el.find("Value") is not None:
scalars[tag] = _text(el.find("Value"))
u = el.find("Units")
if u is not None:
units[tag] = _text(u)
elif len(el) == 0:
scalars[tag] = _text(el)
return XmlReport(
scalars=scalars, units=units, event_units=event_units, channels=channels,
job_number=job_number, notes=notes, sample_rows=sample_rows,
interval_columns=interval_columns, intervals=intervals,
)
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport:
return parse_xml_report(Path(path).read_bytes())
+86 -419
View File
@@ -70,15 +70,8 @@ S3_MONITORING_FLAGS = frozenset({0x10, 0x0B})
# ⚠ RETRACTED 2026-10-27 (#46): a trigger block "hardcoded from 3-11-26 -- no
# read exists, Blastware writes this fixed blob". Blastware reads it first (SUB
# 0x2E), and its byte 5 differs by unit and session (01 / 03 / 04 on record), so
# the copy changed that setting on any unit that differed. apply_config reads
# the unit's own block (MiniMateProtocol.read_trigger_config).
# Compliance ASCII slot format (confirmed from 3-11-26 capture + label search):
# Each label occupies a 64-byte slot.
# Value starts at slot_start + 22, max 42 bytes, null-padded.
_COMPLIANCE_SLOT_SIZE = 64
_COMPLIANCE_VALUE_OFFSET = 22
_COMPLIANCE_VALUE_MAX = _COMPLIANCE_SLOT_SIZE - _COMPLIANCE_VALUE_OFFSET # 42
# the copy changed that setting on any unit that differed. A settings write sends
# the unit's own block back (sfm.device_access.s3 change_settings, phase 5).
# ── MiniMateClient ────────────────────────────────────────────────────────────
@@ -922,6 +915,8 @@ class MiniMateClient:
compliance_data: bytes,
trigger_data: bytes,
waveform_data: bytes,
*,
escaped: bool = False,
) -> None:
"""
Push a complete config update to the device using the confirmed write
@@ -949,6 +944,10 @@ class MiniMateClient:
trigger_data: Raw bytes for SUB 82 write (44-byte trigger config).
waveform_data: Raw bytes for SUB 69 write.
`escaped`: False (the default) -- the blocks are logical, as every block
read returns them since phase 5; True for blocks that still hold the
parser's kept escape bytes.
Raises:
RuntimeError: if the client is not connected.
ProtocolError: if any write step fails (timeout, bad ack SUB).
@@ -960,32 +959,36 @@ class MiniMateClient:
# 2026-10-27): a block refused after 68 + 73 had been sent left a partial
# write behind. write_image is the same check each write makes.
from .protocol import (SUB_COMPLIANCE_WRITE, SUB_EVENT_INDEX_WRITE,
SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE, write_image)
SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE, ImageRefused,
write_image)
for sub, data in ((SUB_EVENT_INDEX_WRITE, event_index_data),
(SUB_COMPLIANCE_WRITE, compliance_data),
(SUB_TRIGGER_CONFIG_WRITE, trigger_data),
(SUB_WAVEFORM_DATA_WRITE, waveform_data)):
write_image(sub, data)
try:
write_image(sub, data, escaped=escaped)
except ValueError as exc: # refused before any frame: the caller audits "nothing sent"
raise ImageRefused(str(exc)) from exc
# 68 → 73
log.info("push_config_raw: write event index (SUB 68)")
proto.write_event_index(event_index_data)
proto.write_event_index(event_index_data, escaped=escaped)
log.info("push_config_raw: confirm B (SUB 73)")
proto.write_confirm(SUB_WRITE_CONFIRM_B)
# 71×3 → 72 (handled internally by write_compliance_config_raw)
log.info("push_config_raw: write compliance config (SUB 71 ×3 + confirm 72)")
proto.write_compliance_config_raw(compliance_data)
proto.write_compliance_config_raw(compliance_data, escaped=escaped)
# 82 → 83
log.info("push_config_raw: write trigger config (SUB 82)")
proto.write_trigger_config(trigger_data)
proto.write_trigger_config(trigger_data, escaped=escaped)
log.info("push_config_raw: trigger confirm (SUB 83)")
proto.write_confirm(SUB_TRIGGER_CONFIRM)
# 69 → 74 → 72
log.info("push_config_raw: write waveform data (SUB 69)")
proto.write_waveform_data(waveform_data)
proto.write_waveform_data(waveform_data, escaped=escaped)
log.info("push_config_raw: confirm C (SUB 74)")
proto.write_confirm(SUB_WRITE_CONFIRM_C)
log.info("push_config_raw: confirm A (SUB 72)")
@@ -993,120 +996,6 @@ class MiniMateClient:
log.info("push_config_raw: complete")
def apply_config(
self,
*,
# Recording parameters
recording_mode: Optional[int] = None,
sample_rate: Optional[int] = None,
record_time: Optional[float] = None,
histogram_interval_sec: Optional[int] = None,
# Threshold parameters (geo channels, in/s)
trigger_level_geo: Optional[float] = None,
alarm_level_geo: Optional[float] = None,
geo_range: Optional[int] = None, # 0x00=Normal 10in/s, 0x01=Sensitive 1.25in/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,
) -> None:
"""
Read the current device config, apply any supplied changes to the
compliance block, and write the full config back to the device.
Only non-None arguments are modified; all other bytes are round-tripped
verbatim from the device.
Configurable fields
-------------------
Recording parameters:
recording_mode : int — 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous
sample_rate : int — samples/sec; valid values: 1024, 2048, 4096
record_time : float — record duration in seconds (e.g. 2.0, 3.0)
Trigger/alarm thresholds and range (geo channels):
trigger_level_geo : float — trigger threshold in/s (e.g. 0.5)
alarm_level_geo : float — alarm threshold in/s (e.g. 1.0)
geo_range : int — 0x00=Normal 10.000 in/s, 0x01=Sensitive 1.250 in/s
(written to Tran/Vert/Long channel blocks)
Project / operator strings (max 41 ASCII characters each):
project : str
client_name : str
operator : str
seis_loc : str — sensor location
notes : str — extended notes
Write sequence (confirmed from 3-11-26 BW TX capture):
68→73 | 71×3→72 | 82→83 | 69→74→72
Write payloads:
event_index_data : 88 bytes — read live via SUB 08
compliance_data : ~2128 bytes — read live via SUB 1A (~2126 bytes, varies ±1-2) + \\x00\\x00 footer
trigger_data : 26 bytes — read live via SUB 2E (was hard-coded; #46)
waveform_data : 204 bytes — read live via SUB 09
Raises:
RuntimeError: if not connected.
ProtocolError: if any read or write step fails.
ValueError: if compliance buffer is shorter than the 2082-byte write minimum.
"""
proto = self._require_proto()
# 1. Read current payloads from the device
log.info("apply_config: reading event index (SUB 08)")
event_index_data = proto.read_event_index()
log.info("apply_config: reading compliance config (SUB 1A)")
compliance_raw = proto.read_compliance_config() # ~2126 bytes (varies ±1-2 by DLE jitter)
log.info("apply_config: reading waveform data (SUB 09)")
waveform_data = proto.read_waveform_data_raw() # 204 bytes
log.info("apply_config: reading trigger config (SUB 2E)")
trigger_data = proto.read_trigger_config() # 26 bytes, this unit's own
# 2. Patch the compliance buffer and build the 2128-byte write payload
compliance_data = _encode_compliance_config(
compliance_raw,
recording_mode=recording_mode,
sample_rate=sample_rate,
record_time=record_time,
histogram_interval_sec=histogram_interval_sec,
trigger_level_geo=trigger_level_geo,
alarm_level_geo=alarm_level_geo,
geo_range=geo_range,
project=project,
client_name=client_name,
operator=operator,
seis_loc=seis_loc,
notes=notes,
)
log.info("apply_config: compliance payload ready (%d bytes)", len(compliance_data))
# 3. Push the full write sequence to the device
self.push_config_raw(event_index_data, compliance_data, trigger_data, waveform_data)
log.info("apply_config: complete")
def set_project_info(
self,
project: Optional[str] = None,
client_name: Optional[str] = None,
operator: Optional[str] = None,
seis_loc: Optional[str] = None,
notes: Optional[str] = None,
) -> None:
"""Backwards-compat shim — delegates to apply_config()."""
self.apply_config(
project=project,
client_name=client_name,
operator=operator,
seis_loc=seis_loc,
notes=notes,
)
# ── Call home config ──────────────────────────────────────────────────────
def get_call_home_config(self) -> CallHomeConfig:
@@ -1127,6 +1016,33 @@ class MiniMateClient:
raw = proto.read_call_home_config()
return _decode_call_home_config(raw)
def read_call_home_raw(self) -> bytes:
"""The `0x2C` reply payload as read (125 B, kept escapes in), for a
read-modify-write (`call_home_image`)."""
return self._require_proto().read_call_home_config()
def read_compliance_content(self) -> bytes:
"""The 1A settings read as the logical 2,090-byte block, unjudged (a
monitoring unit's device-info answer comes back as it is; see
`minimateplus.protocol.is_compliance_content`)."""
return self._require_proto().read_compliance_content()
def read_settings_blocks(self) -> dict:
"""The four blocks a settings write sends back, each as its read returns it:
event index (08), settings (1A, logical), trigger (2E), waveform data (09)."""
proto = self._require_proto()
return {"event_index": proto.read_event_index(),
"compliance": proto.read_compliance_content(),
"trigger": proto.read_trigger_config(),
"waveform": proto.read_waveform_data_raw()}
def write_call_home_image(self, image: bytes) -> None:
"""Send a `0x7E` image (`call_home_image`) and its `0x7F` confirm, each ack
checked -- framed once, never unescaped again. Raises ImageRefused before
any byte goes out for an image that is not a whole block. No retry: what
happened is the caller's to read back."""
self._require_proto().write_call_home_image(image)
def set_call_home_config(
self,
*,
@@ -2096,217 +2012,6 @@ def _extract_project_strings(data: bytes) -> Optional[ProjectInfo]:
)
def _encode_compliance_config(
raw: bytes,
*,
recording_mode: Optional[int] = None,
sample_rate: Optional[int] = None,
record_time: Optional[float] = None,
trigger_level_geo: Optional[float] = None,
alarm_level_geo: Optional[float] = None,
geo_range: Optional[int] = None, # 0x00=Normal 10in/s, 0x01=Sensitive 1.25in/s
histogram_interval_sec: Optional[int] = None,
project: Optional[str] = None,
client_name: Optional[str] = None,
operator: Optional[str] = None,
seis_loc: Optional[str] = None,
notes: Optional[str] = None,
) -> bytes:
"""
Patch a live 2126-byte compliance buffer (read from the device) with any
supplied field values and return the 2128-byte write payload.
Only non-None arguments are modified; everything else is round-tripped verbatim.
Numeric field locations (all anchor-relative or label-relative — immune to
DLE-jitter shifts):
Anchor: b'\\xbe\\x80\\x00\\x00\\x00\\x00' (confirmed stable, both BE11529 and BE18189)
recording_mode → uint8 at anchor_pos - 8 (BOTH read and write)
Values: 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous
NOTE: The byte at anchor_pos - 7 is always 0x10 (a DLE marker regenerated by
device firmware in every E5 response). It must NOT be overwritten during
write — doing so causes anchor drift (+1 per write cycle).
CORRECTION 2026-04-21: previous doc stated anchor-7 for write; empirically
confirmed wrong — writing to anchor-7 shifts the anchor by 1 on every cycle.
sample_rate → uint16 BE at anchor_pos - 6
histogram_interval_sec → uint16 BE at anchor_pos - 4 (seconds; mode-gated to Histogram/Histogram+Continuous)
Valid values: 2, 5, 15, 60, 300, 900 (= 2s, 5s, 15s, 1m, 5m, 15m)
record_time → float32 BE at anchor_pos + 6
Channel block (anchored on b"Tran" with unit-string guard):
geo_range → uint8 at tran_pos + 33 (confirmed 2026-04-20)
0x00 = Normal 10.000 in/s, 0x01 = Sensitive 1.250 in/s
Written to Tran, Vert, Long channel blocks (all three).
adc_scale_factor → float32 BE at tran_pos + 28 (= 6.206053; do NOT write)
trigger_level_geo → float32 BE at tran_pos + 34
"in.\\x00" → unit string at tran_pos + 38 (layout guard)
alarm_level_geo → float32 BE at tran_pos + 42
"/s\\x00\\x00" → unit string at tran_pos + 46 (layout guard)
NOTE: tran_pos+28 (float32 = 6.206053) is the ADC-to-velocity scale factor
(= 1/sensitivity, (in/s)/V — Interface Handbook §4.5: 1.61133 V × 6.206053 = 10.000 in/s).
This is a hardware/firmware constant common to all MiniMate Plus S3 units.
It must NOT be written — do not add it back as a parameter.
String field locations (64-byte slots, label+22 format):
b"Project:" → value at label_pos + 22, max 41 chars + null
b"Client:" → value at label_pos + 22, max 41 chars + null
b"User Name:" → value at label_pos + 22, max 41 chars + null
b"Seis Loc:" → value at label_pos + 22, max 41 chars + null
b"Extended Notes"→ value at label_pos + 22, max 41 chars + null
Returns:
2128-byte write payload: patched 2126-byte buffer + 2-byte footer \\x00\\x00.
(Checksum formula for the footer is unknown; \\x00\\x00 confirmed accepted
by the device in POC test 2026-04-07.)
Raises:
ValueError: if raw is shorter than the minimum needed for the 3-chunk write.
"""
# Total size is nominally ~2126 bytes but varies by ±1-2 bytes depending on
# DLE jitter in the E5 read response (0x10 bytes in the config data cause
# 1-byte expansions per occurrence during DLE stuffing/unstuffing). The
# anchor-based field access and the chunk splitter (fixed chunk1=1027,
# chunk2=1055, chunk3=remainder) both handle variable length correctly.
# Only enforce a minimum — must have at least chunk1+chunk2 bytes of content.
_MIN_COMPLIANCE_LEN = 1027 + 1055 # = 2082
if len(raw) < _MIN_COMPLIANCE_LEN:
raise ValueError(
f"_encode_compliance_config: compliance buffer too short "
f"({len(raw)} bytes, need at least {_MIN_COMPLIANCE_LEN})"
)
if len(raw) not in range(2124, 2132):
log.warning(
"_encode_compliance_config: unusual compliance buffer length %d "
"(expected ~2126); proceeding with anchor-based access",
len(raw),
)
buf = bytearray(raw)
# ── Numeric: recording_mode + sample_rate + record_time (anchor-relative) ──
_ANC = b'\xbe\x80\x00\x00\x00\x00'
_anc = buf.find(_ANC, 0, 150)
# Log anchor position every time so we can detect unexpected shifts due to
# DLE jitter or firmware differences. Expected position is ~15.
if _anc < 0:
log.warning(
"_encode_compliance_config: anchor NOT FOUND in cfg[0:150] "
"(buf len=%d) — all anchor-relative writes will be skipped",
len(buf),
)
else:
log.info(
"_encode_compliance_config: anchor at cfg[%d] buf_len=%d "
"(recording_mode@%d DLE_marker@%d sample_rate@%d:%d "
"histogram_interval@%d:%d record_time@%d:%d)",
_anc, len(buf),
_anc - 8,
_anc - 7,
_anc - 6, _anc - 4,
_anc - 4, _anc - 2,
_anc + 6, _anc + 10,
)
if recording_mode is not None:
if _anc < 8:
log.warning("_encode_compliance_config: anchor not found — cannot write recording_mode")
else:
# Write to anchor-8, same physical position as the E5 read format.
# The byte at anchor-7 is a DLE marker (0x10) that the device firmware
# regenerates in every E5 response — it must NOT be overwritten.
# Writing to anchor-7 causes the device to add an extra byte on the
# next read-back, drifting the anchor by +1 on every write cycle.
# (CLAUDE.md "anchor-7 write" was incorrect — confirmed 2026-04-21)
buf[_anc - 8] = recording_mode & 0xFF
log.debug("_encode_compliance_config: recording_mode=0x%02X -> offset %d",
recording_mode, _anc - 8)
if sample_rate is not None:
if _anc < 6:
log.warning("_encode_compliance_config: anchor not found — cannot write sample_rate")
else:
struct.pack_into(">H", buf, _anc - 6, sample_rate)
log.debug("_encode_compliance_config: sample_rate=%d -> offset %d", sample_rate, _anc - 6)
if histogram_interval_sec is not None:
if _anc < 4:
log.warning("_encode_compliance_config: anchor not found — cannot write histogram_interval")
else:
struct.pack_into(">H", buf, _anc - 4, histogram_interval_sec)
log.debug("_encode_compliance_config: histogram_interval=%ds -> offset %d",
histogram_interval_sec, _anc - 4)
if record_time is not None:
if _anc < 0 or _anc + 10 > len(buf):
log.warning("_encode_compliance_config: anchor not found — cannot write record_time")
else:
struct.pack_into(">f", buf, _anc + 6, record_time)
log.debug("_encode_compliance_config: record_time=%.3f -> offset %d", record_time, _anc + 6)
# ── Numeric: channel block (Tran label + unit-string guard) ───────────────
# NOTE: tran_pos+24 (write format) or tran_pos+28 (E5 read format) is the
# ADC-to-velocity scale factor (6.206053, hardware constant — never written).
# geo_range is written to ALL THREE geo channel blocks (Tran, Vert, Long),
# confirmed from 4-20-26 captures showing the byte at label+29 in each block.
_needs_channel = any(v is not None for v in (trigger_level_geo, alarm_level_geo, geo_range))
if _needs_channel:
_tran = buf.find(b"Tran", 44)
_valid = (
_tran >= 0
and buf[_tran + 4 : _tran + 5] != b"2"
and _tran + 50 <= len(buf)
and buf[_tran + 38 : _tran + 42] == b"in.\x00"
and buf[_tran + 46 : _tran + 50] == b"/s\x00\x00"
)
if not _valid:
log.warning(
"_encode_compliance_config: 'Tran' channel block not found or unit "
"guard failed — trigger/alarm/geo_range will not be written"
)
else:
if trigger_level_geo is not None:
struct.pack_into(">f", buf, _tran + 34, trigger_level_geo)
log.debug("_encode_compliance_config: trigger_level_geo=%.4f -> offset %d", trigger_level_geo, _tran + 34)
if alarm_level_geo is not None:
struct.pack_into(">f", buf, _tran + 42, alarm_level_geo)
log.debug("_encode_compliance_config: alarm_level_geo=%.4f -> offset %d", alarm_level_geo, _tran + 42)
if geo_range is not None:
# Write geo_range to all three geo channel blocks (Tran, Vert, Long).
# Field at label+33 in the E5-format compliance bytes (same in read and write
# since the 2126-byte payload is round-tripped verbatim).
# 0x00 = Normal 10.000 in/s, 0x01 = Sensitive 1.250 in/s.
for _ch_label in (b"Tran", b"Vert", b"Long"):
_ch = buf.find(_ch_label, 44)
if _ch >= 0 and buf[_ch + 4 : _ch + 5] != b"2" and _ch + 34 <= len(buf):
buf[_ch + 33] = geo_range & 0xFF
log.debug(
"_encode_compliance_config: geo_range=0x%02X -> %s+33 offset %d",
geo_range, _ch_label.decode(), _ch + 33,
)
# ── ASCII strings (64-byte slot, value at label_pos+22) ───────────────────
def _set_string(label: bytes, value: Optional[str]) -> None:
if value is None:
return
idx = buf.find(label)
if idx < 0:
log.warning("_encode_compliance_config: label %r not found", label)
return
val_bytes = value.encode("ascii", errors="replace")[:_COMPLIANCE_VALUE_MAX - 1]
padded = val_bytes + b"\x00" * (_COMPLIANCE_VALUE_MAX - len(val_bytes))
buf[idx + _COMPLIANCE_VALUE_OFFSET : idx + _COMPLIANCE_SLOT_SIZE] = padded
log.debug("_encode_compliance_config: %r -> %r", label, value)
_set_string(b"Project:", project)
_set_string(b"Client:", client_name)
_set_string(b"User Name:", operator)
_set_string(b"Seis Loc:", seis_loc)
_set_string(b"Extended Notes", notes)
# 2-byte footer — checksum formula unknown; \x00\x00 confirmed accepted by device
return bytes(buf) + b"\x00\x00"
def _decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None:
@@ -2365,92 +2070,53 @@ def _decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None:
# ── recording_mode / sample_rate / histogram_interval / record_time ─────────
# 6-byte stable anchor: b'\xbe\x80\x00\x00\x00\x00' — confirmed across BE11529
# and BE18189. The 4 bytes immediately before the anchor are NOT constant:
# bytes -4:-2 are the histogram_interval (uint16 BE, seconds), and bytes -2:0
# are zero padding. The old "10-byte anchor" (\x01\x2c\x00\x00 prefix) was
# only constant when the histogram interval happened to be 5 min (0x012C = 300).
# and BE18189. These four fields are read from the reply with its escapes
# REMOVED (unescape_reply): the unit escapes 02/03/04/10 in every reply and
# S3FrameParser keeps the `10` of `10 02/03/04`, so on the raw bytes an escaped
# mode, sample rate or interval moves every field after it by one. BE9441 at
# Histogram / 4096 sps / 2 s read 0 sps and a 4098 s interval (2026-10-29).
#
# E5 read format layout relative to 6-byte anchor:
# _anchor - 8 : recording_mode (uint8)
# _anchor - 7 : 0x10 (extra byte E5 read only; absent in SUB 71 write)
# _anchor - 6 : sample_rate_hi (uint16 BE, MSB)
# _anchor - 5 : sample_rate_lo (uint16 BE, LSB)
# _anchor - 4 : histogram_interval_hi (uint16 BE, seconds, MSB)
# _anchor - 3 : histogram_interval_lo (uint16 BE, seconds, LSB)
# _anchor - 2 : 0x00 (padding)
# _anchor - 1 : 0x00 (padding)
# _anchor : \xbe\x80\x00\x00\x00\x00 (6-byte anchor)
# _anchor + 6 : record_time (float32 BE)
# Layout after unescaping, measured on every recorded reply (four settings,
# two of them Blastware's own writes -- tests/test_s3_compliance_anchor_fields.py):
# _anchor - 7 : recording_mode (uint8)
# _anchor - 6 : sample_rate (uint16 BE)
# _anchor - 4 : histogram_interval_sec (uint16 BE, seconds)
# _anchor - 2 : 0x00 0x00 (padding)
# _anchor : \xbe\x80\x00\x00\x00\x00
# _anchor + 6 : record_time (float32 BE)
# ⚠ The old raw layout's "anchor - 7 = constant 0x10" was the escape in front
# of `04` at 1024 sps (0x0400); it read right only at that rate.
# Everything below this block (channel block, strings) still reads the RAW
# bytes: its label-relative offsets were measured on them and are wrong
# unescaped. A reply with no anchor (BE9441 answered 1A with its device-info
# block while monitoring, 2026-10-29) leaves all four fields None.
_ANCHOR = b'\xbe\x80\x00\x00\x00\x00'
_anchor = data.find(_ANCHOR, 0, 150)
logical = unescape_reply(data)
_anchor = logical.find(_ANCHOR, 0, 150)
# Log anchor position on every decode so we can compare read vs write and
# catch unexpected shifts from DLE jitter or firmware differences.
# Expected position is ~15 for the E5 read payload (anchor - 8 = recording_mode).
if _anchor < 0:
log.warning(
"_decode_compliance_config_into: anchor NOT FOUND in data[0:150] (len=%d)",
len(data),
)
else:
log.info(
"_decode_compliance_config_into: anchor at data[%d] data_len=%d "
"(expected ~15; recording_mode@%d sample_rate@%d:%d "
"histogram_interval@%d:%d record_time@%d:%d)",
_anchor, len(data),
_anchor - 8,
_anchor - 6, _anchor - 4,
_anchor - 4, _anchor - 2,
_anchor + 6, _anchor + 10,
)
if _anchor >= 8 and _anchor + 10 <= len(data):
try:
config.recording_mode = data[_anchor - 8]
log.debug(
"compliance_config: recording_mode = 0x%02X (anchor@%d)", config.recording_mode, _anchor
)
except Exception as exc:
log.warning("compliance_config: recording_mode extraction failed: %s", exc)
try:
config.sample_rate = struct.unpack_from(">H", data, _anchor - 6)[0]
log.debug(
"compliance_config: sample_rate = %d Sa/s (anchor@%d)", config.sample_rate, _anchor
)
except Exception as exc:
log.warning("compliance_config: sample_rate extraction failed: %s", exc)
try:
config.histogram_interval_sec = struct.unpack_from(">H", data, _anchor - 4)[0]
log.debug(
"compliance_config: histogram_interval = %d s (anchor@%d)",
config.histogram_interval_sec, _anchor
)
except Exception as exc:
log.warning("compliance_config: histogram_interval extraction failed: %s", exc)
try:
config.record_time = struct.unpack_from(">f", data, _anchor + 6)[0]
log.debug(
"compliance_config: record_time = %.3f s (anchor@%d)", config.record_time, _anchor
)
except Exception as exc:
log.warning("compliance_config: record_time extraction failed: %s", exc)
elif _anchor >= 6 and _anchor + 10 <= len(data):
# Fallback: anchor found but not enough bytes before it for recording_mode
log.warning("compliance_config: anchor too close to start (anchor@%d) — skipping recording_mode", _anchor)
try:
config.sample_rate = struct.unpack_from(">H", data, _anchor - 6)[0]
except Exception:
pass
try:
config.record_time = struct.unpack_from(">f", data, _anchor + 6)[0]
except Exception:
pass
else:
log.warning(
"compliance_config: anchor %s not found in cfg[0:150] (len=%d) "
"— sample_rate, record_time and recording_mode will be None",
_ANCHOR.hex(), len(data),
)
elif _anchor >= 7 and _anchor + 10 <= len(logical):
log.info("_decode_compliance_config_into: anchor at unescaped[%d] data_len=%d",
_anchor, len(data))
config.recording_mode = logical[_anchor - 7]
config.sample_rate = struct.unpack_from(">H", logical, _anchor - 6)[0]
config.histogram_interval_sec = struct.unpack_from(">H", logical, _anchor - 4)[0]
config.record_time = struct.unpack_from(">f", logical, _anchor + 6)[0]
log.debug(
"compliance_config: recording_mode=0x%02X sample_rate=%d histogram_interval=%d s "
"record_time=%.3f s (anchor@%d unescaped)",
config.recording_mode, config.sample_rate, config.histogram_interval_sec,
config.record_time, _anchor,
)
else:
log.warning("compliance_config: anchor at unescaped[%d] is too close to an end "
"(len=%d) — mode, rate, interval and record time left None",
_anchor, len(logical))
# ── Project strings ───────────────────────────────────────────────────────
try:
@@ -2688,8 +2354,9 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
header, so field offsets below are relative to data[11]).
NOTE: frame.data has the checksum byte already stripped by S3FrameParser
(_finalise returns raw_payload[5:] where raw_payload = body[:-1]).
There is NO trailing checksum byte in section.
(_finalise returns raw_payload[5:], the checksum and, since #58, the 10 of
an escaped checksum removed). There is NO trailing checksum byte in section;
before #58 one status reply in 63 kept that 10 and read 419.84 V.
Monitoring flag (confirmed 4-8-26/2ndtry, byte diff of all 144 data frames):
section[1] == 0x00 → idle
+23
View File
@@ -0,0 +1,23 @@
"""
minimateplus/crc.py — Instantel's record checksum, shared by every reader that checks one.
CRC-16/AUG-CCITT: poly 0x1021, init 0x1D0F, no reflection, no final XOR. The
same rule covers a Micromate's setup blocks (0x1A, 0x08, 0x2E; stored big-endian),
a Blastware event file's footer (big-endian) and every .MLG record (little-endian).
Each block says where its checksum sits; this module only computes it.
"""
from __future__ import annotations
_POLY = 0x1021
_INIT = 0x1D0F
def crc16_aug_ccitt(data: bytes) -> int:
"""CRC-16/AUG-CCITT of `data` (check value: b"123456789" -> 0xE5CC)."""
c = _INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
+506
View File
@@ -0,0 +1,506 @@
"""
minimateplus/decode_check.py — SFM's file-only decode, set beside Blastware's
report of the same event, field by field.
The decode checker's core (`docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`).
SFM's side comes from the event bytes alone, through
`decode_blastware_bytes(raw, name=None)`: no filename, because SFM's own
download and call-in paths have none, and no report overlay. Nothing from the
reference reaches it. SFM's own assumptions stay in -- geophone counts become
in/s at the Normal range -- because the point is to judge what SFM produces.
Pure: no I/O, and no import from `sfm/`.
"""
from __future__ import annotations
import datetime
import math
import re
from dataclasses import dataclass, field
from typing import Callable, Optional, Sequence
from .bw_xml_report import XmlReport
from .event_file_io import (interval_times, _GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
decode_blastware_bytes, mic_count_divisor, over_full_scale)
from .histogram_codec import half_period_to_hz
from .models import Event
from .waveform_codec import mic_count_to_db
# SFM's conversion at the Normal range (10 in/s full scale = 32000 counts),
# which SFM assumes when it cannot read the event's range from the file.
GEO_IPS_PER_COUNT: float = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
_CHANNELS = ("Tran", "Vert", "Long", "MicL")
_EVENT_TYPE = {"Waveform": "Full Waveform", "Histogram": "Full Histogram"}
# How Blastware prints the setup fields SFM reads (measured 2026-11-03).
_MONTHS = ("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December")
_TRIGGERED_BY = {0x0001: "Tran", 0x0002: "Vert", 0x0004: "Long", 0x0008: "MicL", 0x0200: "Manual"}
_STOP_MODES = {0: "Fixed"}
_MIC_TYPES = {2: "Linear Weighting"}
_GEO_TRIGGERS, _MIC_TRIGGER = 0x07, 0x08
# Blastware turns the mic trigger level from psi to dB with 6895 Pa per psi, not
# 6894.757: 4,272 / 4,272 DL2 levels against 4,271 (the odd one 0.01 psi,
# printed 130.8 dB(L), is 130.7498 at the exact constant).
_TRIGGER_PA_PER_PSI = 6895.0
def _setup_values(ev: Event) -> dict[str, object]:
out: dict[str, object] = {}
di = ev.device_info
if di is not None:
out["SerialNumber"] = di.serial
fw = di.firmware_version or ""
if di.dsp_version and fw.startswith("S33") and di.model:
# "V 10.72-8.17 MiniMate Plus" from "10.72", "S338.17" and the model --
# the only version in DL2, so the rule is proven for it alone.
out["Version"] = f"V {di.dsp_version}-{fw[3:]} {di.model}"
if di.calibration_date and di.calibrated_by:
c = di.calibration_date
out["Calibration"] = f"{_MONTHS[c.month - 1]} {c.day}, {c.year} by {di.calibrated_by}"
out["BatteryLevel"] = ev.battery_volts
out["Trigger"] = _TRIGGERED_BY.get(ev.triggered_by)
out["RecordStopMode"] = _STOP_MODES.get(ev.record_stop_mode)
out["Microphone"] = _MIC_TYPES.get(ev.mic_type)
# dB or psi is Blastware's preference, not the unit's (carve-out
# units-is-a-display-preference); SFM reports dB, the default.
out["Units"] = "in/s and dB(L)" if ev.mic_type is not None else "in/s"
# Blastware prints a trigger level only for a channel that is a trigger
# source, and none for a Manual trigger.
src, manual = ev.trigger_sources or 0, ev.triggered_by == 0x0200
if src & _GEO_TRIGGERS and not manual:
out["GeoTriggerLevel"] = ev.trigger_level_geo
if src & _MIC_TRIGGER and not manual and ev.trigger_level_mic_psi:
psi = ev.trigger_level_mic_psi
out["MicTriggerLevel psi(L)"] = psi
out["MicTriggerLevel dB(L)"] = 20 * math.log10(psi * _TRIGGER_PA_PER_PSI / 2e-5)
return out
@dataclass
class SfmSide:
event: Event
values: dict[str, object] # reference tag -> SFM's value; absent or None = blank
notes: list[str] # non-empty user-note slots, in order
job_number: Optional[str] # only when the file says Blastware shows it
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
counts: dict[str, list[int]] # waveform samples or histogram interval peaks
geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it
mic_divisor: int = 1 # mic counts per 0.25 Pa, at the mic's range
# interval column -> SFM's value per interval (a number, or Blastware's word)
interval_values: dict[str, list[object]] = field(default_factory=dict)
interval_times: Optional[list[str]] = None # each interval's printed time
def interval_frequency(halfp: int, sample_rate: int) -> object:
"""An interval's frequency as Blastware prints it: "N/A" for a half-period
of 0, ">100" (">200" at 2048 sps) at 5 samples or fewer, "<1.0" below 1 Hz,
else (sample rate / 2) / half-period in Hz. Measured on ~3.1 M DL2 cells,
2026-11-03 (#50: the rate, not a fixed 512)."""
if halfp == 0:
return "N/A"
hz = half_period_to_hz(halfp, sample_rate)
if hz is None:
return f">{round(100 * sample_rate / 1024)}"
return "<1.0" if hz < 1.0 else hz
def _interval_size(seconds: int) -> str:
n, unit = (seconds // 60, "minute") if seconds % 60 == 0 else (seconds, "second")
return f"{n} {unit}{'' if n == 1 else 's'}"
def sfm_side(raw: bytes) -> SfmSide:
"""What SFM makes of an event from its bytes alone."""
ev = decode_blastware_bytes(raw, name=None)
counts = {ch: list((ev.raw_samples or {}).get(ch) or []) for ch in _CHANNELS}
pv, pi, ts = ev.peak_values, ev.project_info, ev.timestamp
values: dict[str, object] = {
"EventType": _EVENT_TYPE.get(ev.record_type, ev.record_type),
"SampleRate": ev.sample_rate,
"RecordTime": ev.rectime_seconds,
"Pre-triggerLength": (-ev.pretrig_samples / ev.sample_rate
if ev.pretrig_samples is not None and ev.sample_rate else None),
# SFM's interval count is its decoded entry count; the reference
# carries this field for histograms only.
"NumberofIntervals": len(counts["Tran"]) or None,
"GeoRange": _GEO_FS_BY_RANGE.get(ev.geo_range),
}
if ts is not None:
date = f"{ts.year:04d}-{ts.month:02d}-{ts.day:02d}"
time = f"{ts.hour:02d}:{ts.minute:02d}:{ts.second:02d}"
# The event's time, under both of Blastware's names for it, so a time
# is judged as a time even while the type is wrong (#41).
values.update(EventDate=date, EventTime=time,
HistogramStartDate=date, HistogramStartTime=time)
if pv is not None:
values.update(TranPPV=pv.tran, VertPPV=pv.vert, LongPPV=pv.long,
PeakVectorSum=pv.peak_vector_sum)
# A waveform's peak detail (None on a histogram, so not reported).
for tag, value in (("TranTimeofPeak", pv.tran_time_of_peak),
("VertTimeofPeak", pv.vert_time_of_peak),
("LongTimeofPeak", pv.long_time_of_peak),
("MicLTimeofPeak", pv.micl_time_of_peak),
("PeakVectorSumTimeSum", pv.pvs_time),
("TranPeakAcceleration", pv.tran_peak_accel_g),
("VertPeakAcceleration", pv.vert_peak_accel_g),
("LongPeakAcceleration", pv.long_peak_accel_g),
("TranPeakDisplacement", pv.tran_peak_disp_in),
("VertPeakDisplacement", pv.vert_peak_disp_in),
("LongPeakDisplacement", pv.long_peak_disp_in)):
if value is not None:
values[tag] = value
# The unit's ZC frequency, every record type. Above range it is judged
# by its flag (_compare_scalar); below 1 Hz Blastware prints a word.
for tag, hz in (("TranZCFreq", pv.tran_zc_freq), ("VertZCFreq", pv.vert_zc_freq),
("LongZCFreq", pv.long_zc_freq), ("MicLZCFreq", pv.mic_zc_freq)):
if hz is not None:
values[tag] = "<1.0" if hz < 1.0 else hz
# Blastware's "Out of Range" line: on every DL2 event whose mic is over
# range, and on no other (18 / 18, 2026-11-09).
if pv is not None and pv.mic_over_range:
values["OORANGE"] = "Out of Range"
# The event's Monitor Log line, from the footer (2026-11-08).
if ev.monitor_log is not None:
ml = ev.monitor_log
values["MonitorLog"] = (f'{ml.start:%Y-%m-%d %H:%M:%S} - {ml.stop:%Y-%m-%d %H:%M:%S} '
f'"{ml.description}"')
# The unit's sensor check (2026-11-06), every record type.
for ch, r in (ev.sensor_check_results or {}).items():
values[f"{ch}TestResults"] = r.result
for tag, value in (("TestFreq", r.freq_hz), ("TestRatio", r.ratio),
("TestAmplitude", r.amplitude_mv)):
if value is not None:
values[f"{ch}{tag}"] = value
if counts["MicL"]:
values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"])
/ mic_count_divisor(ev.mic_range))
values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None
values.update(_setup_values(ev))
if ev.stop_time is not None:
values.update(HistogramStopDate=ev.stop_time.strftime("%Y-%m-%d"),
HistogramStopTime=ev.stop_time.strftime("%H:%M:%S"))
if ev.histogram_interval_sec:
values["IntervalSize"] = _interval_size(ev.histogram_interval_sec)
interval_values: dict[str, list[object]] = {}
if ev.interval_half_periods and ev.sample_rate:
for ch, hps in ev.interval_half_periods.items():
interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps]
if ev.interval_pvs:
# OORANGE when any geophone passes full scale in that interval: 16 / 16
# DL2 cells, and none of 2,862 without one (2026-11-09).
geo = [counts[c] for c in _GEO if counts.get(c)]
interval_values["Geo PVS in/s"] = [
"OORANGE" if any(i < len(g) and over_full_scale(g[i], "Tran") for g in geo) else v
for i, v in enumerate(ev.interval_pvs)]
times = None
n = len(counts["Tran"])
if ev.record_type == "Histogram" and ts is not None and ev.histogram_interval_sec and n:
start = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
ends = interval_times(start, ev.histogram_interval_sec, ev.stop_time, n)
times = [t.strftime("%Y-%m-%d %H:%M:%S") for t in ends]
# A peak's date and time are those of the interval holding it (first).
for tag, series in (("TranPeak", counts["Tran"]), ("VertPeak", counts["Vert"]),
("LongPeak", counts["Long"]), ("MicL", counts["MicL"]),
("PeakVectorSum", ev.interval_pvs)):
if series and len(series) == n:
j = max(range(n), key=lambda q: abs(series[q]))
values[f"{tag}Date"] = ends[j].strftime("%Y-%m-%d")
values[f"{tag}Time"] = ends[j].strftime("%H:%M:%S")
return SfmSide(
event=ev,
values=values,
notes=[v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v]
if pi is not None else [],
job_number=str(pi.job_number) if pi is not None and pi.job_number_enabled else None,
channels=[ch for ch in _CHANNELS if counts[ch]],
counts=counts,
geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS,
mic_divisor=mic_count_divisor(ev.mic_range),
interval_values=interval_values,
interval_times=times,
)
# ── The comparison ──────────────────────────────────────────────────────────
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
# Not event data: the report's own format version and Blastware's file name.
_NOT_COMPARED = {"FileVersion", "FileName"}
_NUMBER = re.compile(r"^\s*(-?\d+(?:\.\d+)?)")
_GEO = ("Tran", "Vert", "Long")
@dataclass
class FieldResult:
field: str
verdict: str
bw: Optional[str]
sfm: Optional[str]
detail: str = ""
carveout: Optional[str] = None
def _printed_number(printed: str) -> Optional[tuple[float, int]]:
m = _NUMBER.match(printed)
if not m:
return None
num = m.group(1)
return float(num), (len(num) - num.index(".") - 1 if "." in num else 0)
def matches_printed(value: float, printed: str) -> bool:
"""True when `value` prints as `printed` at Blastware's precision. Blastware
rounds halves away from zero (-0.0625 s -> -0.063), so half a unit of the last
printed decimal either way is a match."""
p = _printed_number(printed)
return p is not None and abs(value - p[0]) <= 0.5 * 10 ** -p[1] + 1e-9
def _render(value: object, printed: str) -> str:
p = _printed_number(printed)
if p is not None and isinstance(value, (int, float)) and not isinstance(value, bool):
return f"{value:.{p[1]}f}"
return str(value)
def _same_text(a: object, b: str) -> bool:
return " ".join(str(a).split()) == " ".join(b.split())
def _mic_table_units(ref: XmlReport) -> str:
"""The unit a report's mic sample table is printed in. Its cells say so --
a mic dB value is never under 60, psi never over 1 -- where the event's
Units line need not: S353JTHU.DT0W prints dB under psi (2026-11-09)."""
if ref.sample_rows and "MicL" in ref.channels:
i, seen = ref.channels.index("MicL"), False
for row in ref.sample_rows:
p = _printed_number(row[i]) if len(row) == len(ref.channels) else None
if p is not None:
if abs(p[0]) > 1.0:
return "dB(L)"
seen = True
if seen:
return "psi(L)"
return ref.event_units or ""
def _mic_converter(ref: XmlReport, sfm: SfmSide) -> Optional[Callable[[int], float]]:
units = _mic_table_units(ref)
d = sfm.mic_divisor
if "dB(L)" in units:
return lambda c: mic_count_to_db(c / d)
if "psi(L)" in units:
return lambda c: c * _MIC_PSI_PER_COUNT / d
return None
_OVER_RANGE = {"TranPPV": "tran_over_range", "VertPPV": "vert_over_range",
"LongPPV": "long_over_range", "PeakVectorSum": "pvs_over_range",
"MicLPSPL": "mic_over_range"}
def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> FieldResult:
if not printed.strip() or printed.strip() == "N/A":
return FieldResult(tag, "no_reference", printed, None)
if tag in ("MicLPSPL", "MicTriggerLevel"):
# A printed value that states its unit is compared in that unit:
# K441LA17.IN0W's Units say psi(L), its MicTriggerLevel "125.0 dB(L)".
# Else the field's own <Units>, then the event's line: 7 DL2 reports
# print the mic peak in dB under a psi line, 3 the reverse (2026-11-09).
own = ref.units.get(tag) or ""
units = (printed if ("dB(L)" in printed or "psi(L)" in printed)
else own if ("dB(L)" in own or "psi(L)" in own) else (ref.event_units or ""))
key = (f"{tag} dB(L)" if "dB(L)" in units else
f"{tag} psi(L)" if "psi(L)" in units else None)
value = sfm.values.get(key) if key else None
else:
value = sfm.values.get(tag)
if value is None:
return FieldResult(tag, "sfm_blank", printed, None)
if printed.startswith(">"):
# ZC frequency above range: SFM agrees only by setting its flag.
ch = tag[:-len("ZCFreq")].lower()
flag = getattr(sfm.event.peak_values, ("mic" if ch == "micl" else ch) + "_zc_above_range", False)
return FieldResult(tag, "match" if flag else "mismatch", printed, str(value))
# Over range: SFM agrees with Blastware's OORANGE only by setting its flag,
# and a flag against a printed number is a disagreement.
over = _OVER_RANGE.get(tag)
flagged = bool(over and getattr(sfm.event.peak_values, over, False))
if printed == "OORANGE" or flagged:
ok = printed == "OORANGE" and flagged
return FieldResult(tag, "match" if ok else "mismatch", printed,
"OORANGE" if flagged else _render(value, printed))
if isinstance(value, (int, float)) and not isinstance(value, bool) and _printed_number(printed):
ok = matches_printed(float(value), printed)
else:
ok = _same_text(value, printed)
return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed))
def _cell_diff(value: object, printed: str) -> Optional[float]:
"""|value - printed| when the cell disagrees, else None; inf for a cell that
is not a number. A word on SFM's side (">100", "N/A") must be printed."""
if isinstance(value, str):
return None if _same_text(value, printed) else float("inf")
p = _printed_number(printed)
if p is None:
return float("inf")
d = abs(value - p[0])
return d if d > 0.5 * 10 ** -p[1] + 1e-9 else None
def _series_result(field: str, n_bw: int, n_sfm: int, diffs: list[tuple[int, float]],
row_len: int) -> FieldResult:
first = diffs[0][0] if diffs else None
max_abs = max((d for _, d in diffs), default=0.0)
ok = not diffs and not row_len
return FieldResult(
field, "match" if ok else "mismatch", f"{n_bw} rows", f"{n_sfm} values",
f"rows={n_bw} sfm={n_sfm} differing={len(diffs)} row_length_disagreements={row_len} "
f"first_diff={first} max_abs={max_abs:.4g}",
)
def _sample_converters(sfm: SfmSide, ref: XmlReport) -> dict[str, Callable[[int], float]]:
k = sfm.geo_ips_per_count
convert: dict[str, Callable[[int], float]] = {ch: (lambda c: c * k) for ch in _GEO}
mic = _mic_converter(ref, sfm)
if mic is not None:
convert["MicL"] = mic
return convert
def _interval_converter(title: str, sfm: SfmSide) -> Optional[Callable[[int], float]]:
"""SFM keeps each interval's peaks; it drops their frequencies and geo PVS."""
ch, _, rest = title.partition(" ")
# A peak past full scale is Blastware's OORANGE, in an interval as in the event.
if rest.startswith("Peak") and ch in _GEO:
return lambda c: "OORANGE" if over_full_scale(c, ch) else c * sfm.geo_ips_per_count
d = sfm.mic_divisor
if ch == "MicL" and rest == "Peak dB(L)":
return lambda c: "OORANGE" if over_full_scale(c, ch) else mic_count_to_db(c / d)
if ch == "MicL" and rest == "Peak psi(L)":
return lambda c: "OORANGE" if over_full_scale(c, ch) else c * _MIC_PSI_PER_COUNT / d
return None
def series_pairs(sfm: SfmSide, ref: XmlReport,
field: str) -> Optional[tuple[list[tuple[int, str, float]], int]]:
"""For a `samples.<ch>` or `intervals.<column>` field: the (index, printed
cell, SFM value) pairs and the count of row-length disagreements, or None
when SFM has no conversion or no data for it.
A waveform row holds only the channels still running, so row j's cells
pair, in order, with the reference channels SFM has more than j samples of;
a row whose cell count differs is a disagreement for every channel."""
if field.startswith("samples."):
ch = field[len("samples."):]
convert = _sample_converters(sfm, ref).get(ch)
counts = sfm.counts.get(ch, [])
if convert is None or not counts:
return None
rows = ref.sample_rows or []
lens = {c: len(sfm.counts.get(c, [])) for c in ref.channels}
pairs, row_len = [], 0
for j, row in enumerate(rows):
running = [c for c in ref.channels if lens[c] > j]
if len(running) != len(row):
row_len += 1
elif ch in running:
pairs.append((j, row[running.index(ch)], convert(counts[j])))
return pairs, row_len + max(0, len(counts) - len(rows))
if field.startswith("intervals."):
title = field[len("intervals."):]
columns = ref.interval_columns or []
if title not in columns:
return None
i = columns.index(title)
cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])]
values = sfm.interval_values.get(title)
if values is None:
convert = _interval_converter(title, sfm)
counts = sfm.counts.get(title.partition(" ")[0], [])
if convert is None or not counts:
return None
values = [convert(c) for c in counts]
pairs = [(j, cell, v) for j, (cell, v) in enumerate(zip(cells, values))]
return pairs, abs(len(cells) - len(values))
return None
def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> FieldResult:
got = series_pairs(sfm, ref, field)
if got is None:
return FieldResult(field, "sfm_blank", f"{n_bw} rows", None)
pairs, row_len = got
diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None]
title = field.split(".", 1)[1]
n_sfm = (len(sfm.interval_values[title]) if title in sfm.interval_values
else len(sfm.counts.get(title.partition(" ")[0], [])))
return _series_result(field, n_bw, n_sfm, diffs, row_len)
def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
"""One result per reference channel."""
n = len(ref.sample_rows or [])
return [_compare_series(f"samples.{ch}", n, sfm, ref) for ch in ref.channels]
def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
"""One result per column, plus the interval times."""
n = len(ref.intervals or [])
return ([_compare_interval_times(sfm, ref, n)]
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
def _compare_interval_times(sfm: SfmSide, ref: XmlReport, n: int) -> FieldResult:
if sfm.interval_times is None:
return FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)
diffs = [(j, float("inf")) for j, ((t, _), s) in enumerate(zip(ref.intervals or [], sfm.interval_times))
if not _same_text(s, t)]
return _series_result("intervals.Time", n, len(sfm.interval_times), diffs,
abs(n - len(sfm.interval_times)))
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]:
"""Every field Blastware's report carries, set against what SFM produced.
A mismatch a carve-out covers and applies to becomes `accepted`."""
out = [_compare_scalar(tag, text, sfm, ref)
for tag, text in ref.scalars.items() if tag not in _NOT_COMPARED]
ref_notes = [v for _, v in ref.notes]
if ref_notes and not sfm.notes:
out.append(FieldResult("notes", "sfm_blank", " | ".join(ref_notes), None))
else:
ok = [" ".join(v.split()) for v in ref_notes] == [" ".join(v.split()) for v in sfm.notes]
out.append(FieldResult("notes", "match" if ok else "mismatch",
" | ".join(ref_notes), " | ".join(sfm.notes)))
if ref.job_number is not None:
out.append(FieldResult("JobNumber", "sfm_blank", ref.job_number, None)
if sfm.job_number is None else
FieldResult("JobNumber", "match" if _same_text(sfm.job_number, ref.job_number)
else "mismatch", ref.job_number, sfm.job_number))
elif sfm.job_number is not None:
# SFM says the job number is shown; Blastware printed none.
out.append(FieldResult("JobNumber", "mismatch", None, sfm.job_number))
out.append(FieldResult("Channels", "match" if ref.channels == sfm.channels else "mismatch",
" ".join(ref.channels), " ".join(sfm.channels)))
if ref.sample_rows is not None:
out.extend(_compare_samples(sfm, ref))
if ref.intervals is not None:
out.extend(_compare_intervals(sfm, ref))
for r in out:
if r.verdict != "mismatch":
continue
for co in carveouts:
covered = any(r.field == f or (f.endswith(".") and r.field.startswith(f)) for f in co.fields)
if covered and co.applies(sfm, ref, r):
r.verdict, r.carveout = "accepted", co.id
break
return out
+206
View File
@@ -0,0 +1,206 @@
"""
minimateplus/decode_check_carveouts.py — the proven ways Blastware's report
differs from the instrument's data.
Every disagreement between SFM and Blastware is SFM's bug until shown otherwise.
A carve-out is that showing: the fields it covers, the rule it applies, and
evidence that does not rest on SFM's own output -- Blastware contradicting
itself, the instrument's own data, a third source, or Instantel documentation.
`compare` turns a covered mismatch into `accepted` only when the rule holds,
and every run counts the events each carve-out covers.
Pure: no I/O, and no import from `sfm/`.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable
from .bw_xml_report import XmlReport
from .decode_check import (FieldResult, SfmSide, _mic_table_units, _printed_number, series_pairs,
matches_printed)
from .event_file_io import _MIC_PSI_PER_COUNT
from .waveform_codec import mic_count_to_db
@dataclass(frozen=True)
class Carveout:
id: str
fields: tuple[str, ...] # exact names, or prefixes ending in "."
evidence: str
applies: Callable[[SfmSide, XmlReport, FieldResult], bool]
_TOL = 0.0006
def _at_ceiling(value: float, r: float) -> bool:
"""SFM's value sits at the range ceiling: a decoder unit or two past nominal
full scale is the clipped count itself (32016 = 10.005 in/s). An 8x
Sensitive-range value is far above the band and does not qualify."""
return r - _TOL <= abs(value) <= r * 1.01
def _clamped(printed: str, r: float) -> bool:
if printed.strip() == "OORANGE":
return True
p = _printed_number(printed)
return p is not None and abs(p[0]) >= r - _TOL
def _differs(v: object, cell: str) -> bool:
"""A cell SFM disagrees with. SFM's own word (its OORANGE, since
2026-11-09) agrees only when Blastware printed the same word."""
if isinstance(v, str):
return " ".join(v.split()) != " ".join(cell.split())
return not matches_printed(v, cell)
def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
try:
r = float(ref.scalars["GeoRange"])
except (KeyError, ValueError):
return False
if res.field in ("TranPPV", "VertPPV", "LongPPV"):
v = sfm.values.get(res.field)
return v is not None and _clamped(res.bw or "", r) and _at_ceiling(float(v), r)
if res.field == "PeakVectorSum":
# A vector sum can exceed the range without any clipping, so only
# Blastware's OORANGE counts. SFM's sum is bounded by three channels at
# the ceiling (11.55 on T438HGTZ.B30W), and a channel Blastware itself
# clamped must be the one SFM has at the ceiling -- an unclipped channel
# read 8x high on the Sensitive range does not qualify.
pvs = sfm.values.get("PeakVectorSum")
return ((res.bw or "").strip() == "OORANGE" and pvs is not None
and r - _TOL <= float(pvs) <= 3 ** 0.5 * r * 1.01
and any(_clamped(ref.scalars.get(f, ""), r) and sfm.values.get(f) is not None
and _at_ceiling(float(sfm.values[f]), r)
for f in ("TranPPV", "VertPPV", "LongPPV")))
got = series_pairs(sfm, ref, res.field)
if got is None or got[1]:
return False
if res.field == "intervals.Geo PVS in/s":
# Per interval, as PeakVectorSum: an OORANGE vector sum, SFM's sum within
# three channels at the ceiling, and a channel Blastware itself clamped in
# that interval. 17 / 17 DL2 cells, SFM 10.01 .. 17.33 (2026-11-03).
cols = ref.interval_columns or []
peaks = [cols.index(c) for c in ("Tran Peak in/s", "Vert Peak in/s", "Long Peak in/s")
if c in cols]
rows = ref.intervals or []
differing = [(j, cell, v) for j, cell, v in got[0] if _differs(v, cell)]
return bool(differing) and all(
cell.strip() == "OORANGE" and not isinstance(v, str)
and r - _TOL <= v <= 3 ** 0.5 * r * 1.01
and any(_clamped(rows[j][1][p], r) for p in peaks if p < len(rows[j][1]))
for j, cell, v in differing)
differing = [(cell, v) for _, cell, v in got[0] if _differs(v, cell)]
return bool(differing) and all(
not isinstance(v, str) and _clamped(cell, r) and _at_ceiling(v, r)
and (cell.strip() == "OORANGE" or (v >= 0) == (_printed_number(cell)[0] >= 0))
for cell, v in differing)
SATURATION = Carveout(
id="saturation",
fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
"samples.Tran", "samples.Vert", "samples.Long",
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s",
"intervals.Geo PVS in/s"),
evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; "
"the file holds counts past full scale (32016 counts = 10.005 in/s observed). "
"scratch/verify_against_ascii.py, 2026-08-28. An interval's vector sum prints "
"OORANGE when it exceeds the range in an interval with a clamped channel: 17 / 17 "
"DL2 cells, 2026-11-03."),
applies=_saturation,
)
def _interval_count_is_duration(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
"""Blastware's count exceeds the intervals in its own table, and SFM decoded
exactly the table's."""
p = _printed_number(res.bw or "")
n = sfm.values.get("NumberofIntervals")
rows = len(ref.intervals or [])
return p is not None and n is not None and rows == n and p[0] > n
INTERVAL_COUNT_IS_DURATION = Carveout(
id="interval-count-is-duration",
fields=("NumberofIntervals",),
evidence=("Blastware's Number of Intervals is (stop - start) / interval from the file's "
"footer times -- exact on T193KSWP.FF0H (2,880), M462KSWR.1R0H (1,650) and "
"T193KY0A.740H (6,390). Its own interval table lists the intervals the file "
"holds: one block (30 at 2 s) fewer when the unit never wrote the last minute. "
"2026-11-02."),
applies=_interval_count_is_duration,
)
_MIC_UNITS = ("in/s and dB(L)", "in/s and psi(L)")
def _units_is_a_display_preference(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
"""Both sides say the event has a mic; they differ only in dB against psi."""
return (" ".join((res.bw or "").split()) in _MIC_UNITS
and sfm.values.get("Units") in _MIC_UNITS)
UNITS_IS_A_DISPLAY_PREFERENCE = Carveout(
id="units-is-a-display-preference",
fields=("Units",),
evidence=("dB(L) or psi(L) is Blastware's display preference on the PC when it wrote the "
"report, not the unit's: in report-write order (the _XML.XML mtimes) DL2's 70,034 "
"reports switch fleet-wide in 61 clean runs, every unit at once, and no byte or "
"bit of the event file separates the two (k-240 .. k+520, nor the 1.2 KB before "
"the footer). Instantel documents both settings: the unit's own Microphone "
"Units (MiniMate Plus manual 716U0101 Rev 15 §3.9.7: psi(L), dB(L) or Pa(L), "
"keypad Right Arrow + Setups) and Blastware's report preference (Blastware "
"manual 714U0301 Rev 22 §4, Preferences > Units and Channel: Show Mic in dB / "
"in Linear Units). 2026-11-03."),
applies=_units_is_a_display_preference,
)
def _other_mic_unit(sfm: SfmSide, units: str):
"""SFM's mic value in the unit the report did NOT say, as Blastware renders it."""
d = sfm.mic_divisor
if "dB(L)" in units:
return lambda c: c * _MIC_PSI_PER_COUNT / d
if "psi(L)" in units:
return lambda c: mic_count_to_db(c / d)
return None
def _mic_units_mixed(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
"""Every mic cell SFM disagrees with is SFM's own value in the other unit."""
counts = sfm.counts.get("MicL") or []
if res.field == "MicLPSPL":
own = ref.units.get("MicLPSPL") or ""
alt = _other_mic_unit(sfm, own if ("dB(L)" in own or "psi(L)" in own) else (ref.event_units or ""))
peak = max((abs(c) for c in counts), default=None)
return alt is not None and peak is not None and not _differs(alt(peak), res.bw or "")
got = series_pairs(sfm, ref, res.field)
# An interval column names its own unit; a sample table says it in its cells.
units = res.field if res.field.startswith("intervals.") else _mic_table_units(ref)
alt = _other_mic_unit(sfm, units)
if got is None or got[1] or alt is None:
return False
differing = [(j, cell) for j, cell, v in got[0] if _differs(v, cell)]
return bool(differing) and all(j < len(counts) and not _differs(alt(counts[j]), cell)
for j, cell in differing)
MIC_UNITS_MIXED = Carveout(
id="mic-units-mixed",
fields=("MicLPSPL", "samples.MicL", "intervals.MicL Peak psi(L)", "intervals.MicL Peak dB(L)"),
evidence=("Blastware's dB(L) / psi(L) labels do not hold for the mic on every report: 7 DL2 "
"reports print the mic peak in dB under a psi line, 3 the reverse, and some mix the "
"two inside one column -- K441L9IN.OT0W prints psi '0.000' / '-0.000' for counts of 1 "
"to 3 in a dB table, S353JTHU.DT0W psi rows then dB rows. On 19 DL2 events (14 "
"sample tables, 5 peaks) every mic cell SFM disagrees with is SFM's own value in the "
"other unit; a cell matching neither is still a mismatch. A histogram row can print "
"one unit in both its mic columns: I145HKWT.DY0H row 672 reads 95.92 under psi(L) "
"and dB(L) (count 5, dB), S353K894.OE0H rows 106 and 608 0.000 under both (count 2, "
"psi). 2026-11-09."),
applies=_mic_units_mixed,
)
CARVEOUTS: tuple[Carveout, ...] = (SATURATION, INTERVAL_COUNT_IS_DURATION,
UNITS_IS_A_DISPLAY_PREFERENCE, MIC_UNITS_MIXED)
File diff suppressed because it is too large. Load diff
+24 -277
View File
@@ -124,118 +124,17 @@ def build_5a_request(address: int, length: int) -> bytes:
crossing a 64 KB page): a 5A request is an ORDINARY 16-byte request --
`[10 00 5A 00][length BE][address BE 4][zeros 6]`, SUM8 checksum, every
02/03/04/10 escaped -- and this rebuilds all 540 of Blastware's 5A requests
byte for byte. The older model below (`build_5a_frame`: a raw "offset_hi
0x10", an "11-byte params", "metadata pages at 0x1002 / 0x1004") was the
same bytes misread: `10 02 00` is the length 0x0200 escaped, and the
"metadata pages" are the first event's chunks at 0x0200 and 0x0400.
byte for byte. The older model (`build_5a_frame` and the
`bulk_waveform_*` helpers, removed 2026-11-20: a raw "offset_hi 0x10", an
"11-byte params", "metadata pages at 0x1002 / 0x1004") was the same bytes
misread: `10 02 00` is the length 0x0200 escaped, and the "metadata pages"
are the first event's chunks at 0x0200 and 0x0400.
"""
if not 0 <= address <= 0xFFFFFFFF:
raise ValueError(f"address must fit in 32 bits, got {address:#x}")
return build_bw_frame(SUB_5A, length, address.to_bytes(4, "big") + bytes(6))
def build_5a_frame(offset_word: int, raw_params: bytes) -> bytes:
"""
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` -- no production caller. Kept
because tests/test_5a_protocol.py pins its bytes against the 5-1-26 captures;
for in-page requests it emits the same bytes. Its model (below) is retracted.
Build a BW→S3 frame for SUB 5A (BULK_WAVEFORM_STREAM) that exactly
matches Blastware's wire output.
SUB 5A uses a DIFFERENT frame format from all other read commands:
1. The offset field (bytes [4:6]) is written RAW — the 0x10 in
offset_hi=0x10 is NOT DLE-stuffed, unlike build_bw_frame().
2. The checksum uses a DLE-aware sum: for each 0x10 XX pair in the
stuffed section, only XX contributes; lone bytes contribute normally.
This differs from the standard SUM8 checksum on the unstuffed payload.
Both differences are confirmed from the 1-2-26 BW TX capture (all 10 frames
verified against this algorithm on 2026-04-02).
Args:
offset_word: 16-bit offset. For probe/chunks/metadata pages this is
`0x1002`. For the proper TERM frame this is computed by
`bulk_waveform_term_v2()` from the STRT-derived
`end_offset`.
raw_params: 10, 11, or 12 params bytes (from `bulk_waveform_params`
for probes/samples, `bulk_waveform_term_v2` for TERM, or
a manually-built 12-byte block for the metadata pages
0x1002 / 0x1004). See gotcha #3 below — params region
uses partial DLE stuffing of 0x10 bytes.
Returns:
Complete frame bytes: [ACK][STX][stuffed_section][chk][ETX]
"""
if len(raw_params) not in (10, 11, 12):
# 10 = termination params; 11 = regular probe / chunk params;
# 12 = metadata-page params (extra trailing 0x00 — BW byte-perfect quirk
# for the two fixed metadata reads at counter=0x1002 and 0x1004).
raise ValueError(f"raw_params must be 10/11/12 bytes, got {len(raw_params)}")
# Build stuffed section between STX and checksum
s = bytearray()
s += b"\x10\x10" # DLE-stuffed BW_CMD
s += b"\x00" # flags
s += bytes([SUB_5A]) # sub = 0x5A
s += b"\x00" # field3
s += bytes([(offset_word >> 8) & 0xFF, # offset_hi — raw, NOT stuffed
offset_word & 0xFF]) # offset_lo
# Params — partial DLE stuffing of 0x10 bytes (CONFIRMED 2026-05-05).
#
# The device's de-stuffing rule for params is:
# • `10 10` → de-stuffs to `10`
# • `10 02/03/04` → kept literal (these are inner-frame markers)
# • `10 X` other → de-stuffs to just `X` (drops the 0x10)
#
# So for any 0x10 byte in the *logical* params that is followed by a
# byte NOT in {0x02, 0x03, 0x04, 0x10}, we must double the 0x10 on the
# wire (`10 X` → `10 10 X`) so the device's de-stuffer reproduces the
# original `10 X` pair. Without this, counter values with `0x10` in
# the high byte (e.g. counter=0x1000 has params bytes `10 00`) are
# silently corrupted to `0x__00` on the device side, and the device
# responds for the wrong address — for counter=0x1000 it returns the
# probe response (counter=0x0000), which contains the file header +
# STRT. That STRT block then lands in the assembled file body and
# Blastware rejects the file as malformed.
#
# Confirmed against BW capture 5-1-26 / bwcap3sec frame 20: params
# logical bytes `00 01 11 10 00 00 00 00 00 00 00` (counter=0x1000)
# are encoded on the wire as `00 01 11 10 10 00 00 00 00 00 00 00`.
# BW frames 13/14 (meta @ 0x1002 / 0x1004) leave `10 02` and `10 04`
# raw — the device handles those literal pairs correctly.
i = 0
while i < len(raw_params):
b = raw_params[i]
s.append(b)
if (
b == 0x10
and i + 1 < len(raw_params)
and raw_params[i + 1] not in (0x02, 0x03, 0x04, 0x10)
):
s.append(0x10) # double the 0x10 so it survives device de-stuffing
i += 1
# DLE-aware checksum: for 0x10 XX pairs count XX; for lone bytes count them
chk, i = 0, 0
while i < len(s):
if s[i] == DLE and i + 1 < len(s):
chk = (chk + s[i + 1]) & 0xFF
i += 2
else:
chk = (chk + s[i]) & 0xFF
i += 1
# A checksum that is itself a framing byte is DLE-escaped. Sent bare, a
# 0x02 before ETX reads as a new STX: BE9441 never answered chunk 0x7D06
# (`... 02 03`) and rebooted ~11 s later, twice; escaped (`10 02 03`) it
# answered in 28 ms, as did checksums 0x04 and 0x10 (bench, 2026-10-26).
# The set is a Micromate's escape set (251/251 THOR requests); the MiniMate's
# de-stuffing keeps `10 02/03/04` literal and turns `10 10` into 0x10.
tail = bytes([DLE, chk]) if chk in (STX, ETX, 0x04, DLE) else bytes([chk])
return bytes([ACK, STX]) + bytes(s) + tail + bytes([ETX])
def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> bytes:
"""
Build a BW→S3 read-command frame.
@@ -368,164 +267,6 @@ def token_params(token: int = 0) -> bytes:
return bytes(p)
def bulk_waveform_params(key4: bytes, counter: int, *, is_probe: bool = False) -> bytes:
"""
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` / `parse_strt_end_key` -- no
production caller; kept for tests/test_5a_protocol.py. See build_5a_request.
Build the 10-byte params block for SUB 5A (BULK_WAVEFORM_STREAM) requests.
Confirmed 2026-04-02 from 1-2-26 BW TX capture analysis:
Probe / first request (is_probe=True, counter=0):
params[0] = 0x00
params[1:5] = key4 (all 4 key bytes; counter overlaps key4[2:4] = 0x0000)
params[5:] = zeros
Regular chunk requests (is_probe=False):
params[0] = 0x00
params[1:3] = key4[0:2] (first 2 key bytes as session handle)
params[3:5] = counter (BE uint16) (chunk position, increments by 0x0400)
params[5:] = zeros
Termination request: DO NOT use this helper — see bulk_waveform_term_params().
Args:
key4: 4-byte waveform key from EVENT_HEADER (1E) response.
counter: Chunk position counter (uint16 BE). Pass 0 for probe.
is_probe: If True, embed full key4 (probe step only).
Returns:
11-byte params block. (BW confirmed: chunk frames carry 11 params bytes,
not 10; the extra trailing 0x00 was confirmed from 1-2-26 wire capture
on 2026-04-02.)
"""
if len(key4) != 4:
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
p = bytearray(11) # 11 bytes confirmed from BW wire capture
p[0] = 0x00
p[1] = key4[0]
p[2] = key4[1]
if is_probe:
# Full key4; counter=0 is implied (overlaps with key4[2:4] which must be 0x0000)
p[3] = key4[2]
p[4] = key4[3]
else:
p[3] = (counter >> 8) & 0xFF
p[4] = counter & 0xFF
return bytes(p)
def bulk_waveform_term_params(key4: bytes, counter: int) -> bytes:
"""
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` / `parse_strt_end_key` -- no
production caller; kept for tests/test_5a_protocol.py. See build_5a_request.
⛔ DEPRECATED — DO NOT USE IN NEW CODE.
This is the v1 termination params helper, paired with the broken
`_BULK_TERM_OFFSET = 0x005A` magic offset_word. Together they produce a
~100-byte device-side terminator response that does NOT contain the
partial-last-chunk waveform tail or the 26-byte file footer. Files
reconstructed using this terminator are missing their last ~512 bytes of
waveform data and have a synthesized footer that disagrees with what BW
would have written.
**For new code, use `bulk_waveform_term_v2(key4, end_offset, last_chunk_counter)`**
which computes the correct offset_word + params from the STRT-derived
`end_offset`. v2 produces wire bytes that match BW exactly across all
tested events (4-27-26 / 5-1-26 / 5-4-26 captures).
This function is retained ONLY for the defensive fallback path in
`read_bulk_waveform_stream()` that triggers when STRT parsing fails or no
chunks are fetched (= a malformed event or an unexpected device state).
The fallback already logs a WARNING when it activates; if you see that
warning, the bug is upstream — STRT should have been parseable.
"""
if len(key4) != 4:
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
p = bytearray(10)
p[0] = key4[0]
p[1] = key4[1]
p[2] = (counter >> 8) & 0xFF
return bytes(p)
def bulk_waveform_term_v2(
key4: bytes,
end_offset: int,
last_chunk_counter: int,
) -> tuple[int, bytes]:
"""
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` / `parse_strt_end_key` -- no
production caller; kept for tests/test_5a_protocol.py. See build_5a_request.
Compute the SUB 5A TERM frame's offset_word and 10-byte params block.
Confirmed across 3 events (4-27-26 + 5-1-26 captures):
next_boundary = last_chunk_counter + 0x0200
offset_word = end_offset - next_boundary (residual byte count)
params[0] = key4[0] (= 0x01 on every observed device)
params[1] = key4[1] (= 0x11)
params[2] = (next_boundary >> 8) & 0xFF
params[3] = next_boundary & 0xFF
params[4:10] = zeros
Verification:
| end_offset | last_chunk | next_boundary | offset_word | params[2:4] |
| 0x1ABE | 0x1800 | 0x1A00 | 0x00BE | 1A 00 |
| 0x21F2 | 0x1E00 | 0x2000 | 0x01F2 | 20 00 |
| 0x417E | 0x3E38 | 0x4038 | 0x0146 | 40 38 |
The device receives `requested_address = (params[2] << 8) | offset_word`
and replies with `(end_offset - next_boundary)` bytes of waveform tail
starting at `next_boundary` — including the 26-byte file footer.
Args:
key4: 4-byte waveform key for this event.
end_offset: Event-end pointer (= `(end_key[2] << 8) | end_key[3]`
from the STRT record at data[23:27] of A5[0]).
last_chunk_counter: Counter of the last full 0x0200-byte chunk fetched
(the chunk that covers [last_chunk_counter,
last_chunk_counter + 0x0200)).
Returns:
(offset_word, params10) tuple. Pass as
`build_5a_frame(offset_word, params)`.
Raises:
ValueError: on inconsistent inputs.
"""
if len(key4) != 4:
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
next_boundary = last_chunk_counter + 0x0200
if next_boundary > 0xFFFF:
raise ValueError(
f"next_boundary 0x{next_boundary:04X} exceeds uint16; check inputs"
)
if end_offset <= last_chunk_counter:
raise ValueError(
f"end_offset 0x{end_offset:04X} must be > "
f"last_chunk_counter 0x{last_chunk_counter:04X}"
)
offset_word = end_offset - next_boundary
if offset_word < 0:
# Last chunk overshot end_offset; caller should have stopped one chunk
# earlier. Treat as zero residual.
offset_word = 0
if offset_word > 0xFFFF:
raise ValueError(
f"offset_word 0x{offset_word:04X} exceeds uint16"
)
p = bytearray(10)
p[0] = key4[0]
p[1] = key4[1]
p[2] = (next_boundary >> 8) & 0xFF
p[3] = next_boundary & 0xFF
return offset_word, bytes(p)
# ── End-offset extraction from STRT record ────────────────────────────────────
STRT_MARKER = b"STRT"
@@ -534,11 +275,13 @@ STRT_MARKER = b"STRT"
def unescape_reply(data: bytes) -> bytes:
"""A reply's data with each kept escape removed: `10 02/03/04` → `02/03/04`.
The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do
(748/748 replies, 2026-10-26). S3FrameParser collapses `10 10` but keeps the
`10` of `10 02/03/04` (inner-frame markers to it), so its `.data` carries an
extra byte before each 02/03/04 value -- harmless for fields read before the
escape, one byte off for any read after it, or counted from the end."""
The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do,
the checksum included (748/748 replies, 2026-10-26; 7,747 / 7,747 across every
recording, March to October 2026, #58). S3FrameParser collapses `10 10` but
keeps the `10` of `10 02/03/04` (inner-frame markers to it) everywhere but the
checksum, so its `.data` carries an extra byte before each 02/03/04 value --
harmless for fields read before the escape, one byte off for any read after it,
or counted from the end."""
out, i = bytearray(), 0
while i < len(data):
if data[i] == DLE and i + 1 < len(data) and data[i + 1] in (STX, ETX, 0x04):
@@ -565,7 +308,8 @@ def parse_strt_end_offset(a5_data: bytes) -> Optional[int]:
"""
⛔ SUPERSEDED 2026-10-26 by `parse_strt_end_key`: this keeps only the low 16
bits (the 64 KB page bug) and misreads an end whose low bytes hold an escaped
02/03/04. No production caller; kept for tests/test_5a_protocol.py.
02/03/04. No production caller; tests/test_5a_blastware_walk.py keeps it
to show that misread.
Extract the event-end offset from the STRT record in an A5 response payload.
@@ -632,11 +376,8 @@ class S3Frame:
page_lo: int # PAGE_LO from header
data: bytes # payload data section (payload[5:], checksum already stripped)
checksum_valid: bool
chk_byte: int = 0 # actual checksum byte received from wire (body[-1])
# needed for waveform file reconstruction: when the last data byte
# is 0x10 and chk_byte ∈ {0x02, 0x03, 0x04}, the DLE+chk pair
# must be included in the DLE-strip operation to correctly
# reconstruct the Blastware binary body.
chk_byte: int = 0 # actual checksum byte received from wire (body[-1]); an
# escaped one (`10 02/03/04`) leaves no 10 in `data` (#58)
@property
def page_key(self) -> int:
@@ -759,9 +500,15 @@ class S3FrameParser:
if len(body) < 6:
return None
raw_payload = body[:-1] # everything except the trailing checksum byte
# A checksum of 02, 03 or 04 arrives escaped, `10 X`, and _step keeps both
# bytes; that 10 is the escape, never data (#58: 272 of 7,747 recorded
# replies, every one an escape pair). Any other checksum is one byte.
n_chk = 2 if body[-2] == DLE and body[-1] in (STX, ETX, 0x04) else 1
raw_payload = body[:-n_chk] # everything except the checksum
chk_received = body[-1]
chk_computed = checksum(raw_payload)
# SUM8 of the payload unescaped: the kept `10` of a `10 02/03/04` is not
# summed (7,747 of 7,747 recorded replies check this way).
chk_computed = checksum(unescape_reply(raw_payload))
if len(raw_payload) < 5:
return None
+243 -145
View File
@@ -40,6 +40,13 @@ iterate 32-stride and stop before the tail.
[24:28] 4-byte variable purpose unknown (possibly CRC or timestamp delta)
[28:32] block-end signature see "Two block tails" below
⚠ CORRECTED 2026-10-30 (measured): [21:25] is the interval's peak vector sum
SQUARED, uint32 BE in 0.005 in/s units. sqrt([21:25]) x 0.005 is the "Geo PVS"
Blastware prints for the interval, on 1,668,073 / 1,668,074 standard DL2
intervals checked against the _XML.XML reports. [21:23] is zero only while the
square is below 65,536 (PVS < 1.28 in/s), which is why it looked constant; only
[25:28] is still unexplained. `interval_pvs` reads it.
**Every per-channel field is uint16 BIG-endian** (confirmed 2026-08-25).
Only ``block_ctr`` at [2:4] is little-endian.
@@ -124,6 +131,7 @@ record list.
from __future__ import annotations
import math
import struct
from typing import List, Optional, Tuple
@@ -148,10 +156,11 @@ _BLOCK_MARKER = 10
# 16-count-unit output (1 unit = 0.005 in/s = 16 ADC counts).
_GEO_LSB_INS = 0.005
# Frequency formula: freq_Hz = _FREQ_NUMERATOR / half_period_samples.
# Empirically determined to be 512 (= sample_rate / 2, where sample rate
# is 1024 sps for the standard MiniMate Plus configuration).
_FREQ_NUMERATOR = 512
# Frequency formula: freq_Hz = (sample_rate / 2) / half_period_samples.
# ⚠ RETRACTED 2026-11-03 (#50): "a fixed numerator of 512". 512 is sample_rate
# / 2 at 1024 sps only; at 2048 sps it halved every frequency. Measured on DL2:
# 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048.
_FREQ_NUMERATOR = 512 # sample_rate / 2 at the default 1024 sps
def _is_data_block(block: bytes) -> bool:
@@ -216,6 +225,7 @@ def _decode_block(block: bytes) -> Optional[dict]:
"m_peak": m_peak,
"m_halfp": m_halfp,
"meta_var": var_meta,
"pvs_sq": int.from_bytes(block[21:25], "big"),
"is_terminal": block[28:32] == _BLOCK_TAIL_TERMINAL,
}
@@ -255,18 +265,25 @@ def walk_body(body: bytes) -> List[dict]:
def _walk_auto(body: bytes) -> List[dict]:
"""Pick the block model by signature strength, not by which returns first.
The multi-interval variant announces itself with consecutive block headers
at an exact ``12 + 20*n`` stride — far stronger evidence than a handful of
scattered standard-tail blocks, which a multi-interval body will also yield
by coincidence. Dispatching on "whichever decoder returns something"
handed 193 BE18193 files to the standard walker and produced peaks of
149 in/s against a 10 in/s full scale.
A multi-interval body announces itself with consecutive block headers at an
exact ``12 + record * n`` stride -- far stronger evidence than a handful of
scattered standard-tail blocks, which it will also yield by coincidence.
Dispatching on "whichever decoder returns something" handed 193 BE18193
files to the standard walker and produced peaks of 149 in/s against a
10 in/s full scale. A single short block (under a minute of intervals) has
no second header; it is tried after the standard walker, which a one-block
standard body satisfies with the same values.
"""
if detect_multi_interval_stride(body):
layout = detect_multi_interval_layout(body)
if layout and (_is_multi_header(body, _stride(*layout))
or layout[0] == 16):
recs = walk_multi_interval_blocks(body)
if recs:
return recs
return walk_body(body)
recs = walk_body(body)
if recs:
return recs
return walk_multi_interval_blocks(body) if layout else []
def decode_histogram_body(body: bytes) -> Optional[dict]:
@@ -284,14 +301,20 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
to get 1-count ADC values, then ``count / 32767 * 10.0`` for in/s)
- Mic channel: use ``waveform_codec.mic_count_to_db(count)``
"""
records = _walk_auto(body)
return channels_from_records(_walk_auto(body))
def channels_from_records(records: Optional[List[dict]]) -> Optional[dict]:
"""``decode_histogram_body``'s per-channel peaks, from records already walked."""
if not records:
return None
return {
"Tran": [r["t_peak"] for r in records],
"Vert": [r["v_peak"] for r in records],
"Long": [r["l_peak"] for r in records],
"MicL": [r["m_peak"] for r in records],
# A mic-off histogram has no mic channel: an empty list, as a mic-off
# waveform's decode gives.
"MicL": [r["m_peak"] for r in records if r["m_peak"] is not None],
}
@@ -310,17 +333,29 @@ def decode_histogram_body_full(body: bytes) -> Optional[List[dict]]:
return records if records else None
def half_period_to_hz(halfp: int) -> Optional[float]:
"""Convert a half-period in samples to frequency in Hz.
def interval_pvs(body: bytes) -> Optional[List[float]]:
"""Each interval's peak vector sum, in the geo peak units (0.005 in/s at
Normal range): the square root of the square the device stores with every
interval. This is the vector sum at an instant, as Blastware prints it --
not the magnitude of the three channel peaks, which can come from
different moments. None when the body has no valid blocks."""
records = _walk_auto(body)
return [math.sqrt(r["pvs_sq"]) for r in records] if records else None
def half_period_to_hz(halfp: int, sample_rate: int = 1024) -> Optional[float]:
"""Convert a half-period in samples to frequency in Hz:
``(sample_rate / 2) / halfp``.
Returns ``None`` for half-period ≤ 5 — the device emits values in
that range when the measured zero-crossing rate exceeds 100 Hz
(the BW display reports `>100 Hz` for such cases). Callers can
treat ``None`` as the `>100 Hz` sentinel.
that range when the measured zero-crossing rate exceeds 100 Hz at
1024 sps (the BW display reports `>100`, `>200` at 2048 sps). Callers
can treat ``None`` as that sentinel. A half-period of 0 is Blastware's
"N/A"; it also returns None.
"""
if halfp <= 5:
return None
return _FREQ_NUMERATOR / halfp
return (sample_rate / 2) / halfp
def geo_count_to_ins(count: int) -> float:
@@ -328,160 +363,223 @@ def geo_count_to_ins(count: int) -> float:
return count * _GEO_LSB_INS
# ── Multi-interval block variant (CONFIRMED 2026-08-26) ─────────────────────
# ── Multi-interval blocks (CONFIRMED 2026-08-26; re-read 2026-10-26) ─────────
#
# When the histogram interval is SHORTER than one minute, the device packs
# several intervals into a single block so that every block still covers
# exactly one minute of data:
# When the histogram interval is SHORTER than one minute, the device packs one
# minute of intervals into each block:
#
# interval size intervals/block stride
# 1 minute 1 32 <- the standard block above
# 15 seconds 4 92
# 2 seconds 30 612
# interval per block stride, mic on (20 B records) mic off (16 B)
# 1 minute 1 32 <- the standard block above 28 (inferred)
# 15 s 4 92 76 (inferred)
# 2 s 30 612 492 (inferred)
#
# stride = 12 + n_intervals * 20
# stride = 12 + per_block * record, record = 4 * channels + 4
#
# Block layout:
# Block layout (measured 2026-10-26, issues #47 and #49):
# [0] 0x00
# [1] segment_id (256 blocks per segment, same as the standard block)
# [2:4] block_ctr uint16 LE (0x0100.., resets each segment)
# [4] 0x0a marker
# [5] 0x00
# [6 ...] n x 20-byte interval records, each carrying 8 x uint16
# LITTLE-endian values:
# T_peak, T_halfperiod, V_peak, V_halfperiod,
# L_peak, L_halfperiod, M_peak, M_halfperiod
# then 2 more words; the first is 0x0000 on every real interval.
# [-6:] 6-byte block trailer
# [1] segment_id (256 blocks per segment, as in the standard block)
# [2:4] block_ctr uint16 LE
# [4] 0x0a
# [5 ...] one record per interval: per channel a BIG-endian uint16 peak and
# half-period (Tran, Vert, Long[, MicL]), then 0x0000, then one more
# word ("meta_var" keeps those 4 bytes). Measured 2026-10-30: those
# 4 bytes are the interval's peak vector sum SQUARED, uint32 BE in
# 0.005 in/s units -- sqrt matches Blastware's "Geo PVS" on 34.5 M
# DL2 sub-minute intervals; the 0x0000 is its high word
# [-7:] trailer: 3 bytes, then the 4-byte tail -- 9c 06 00 42 on the
# stream's LAST block
#
# ⚠ ENDIANNESS: the standard 32-byte block is BIG-endian. This variant is
# LITTLE-endian. Do not share the accessor.
# The last block is SHORT, not padded: it holds only the intervals recorded and
# ends on 9c 06 00 42 (K440L3AQ.T70H: 1,427 x 4 + 2 = 5,710, Blastware's count;
# T193L0XM.CI0H: 30 + 21 = 51). Reading it at full stride ran into the setup
# data that follows, which is what the old "garbage slot" trimming cleaned up;
# that trimming survives only as the fallback for a stream with no 9c 06 00 42.
#
# These files previously decoded to nothing at all — 415 of them in the
# production snapshot, 216 on BE18193 (2 s intervals) and 199 on BE9440
# (15 s). Before that they were being accepted by the WAVEFORM codec, which
# returned garbage peaking up to 400x the device-reported PPV.
# ⚠ RETRACTED 2026-10-26: "8 x uint16 LITTLE-endian from byte 6, a 6-byte
# header with [5] == 0". That is the same bytes shifted by one: identical while
# every high byte is zero, which is why it matched Blastware on 10,715,314 of the
# 770 archive files' intervals -- and wrong on the 1 that was not (K440KZP4.560H
# #4764: a Long half-period of 1 read as 257, ">100 Hz" read as ~2 Hz). And
# byte 5 is the first record's Tran peak high byte, so a block whose first
# interval exceeded 1.275 in/s ended the old walk.
#
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
# against its Blastware ASCII export with 17,130/17,130 geo peak counts,
# 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) values matching exactly.
# Mic off (#47): BE9441's K441LTOK.QZ0 (2 s, 22 intervals, one short block)
# matches its Blastware export on 66/66 peaks and 66/66 frequencies. The mic-off
# strides above follow from the same layout; only the 2 s short block is
# measured.
#
# Ground truth, mic on: BE9440/K440L3AQ.T70H (15 s, 5,710 intervals) --
# 17,130 / 22,840 / 5,710 geo peaks, frequencies and mic dB(L), all exact.
_MULTI_HEADER_LEN = 6
_MULTI_RECORD_LEN = 20
_MULTI_TRAILER_LEN = 6
# At least 2 records: a 1-record block would have stride 12 + 20 = 32, which
# collides with the standard big-endian block and mis-decodes it.
_MULTI_MIN_RECORDS = 2
_MULTI_MAX_RECORDS = 64
_MULTI_HEADER_LEN = 5
_MULTI_TRAILER_LEN = 7
_MULTI_MAX_RECORDS = 64
_RECORD_LENS = (20, 16) # mic on (4 channels), mic off (3 channels)
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. A peak above
# this is physically impossible and marks buffer garbage in a partial block.
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. Used only by
# the fallback trim of a stream with no terminal tail.
_GEO_MAX_COUNTS = 2000
def _is_multi_header(body: bytes, off: int) -> bool:
return (off + _MULTI_HEADER_LEN <= len(body)
and body[off] == 0x00
and body[off + 4] == 0x0A
and body[off + 5] == 0x00)
and body[off + 4] == 0x0A)
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None.
def _ctr(body: bytes, off: int) -> int:
return body[off + 2] | (body[off + 3] << 8)
Found by locating the second block header; validated against
``stride = 12 + n * 20`` and confirmed on a third block where present.
def _follows(body: bytes, off: int, nxt: int) -> bool:
"""A block header at ``nxt`` that continues the block at ``off``: block_ctr
one higher, or -- every 256 blocks -- the next segment (block_ctr restarts)."""
if not _is_multi_header(body, nxt):
return False
if body[nxt + 1] == body[off + 1]:
return (_ctr(body, nxt) - _ctr(body, off)) & 0xFFFF == 1
return body[nxt + 1] == (body[off + 1] + 1) & 0xFF
def _stride(rec: int, n: int) -> int:
return _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + rec * n
def _records_plausible(body: bytes, off: int, rec: int, m: int) -> bool:
"""Every record's last 4 bytes are its vector sum squared, consistent with
its channel peaks: at least the largest peak, at most sqrt(3) times it (one
unit of rounding either way). That is what tells a 16-byte layout from a
20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24);
misread, those bytes are other fields. Holds on 34,502,955 / 34,502,955 DL2
sub-minute intervals (2026-11-02).
⚠ RETRACTED 2026-11-02: "every record's zero word is 0000". It is the high
word of the PVS², non-zero on any interval above 1.28 in/s, so a short
histogram with one loud interval was not recognised at all (T193KR5M.X90H,
K440HA3C.JM0H decoded to nothing)."""
z = rec - 4
for k in range(m):
q = off + _MULTI_HEADER_LEN + rec * k
if q + rec > len(body):
return False
peak = max((body[q + i] << 8) | body[q + i + 1] for i in (0, 4, 8))
if not _pvs_consistent(peak, int.from_bytes(body[q + z:q + z + 4], "big")):
return False
return True
def _pvs_consistent(peak: int, pvs_sq: int) -> bool:
"""A record's vector sum squared against its largest geo peak, one unit of
rounding either way: peak <= PVS <= sqrt(3) * peak."""
return max(peak - 1, 0) ** 2 <= pvs_sq <= 3 * (peak + 1) ** 2
def detect_multi_interval_layout(body: bytes) -> Optional[Tuple[int, int]]:
"""``(record_len, per_block)`` of a multi-interval body, or None.
Found from the second block header (block_ctr one higher), confirmed on a
third when present; a single short block is found from its terminal tail.
"""
if not _is_multi_header(body, 0):
return None
lo = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MIN_RECORDS
hi = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MAX_RECORDS
for stride in range(lo, min(hi, len(body)) + 1, 2):
if (stride - 12) % _MULTI_RECORD_LEN:
continue
if not _is_multi_header(body, stride):
continue
# DECISIVE CHECK: consecutive blocks differ by exactly 1 in block_ctr.
# Without it this false-positives on ordinary standard-block bodies:
# those carry a header every 32 bytes, and 192 = 12 + 20*9 and
# 512 = 12 + 20*25 are both multiples of 32, so a stride "fits" while
# actually skipping 6 or 16 real blocks. Sampling a standard body at
# stride 192 handed 9,082 files to the wrong decoder and produced peaks
# of 149 in/s against a 10 in/s full scale.
def _ctr(o: int) -> int:
return body[o + 2] | (body[o + 3] << 8)
if (_ctr(stride) - _ctr(0)) & 0xFFFF != 1:
continue
# Confirm on a third block WHEN ONE IS ACTUALLY PRESENT. A body can
# be longer than two strides and still hold only two real blocks: a
# final *partial* block leaves trailing padding. E.g. 51 intervals at
# 2 s = one full 30-interval block + a 21-interval remainder, in a
# 2787-byte body — long enough to demand a third header at 1224 that
# does not exist. Requiring it unconditionally threw away the correct
# stride and the file decoded to nothing (BE18193 T193L0XM.CI0H).
# The block-counter check above is the decisive anti-false-positive
# test; this one is corroboration, so a missing third header means
# end-of-stream, not disqualification.
if (2 * stride + _MULTI_HEADER_LEN <= len(body)
and _is_multi_header(body, 2 * stride)):
if (_ctr(2 * stride) - _ctr(stride)) & 0xFFFF != 1:
for rec in _RECORD_LENS:
# A 20-byte record with one interval per block IS the standard 32-byte
# block, which walk_body reads; the mic-off one-minute block is not.
for n in range(2 if rec == 20 else 1, _MULTI_MAX_RECORDS + 1):
s = _stride(rec, n)
if s + _MULTI_HEADER_LEN > len(body):
break
if not _follows(body, 0, s):
continue
return stride
# The block-counter step is the decisive test: a standard body has a
# header every 32 bytes, and 192 = 12 + 20x9 skips 6 of them. A third
# block, when there is one, must follow too.
if (_is_multi_header(body, 2 * s) and not _follows(body, s, 2 * s)
and body[2 * s - 4:2 * s] != _BLOCK_TAIL_TERMINAL):
continue
if not _records_plausible(body, 0, rec, n):
continue
return rec, n
# One block only (a histogram shorter than a minute): bounded by its tail.
t = body.find(_BLOCK_TAIL_TERMINAL)
while t >= 0:
for rec in _RECORD_LENS:
span = t + 4 - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN
if span > 0 and span % rec == 0 and span // rec <= _MULTI_MAX_RECORDS \
and _records_plausible(body, 0, rec, span // rec):
return rec, span // rec
t = body.find(_BLOCK_TAIL_TERMINAL, t + 1)
return None
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None."""
layout = detect_multi_interval_layout(body)
return _stride(*layout) if layout else None
def _decode_record(body: bytes, q: int, rec: int, off: int) -> dict:
def be16(p: int) -> int:
return (body[p] << 8) | body[p + 1]
mic = rec == 20
z = rec - 4
return {
"segment_id": body[off + 1],
"block_ctr": _ctr(body, off),
"t_peak": be16(q), "t_halfp": be16(q + 2),
"v_peak": be16(q + 4), "v_halfp": be16(q + 6),
"l_peak": be16(q + 8), "l_halfp": be16(q + 10),
"m_peak": be16(q + 12) if mic else None,
"m_halfp": be16(q + 14) if mic else None,
"meta_var": bytes(body[q + z:q + z + 4]),
"pvs_sq": int.from_bytes(body[q + z:q + z + 4], "big"),
"is_terminal": False,
}
def walk_multi_interval_blocks(body: bytes,
stride: Optional[int] = None) -> List[dict]:
"""Decode a multi-interval histogram body into per-interval records."""
if stride is None:
stride = detect_multi_interval_stride(body)
if not stride:
return []
n_per_block = (stride - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN) // _MULTI_RECORD_LEN
if n_per_block < 1:
return []
def u16le(p: int) -> int:
return body[p] | (body[p + 1] << 8)
"""Decode a multi-interval histogram body into per-interval records.
``stride`` is accepted for compatibility and ignored: the record size is
detected, and each block's own length is read from the stream.
"""
layout = detect_multi_interval_layout(body)
if not layout:
return []
rec, n = layout
s = _stride(rec, n)
out: List[dict] = []
for off in range(0, len(body) - stride + 1, stride):
if not _is_multi_header(body, off):
break # end of the block run; trailer follows
for k in range(n_per_block):
q = off + _MULTI_HEADER_LEN + _MULTI_RECORD_LEN * k
out.append({
"_tail0": u16le(q + 16),
"segment_id": body[off + 1],
"block_ctr": u16le(off + 2),
"t_peak": u16le(q), "t_halfp": u16le(q + 2),
"v_peak": u16le(q + 4), "v_halfp": u16le(q + 6),
"l_peak": u16le(q + 8), "l_halfp": u16le(q + 10),
"m_peak": u16le(q + 12), "m_halfp": u16le(q + 14),
"meta_var": bytes(body[q + 16:q + 20]),
"is_terminal": False,
})
# A session ending mid-block leaves the remaining slots of the FINAL block
# filled with whatever was in the buffer. Those decoded as peaks thousands
# of times the device-reported PPV, so they have to go — but only from the
# final block: a non-zero tail word occurs mid-file on real intervals, and
# trimming on that alone truncated four BE9440 files by up to 2,800
# intervals, while trimming purely from the end left garbage stranded
# behind one slot that happened to have a zero tail word.
#
# Within the final block, stop at the first slot that is not plausibly
# real: a non-zero tail word, or a geo peak above full scale. 16-count
# units put Normal-range full scale (10.000 in/s) at 2000 counts, so
# anything beyond that is physically impossible.
if out:
last_block_start = ((len(out) - 1) // n_per_block) * n_per_block
for i in range(last_block_start, len(out)):
r = out[i]
if (r["_tail0"] != 0
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
del out[i:]
off = 0
while _is_multi_header(body, off):
# The last block ends on the terminal tail, after however many intervals
# it holds; any other block runs the full stride to the next header.
m = next((k for k in range(1, n + 1)
if body[off + _stride(rec, k) - 4:off + _stride(rec, k)] == _BLOCK_TAIL_TERMINAL),
None)
last = m is not None
if not last:
nxt = off + s
if not _follows(body, off, nxt):
# No terminal tail and no next block: the stream just stops. Read
# what fits and trim implausible slots (the pre-2026-10-26 rule).
m, last = min(n, (len(body) - off - _MULTI_HEADER_LEN) // rec), True
recs = [_decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
for k in range(max(m, 0))]
for k, r in enumerate(recs):
peak = max(r["t_peak"], r["v_peak"], r["l_peak"])
if not _pvs_consistent(peak, r["pvs_sq"]) or peak > _GEO_MAX_COUNTS:
del recs[k:]
break
out.extend(recs)
break
for r in out:
r.pop("_tail0", None)
m = n
for k in range(m):
r = _decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
r["is_terminal"] = last
out.append(r)
if last:
break
off += s
return out
+185
View File
@@ -0,0 +1,185 @@
"""
minimateplus/mlg_file.py — Blastware's monitor log (.MLG): reader and writer.
Blastware writes one .MLG per call-in, named <serial><counter>.MLG, holding what
the unit logged since the previous call-in: each time monitoring started, each
event, and each time it stopped and why. Measured on 1,273 DL2 files and 9
bench files (2026-11-09; reference D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md):
[18-byte prefix 10 00 01 80 00 00 "Instantel\\0" 07 2c]
[292-byte records ...] size is always 18 + 292*n
Every record:
[0:2] length, uint16 LE = 290
[2:4] id: 0e a0 the header record (first, carries the serial), 0e 80 a log record
[4:12] start: day, month, year LE, 0, hour, minute, second
[12:20] stop, same format; all zeros = no stop
[20:22] monitor-log flag word, uint16 LE (the event footer's, D.6.14); 0xFFFF = started
[22:24] trigger source, uint16 LE: 0x0001-0x0008 a channel, 0x0400 a histogram
[24:34] serial, NUL-padded ASCII
[34:288] text, NUL-padded; an event's starts 0x08 + its 8-byte time
[288:290] 00 00
[290:292] CRC-16/AUG-CCITT over [0:288], little-endian
An empty file is the prefix alone: no header record, no serial. Pure: no I/O
beyond reading the path it is given.
"""
from __future__ import annotations
import datetime
import struct
from pathlib import Path
from typing import Optional, Union
from .crc import crc16_aug_ccitt
from .event_file_io import monitor_log_description
from .models import MlgFile, MlgRecord
MLG_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c"
RECORD_SIZE = 292
_RECORD_LENGTH = 290
_HEADER_ID = b"\x0e\xa0"
_LOG_ID = b"\x0e\x80"
_EVENT_TIME_MARK = 0x08
_TRIGGER_LEVEL_PREFIXES = ("Trigger Level :", "Trigger Level:")
class MlgFormatError(ValueError):
"""The bytes are not a whole .MLG file."""
def _ts(raw: bytes) -> Optional[datetime.datetime]:
"""8-byte MLG time (year little-endian); all zeros = None. Raises ValueError."""
if raw == bytes(8):
return None
year = struct.unpack_from("<H", raw, 2)[0]
return datetime.datetime(year, raw[1], raw[0], raw[5], raw[6], raw[7])
def _crc_ok(record: bytes) -> bool:
return crc16_aug_ccitt(record[:288]) == struct.unpack_from("<H", record, 290)[0]
def _trigger_level(text: str) -> Optional[str]:
line = text.split("\r", 1)[0]
for prefix in _TRIGGER_LEVEL_PREFIXES:
if line.startswith(prefix):
line = line[len(prefix):]
break
line = line.strip()
return line or None
def _log_record(index: int, rec: bytes) -> MlgRecord:
try:
start = _ts(rec[4:12])
stop = _ts(rec[12:20])
except ValueError as exc:
raise MlgFormatError(f"record {index}: a time cannot be decoded ({exc})") from None
if start is None:
raise MlgFormatError(f"record {index}: no start time")
flags, source = struct.unpack_from("<HH", rec, 20)
text_raw = rec[34:288]
body, event_time = text_raw, None
if text_raw[0] == _EVENT_TIME_MARK:
try:
event_time = _ts(text_raw[1:9])
except ValueError as exc:
raise MlgFormatError(f"record {index}: the event time cannot be decoded ({exc})") from None
body = text_raw[9:]
text = body.split(b"\x00", 1)[0].decode("latin-1")
is_start = flags == 0xFFFF
return MlgRecord(
index=index,
start=start,
stop=stop,
flags=flags,
trigger_source=source,
serial=rec[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
text_raw=text_raw,
event_time=event_time,
text=text,
trigger_level=_trigger_level(text),
description="Monitoring started" if is_start else monitor_log_description(flags).strip(),
crc_ok=_crc_ok(rec),
)
def parse_mlg(data: bytes) -> MlgFile:
"""Parse the bytes of a .MLG file.
Raises MlgFormatError when the bytes are not a whole .MLG. A record whose
checksum fails is returned with crc_ok=False (MlgFile.crc_failures lists
them); the caller decides what to do with it."""
if len(data) < len(MLG_PREFIX) or not data.startswith(MLG_PREFIX):
raise MlgFormatError("not an MLG: the 18-byte Instantel prefix is missing")
body = data[len(MLG_PREFIX):]
if len(body) % RECORD_SIZE:
raise MlgFormatError(f"not an MLG: size {len(data)} is not 18 + 292*n")
records = [body[i:i + RECORD_SIZE] for i in range(0, len(body), RECORD_SIZE)]
if not records:
return MlgFile(serial=None)
for index, rec in enumerate(records):
length = struct.unpack_from("<H", rec, 0)[0]
if length != _RECORD_LENGTH:
raise MlgFormatError(f"record {index}: length field {length}, expected 290")
expected = _HEADER_ID if index == 0 else _LOG_ID
if rec[2:4] != expected:
raise MlgFormatError(f"record {index}: id {rec[2:4].hex()}, expected {expected.hex()}")
header = records[0]
return MlgFile(
serial=header[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
records=[_log_record(i, rec) for i, rec in enumerate(records) if i > 0],
header_crc_ok=_crc_ok(header),
)
def read_mlg(path: Union[str, Path]) -> MlgFile:
"""Read and parse a .MLG file."""
return parse_mlg(Path(path).read_bytes())
# ── Writer ────────────────────────────────────────────────────────────────────
def _ts_bytes(ts: Optional[datetime.datetime]) -> bytes:
if ts is None:
return bytes(8)
return bytes([ts.day, ts.month]) + struct.pack("<H", ts.year) + bytes([0, ts.hour, ts.minute, ts.second])
def _serial_field(serial: str) -> bytes:
return serial.encode("ascii", errors="replace")[:10].ljust(10, b"\x00")
def _sealed(body: bytes) -> bytes:
"""`body` is record[0:288]; append the two zero bytes and the LE checksum."""
return body + b"\x00\x00" + struct.pack("<H", crc16_aug_ccitt(body))
def _header_record(serial: str) -> bytes:
# Every byte but the serial is zero on all 1,273 DL2 files (measured 2026-11-13).
body = struct.pack("<H", _RECORD_LENGTH) + _HEADER_ID + bytes(20) + _serial_field(serial)
return _sealed(body.ljust(288, b"\x00"))
def _log_record_bytes(r: MlgRecord) -> bytes:
body = (struct.pack("<H", _RECORD_LENGTH) + _LOG_ID + _ts_bytes(r.start) + _ts_bytes(r.stop)
+ struct.pack("<HH", r.flags, r.trigger_source) + _serial_field(r.serial)
+ r.text_raw.ljust(254, b"\x00")[:254])
return _sealed(body)
def mlg_bytes(mlg: MlgFile) -> bytes:
"""The bytes of a .MLG file, as Blastware writes them: little-endian times,
length-led records, each record's checksum computed. An empty MlgFile is
the prefix alone."""
if mlg.empty:
return MLG_PREFIX
return MLG_PREFIX + _header_record(mlg.serial or "") + b"".join(_log_record_bytes(r) for r in mlg.records)
def write_mlg(mlg: MlgFile, path: Union[str, Path]) -> None:
"""Write `mlg` to `path` (see mlg_bytes)."""
Path(path).write_bytes(mlg_bytes(mlg))
+132
View File
@@ -300,6 +300,10 @@ class DeviceInfo:
# ── From SUB 08 (EVENT_INDEX_RESPONSE) ────────────────────────────────────
event_count: Optional[int] = None # stored event count from F7 response 🔶
# ── From a Blastware event file's identity block (2026-11-03) ─────────────
calibration_date: Optional[datetime.date] = None # e.g. 2019-02-20 ✅
calibrated_by: Optional[str] = None # e.g. "Instantel" ✅
def __str__(self) -> str:
fw = self.firmware_version or f"?.{self.firmware_minor}"
mdl = self.model or "MiniMate Plus"
@@ -352,6 +356,9 @@ class PeakValues:
long: Optional[float] = None # Longitudinal PPV (in/s) ✅
micl: Optional[float] = None # Air overpressure (psi) 🔶 (units uncertain)
peak_vector_sum: Optional[float] = None # Scalar geo PVS (in/s) ✅
# ZC frequency (Hz), from the unit's own summary in the file (2026-11-05) or
# a report. Above range, the value is Blastware's threshold (100 Hz at
# 1024 sps) and the flag is set; None is Blastware's "N/A".
tran_zc_freq: Optional[float] = None
vert_zc_freq: Optional[float] = None
long_zc_freq: Optional[float] = None
@@ -360,6 +367,50 @@ class PeakValues:
vert_zc_above_range: bool = False
long_zc_above_range: bool = False
mic_zc_above_range: bool = False
# A waveform's peak detail (2026-11-04); None for a histogram. Times of peak
# are the unit's own peak samples, acceleration comes from the samples.
tran_time_of_peak: Optional[float] = None # s from the trigger; negative = pre-trigger
vert_time_of_peak: Optional[float] = None
long_time_of_peak: Optional[float] = None
micl_time_of_peak: Optional[float] = None
pvs_time: Optional[float] = None # s from the trigger, of the vector-sum peak
tran_peak_accel_g: Optional[float] = None
vert_peak_accel_g: Optional[float] = None
long_peak_accel_g: Optional[float] = None
# Peak displacement (in), from the unit's own summary (2026-11-05).
tran_peak_disp_in: Optional[float] = None
vert_peak_disp_in: Optional[float] = None
long_peak_disp_in: Optional[float] = None
# Over range: the unit's own peak passed full scale (2026-11-09). Blastware
# prints OORANGE for that peak, and for the vector sum when any geophone is
# over; the value beside it is then a lower bound.
tran_over_range: bool = False
vert_over_range: bool = False
long_over_range: bool = False
mic_over_range: bool = False
pvs_over_range: bool = False
@dataclass
class SensorCheckResult:
"""One channel's sensor check, as the unit stores it in the event file
(2026-11-06). `result` is Blastware's word for it."""
result: str # "Passed", "Check" or "Disabled"
status: int # the unit's code: 0 passed; its bits are not decoded
freq_hz: Optional[float] = None # geophone resonance / mic test frequency; None when Disabled
ratio: Optional[float] = None # geophones only
amplitude_mv: Optional[int] = None # the mic only
@dataclass
class MonitorLogLine:
"""The Monitor Log line Blastware prints for an event, from the file's
footer (2026-11-08): the monitoring session's start, the stop, and what
happened. Not the live 0x0A browse entries (MonitorLogEntry)."""
start: datetime.datetime
stop: datetime.datetime
flags: int # the footer's flag word
description: str # Blastware's words, e.g. "Event Recorded Modem Exit"
# ── Project / operator metadata ───────────────────────────────────────────────
@@ -379,6 +430,8 @@ class ProjectInfo:
operator: Optional[str] = None # operator / user name
sensor_location: Optional[str] = None # sensor location string
notes: Optional[str] = None # extended notes
job_number_enabled: Optional[bool] = None # Blastware prints the job number
job_number: Optional[int] = None # kept while switched off
# ── Compliance Config ──────────────────────────────────────────────────────────
@@ -543,6 +596,24 @@ class Event:
total_samples: Optional[int] = None # from STRT record: expected total sample-sets
pretrig_samples: Optional[int] = None # from STRT record: pre-trigger sample count
rectime_seconds: Optional[int] = None # from STRT record: record duration (seconds)
# Geophone range from the recording setup, as ComplianceConfig.geo_range:
# 0 Normal (10 in/s full scale), 1 Sensitive (1.25 in/s). None: not read.
geo_range: Optional[int] = None
# From a Blastware event file (2026-11-03); None when not read.
device_info: Optional["DeviceInfo"] = None # the unit, as SUB FE reports it
battery_volts: Optional[float] = None # at the event
triggered_by: Optional[int] = None # 0x01 Tran 0x02 Vert 0x04 Long 0x08 MicL 0x200 Manual
trigger_sources: Optional[int] = None # setup bitmask: 0x07 geophones, 0x08 mic
trigger_level_geo: Optional[float] = None # in/s, as ComplianceConfig.trigger_level_geo
trigger_level_mic_psi: Optional[float] = None
record_stop_mode: Optional[int] = None # 0 = Fixed
mic_type: Optional[int] = None # 2 = Linear Weighting (as Series IV)
mic_range: Optional[int] = None # 0; 1 = each mic count is an eighth (2026-11-09)
stop_time: Optional[datetime.datetime] = None # the footer's stop
# A histogram's per-interval detail (2026-11-03); None for a waveform.
histogram_interval_sec: Optional[int] = None # as ComplianceConfig.histogram_interval_sec
interval_half_periods: Optional[dict] = None # channel -> half-period per interval, samples
interval_pvs: Optional[list] = None # each interval's vector sum, in/s
# Sensor self-check traces keyed by channel label — the short diagnostic
# waveforms the unit records when it pulses each sensor before monitoring
@@ -552,6 +623,21 @@ class Event:
# Raw ADC counts; the source series' scale differs but the trace is a
# shape diagnostic (rendered fit-to-box). None when absent.
sensor_check: Optional[dict] = None # {"Tran": [...], ..., "MicL": [...]}
# And its results per channel, from the same records (2026-11-06): None
# when the file's record chain is not whole.
sensor_check_results: Optional[dict] = None # channel -> SensorCheckResult
# The event's Monitor Log line (2026-11-08): None unless the file's record
# chain is whole, which proves the footer.
monitor_log: Optional[MonitorLogLine] = None
# Where `timestamp` came from, when decoded from a Blastware binary
# (event_file_io): "event_record" -- the instrument's own event record in
# the 5A stream, validated; "report" -- a paired Blastware report;
# "footer" -- a histogram's footer start; "estimate" -- footer stop minus
# the record time, a second off on ~19% of measured files, so it comes with
# an entry in decode_problems. None: not decoded from a file.
timestamp_source: Optional[str] = None
decode_problems: list = field(default_factory=list)
# ── Debug / introspection ─────────────────────────────────────────────────
# Raw 210-byte waveform record bytes, set when debug mode is active.
@@ -643,6 +729,52 @@ class MonitorLogEntry:
return f"MonitorLog#{self.index} key={self.key} {start}→{stop}{dur}"
# ── Blastware monitor log (.MLG) ──────────────────────────────────────────────
@dataclass
class MlgRecord:
"""One log record of a Blastware .MLG file (minimateplus/mlg_file.py).
Times are the unit's own local clock. `flags` is the monitor-log flag word
(the event footer's, reference D.6.14); 0xFFFF means monitoring started
and has no stop yet."""
index: int # position in the file; 0 is the header record
start: datetime.datetime
stop: Optional[datetime.datetime]
flags: int
trigger_source: int # 0x0001-0x0008 a channel, 0x0400 a histogram, 0 none
serial: str
text_raw: bytes = field(repr=False) # record[34:288] exactly, for write_mlg
event_time: Optional[datetime.datetime] = None
text: str = "" # Blastware's text, after any event time
trigger_level: Optional[str] = None # e.g. "Geo: 0.0500 in/s Mic: 125.0 dB(L)", "Histogram"
description: str = "" # "Monitoring started", or Blastware's words
crc_ok: bool = True
@property
def is_start(self) -> bool:
return self.flags == 0xFFFF
@dataclass
class MlgFile:
"""A whole .MLG file: the serial from its header record and its log records,
in file order. An empty file (the 18-byte prefix alone) has neither."""
serial: Optional[str]
records: list[MlgRecord] = field(default_factory=list)
header_crc_ok: bool = True
@property
def empty(self) -> bool:
return self.serial is None and not self.records
@property
def crc_failures(self) -> list[int]:
"""Indexes of the records whose checksum fails (0 is the header record)."""
head = [] if self.header_crc_ok else [0]
return head + [r.index for r in self.records if not r.crc_ok]
# ── MonitorStatus ─────────────────────────────────────────────────────────────
@dataclass
+149 -44
View File
@@ -142,9 +142,14 @@ _WRITE_TAIL = {SUB_EVENT_INDEX_WRITE: b"\x02\x00", SUB_TRIGGER_CONFIG_WRITE: b"\
SUB_CALL_HOME_WRITE: b"\x00\x00"}
def write_image(sub: int, data: bytes) -> bytes:
def write_image(sub: int, data: bytes, *, escaped: bool = True) -> bytes:
"""The whole block a write sends: `data` unescaped, N + 2 bytes.
`escaped=False`: `data` is already logical (every block read since phase 5 --
read_event_index, read_compliance_content, read_trigger_config,
read_waveform_data_raw -- returns unescaped bytes), so it is NOT unescaped
again: a logical `10 02` (job number 4098) would otherwise collapse.
A config block starts with its own length N (uint16 BE) and is written as N
bytes plus two -- on every Blastware write on record. `data` may be the
block as a read returned it (N bytes, or N + 2) and may still hold the
@@ -152,7 +157,7 @@ def write_image(sub: int, data: bytes) -> bytes:
Anything else is refused before a byte is sent: a block one byte longer than
its header says is what an edit beside a kept escape byte leaves behind.
"""
image = unescape_reply(bytes(data))
image = unescape_reply(bytes(data)) if escaped else bytes(data)
if len(image) < 2:
raise ValueError(f"write SUB 0x{sub:02X}: {len(image)} bytes is not a whole block")
n = int.from_bytes(image[:2], "big")
@@ -165,6 +170,82 @@ def write_image(sub: int, data: bytes) -> bytes:
return image
class ImageRefused(ValueError):
"""A write refused before any byte was sent: the image is not a whole block."""
# ── The settings block (SUB 1A), as content ─────────────────────────────────
#
# Measured 2026-11-03 on BE9441's 10-26 recording (12 reads, both Blastware's
# 4 x 512 + 42 pattern and SFM's 1024 + 1024 + 42): unescape each data frame and
# take data[11:]; every frame but the last then starts with one `00` that is not
# content. Dropped, the frames join into 2,090 bytes that start with their own
# length N = 2090 -- Series IV's 0x1A content layout -- and the read after each
# of Blastware's two writes equals the image it had just written.
# tests/test_s3_settings_read.py.
COMPLIANCE_CONTENT_LEN = 2090
# SFM's 1A read: (offset = the content length asked for, page) per data frame.
_COMPLIANCE_READ_STEPS = ((0x0400, 0x00), (0x0400, 0x04), (0x002A, 0x08))
def assemble_compliance_content(frames: "list[bytes]", lengths: "Optional[tuple]" = None) -> bytes:
"""Join a 1A read's data frames (each S3Frame.data, kept escapes and all, in
order) into the logical settings block. Judges nothing: a monitoring unit's
device-info answer assembles too -- `is_compliance_content` tells them apart.
`lengths`: the content each frame was asked for (SFM's read: 1024, 1024, 42).
Each frame then gives exactly that. Measured at the bench 2026-11-04 (BE9441):
when a frame's checksum byte was itself escaped (02 / 03 / 04), the parser kept
the escape's 0x10, so the frame arrived one byte long, ending in a lone 0x10.
The parser drops it since #58; this trim stays as a guard. That one byte is
dropped; any other leftover is kept, and the block then fails
is_compliance_content."""
parts = [unescape_reply(bytes(f))[11:] for f in frames]
parts = [p[1:] for p in parts[:-1]] + parts[-1:]
if lengths is not None and len(lengths) == len(parts):
parts = [p[:n] if p[n:] == b"\x10" else p for p, n in zip(parts, lengths)]
return b"".join(parts)
def is_compliance_content(block: bytes) -> bool:
"""Whether `block` is the settings block: 2,090 bytes headed by N = 2090."""
return (len(block) == COMPLIANCE_CONTENT_LEN
and int.from_bytes(block[0:2], "big") == COMPLIANCE_CONTENT_LEN)
def is_call_home_block(raw: bytes) -> bool:
"""Whether a 0x2C reply payload is the call-home block: it starts with its own
length N = 0x7C (00 7C DC on every read on record) and is N (or N + 2) bytes
unescaped. A MONITORING MiniMate answers the read with its device-info block
instead (00 00 00 08 'Instantel' ..., measured 2026-11-03 on BE9441), which
fails this."""
image = unescape_reply(bytes(raw))
n = DATA_LENGTHS[SUB_CALL_HOME]
return len(image) >= 3 and int.from_bytes(image[:2], "big") == n and len(image) in (n, n + 2)
def call_home_enabled(raw: bytes) -> Optional[bool]:
"""The call-home switch of a `0x2C` reply payload, read UNESCAPED (an escaped
byte before it would move the raw index -- bench finding #1's lesson): byte 5,
0x01 on / 0x00 off (measured 2026-04-20, BE11529). Anything else is None."""
image = unescape_reply(bytes(raw))
if len(image) <= 5:
return None
return {0x01: True, 0x00: False}.get(image[5])
def call_home_image(raw: bytes, enabled: bool) -> bytes:
"""The `0x7E` image that turns call-home on or off: the block as read
(`write_image`, N + 2 bytes, unescaped) with byte 5 set to 0x01 / 0x00 and
every other byte as the unit sent it. Refuses a byte 5 never measured."""
image = write_image(SUB_CALL_HOME_WRITE, raw)
if image[5] not in (0x00, 0x01):
raise ValueError(f"call-home byte 5 is 0x{image[5]:02X} -- not a value ever measured "
"(0x00 off / 0x01 on); nothing built")
return image[:5] + bytes([0x01 if enabled else 0x00]) + image[6:]
# Default timeout values (seconds).
# MiniMate Plus is a slow device — keep these generous.
DEFAULT_RECV_TIMEOUT = 10.0
@@ -553,6 +634,11 @@ class MiniMateProtocol:
data_rsp = self._recv_one(expected_sub=rsp_sub)
raw = unescape_reply(data_rsp.data)[11:] # unescaped, as read_event_index
# An escaped checksum byte left its 0x10 behind until #58 (bench 2026-11-04;
# see assemble_compliance_content): kept as a guard, one stray byte beyond
# what was asked is dropped.
if len(raw) == length + 1 and raw[-1:] == b"\x10":
raw = raw[:-1]
log.debug("read_waveform_data_raw: got %d bytes", len(raw))
return raw
@@ -993,6 +1079,25 @@ class MiniMateProtocol:
return bytes(config)
def read_compliance_content(self) -> bytes:
"""The 1A read as the logical settings block (see assemble_compliance_content).
The same requests as read_compliance_config -- probe, then B / C / D -- but
strict: a data frame that does not arrive raises, and there is no tail
drain, so a short read is never assembled. Returns whatever assembled,
unjudged; a MONITORING unit answers with its device-info block, which
is_compliance_content() rejects.
"""
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE)
self._send(build_bw_frame(SUB_COMPLIANCE, 0, bytes([0, 0, 0, 0, 0, 0, 0, 0x64, 0, 0])))
self._recv_one(expected_sub=rsp_sub)
frames = []
for offset, page in _COMPLIANCE_READ_STEPS:
self._send(build_bw_frame(SUB_COMPLIANCE, offset,
bytes([0, 0, page, 0, 0, 0, 0, 0x64, 0, 0])))
frames.append(self._recv_one(expected_sub=rsp_sub).data)
return assemble_compliance_content(frames, lengths=tuple(o for o, _ in _COMPLIANCE_READ_STEPS))
# ── Write commands (SUBs 68–83) ───────────────────────────────────────────
def recv_write_ack(
@@ -1050,25 +1155,26 @@ class MiniMateProtocol:
self._send(frame)
return self.recv_write_ack(expected_sub=rsp_sub)
def _write_block(self, sub: int, data: bytes, params: bytes = bytes(10)) -> S3Frame:
def _write_block(self, sub: int, data: bytes, params: bytes = bytes(10), *,
escaped: bool = True) -> S3Frame:
"""Send one config block as a write and return its ack (0xFF - sub)."""
image = write_image(sub, data)
image = write_image(sub, data, escaped=escaped)
frame = build_bw_write_frame(sub, image, params=params)
log.debug("write SUB=0x%02X: %d-byte image", sub, len(image))
self._send(frame)
return self.recv_write_ack(expected_sub=_expected_rsp_sub(sub))
def write_event_index(self, data: bytes) -> S3Frame:
def write_event_index(self, data: bytes, *, escaped: bool = True) -> S3Frame:
"""SUB 68: write the event-index block (as SUB 08 read it). Ack 0x97;
callers follow with write_confirm(SUB_WRITE_CONFIRM_B). See write_image."""
return self._write_block(SUB_EVENT_INDEX_WRITE, data)
return self._write_block(SUB_EVENT_INDEX_WRITE, data, escaped=escaped)
def write_waveform_data(self, data: bytes) -> S3Frame:
def write_waveform_data(self, data: bytes, *, escaped: bool = True) -> S3Frame:
"""SUB 69: write the waveform-data block (as SUB 09 read it). Ack 0x96;
callers follow with write_confirm C then A. See write_image."""
return self._write_block(SUB_WAVEFORM_DATA_WRITE, data)
return self._write_block(SUB_WAVEFORM_DATA_WRITE, data, escaped=escaped)
def write_compliance_config_raw(self, data: bytes) -> None:
def write_compliance_config_raw(self, data: bytes, *, escaped: bool = True) -> None:
"""SUB 71: write the compliance image in addressed chunks, then confirm (72).
Measured: the image is 2,092 bytes (its header N = 2,090, plus 2), sent as
@@ -1079,7 +1185,7 @@ class MiniMateProtocol:
both. (Retracted: "exactly 3 chunks, offset 0x1004, params 00 00 00 10 04"
-- the length 0x0400 and address 0x0400, read with their escape bytes.)
"""
image = write_image(SUB_COMPLIANCE_WRITE, data)
image = write_image(SUB_COMPLIANCE_WRITE, data, escaped=escaped)
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE_WRITE)
for addr in range(0, len(image), _COMPLIANCE_CHUNK):
params = bytes([0x00, 0x00, (addr >> 8) & 0xFF, addr & 0xFF]) + bytes(6)
@@ -1090,10 +1196,10 @@ class MiniMateProtocol:
self.recv_write_ack(expected_sub=rsp_sub)
self.write_confirm(SUB_WRITE_CONFIRM_A)
def write_trigger_config(self, data: bytes) -> S3Frame:
def write_trigger_config(self, data: bytes, *, escaped: bool = True) -> S3Frame:
"""SUB 82: write the trigger block (as SUB 0x2E read it). Ack 0x7D;
callers follow with write_confirm(SUB_TRIGGER_CONFIRM). See write_image."""
return self._write_block(SUB_TRIGGER_CONFIG_WRITE, data)
return self._write_block(SUB_TRIGGER_CONFIG_WRITE, data, escaped=escaped)
def read_trigger_config(self) -> bytes:
"""SUB 0x2E two-step read: the 26-byte trigger block that SUB 82 writes.
@@ -1151,41 +1257,40 @@ class MiniMateProtocol:
def write_call_home_config(self, data: bytes) -> None:
"""
Write the auto call home configuration (SUB 0x7E → 0x7F confirm).
Write the call-home block as a read returned it (SUB 0x7E, then 0x7F).
Write sequence (confirmed from 4-20-26 call home settings captures):
SUB 0x7E write 127-byte payload → device acks SUB 0x81
SUB 0x7F confirm (no data) → device acks SUB 0x80
The 127-byte write payload = 125-byte read payload + b'\\x00\\x00'.
The offset field = data[1] + 2 = 0x7C + 2 = 0x7E = 126.
Write frame format: build_bw_write_frame (minimal DLE stuffing — only
BW_CMD is doubled; all other bytes are RAW). The \\x10\\x03 sequence
within the payload is preserved as-is (device interprets DLE+ETX as the
literal value 0x03 per the inner-frame terminator convention).
Args:
data: 127-byte write payload (read payload + \\x00\\x00 footer).
Must start with [0x00][0x7C][...] (standard header).
Raises:
ValueError: if data is not exactly 127 bytes or lacks expected header.
ProtocolError: on timeout or wrong response SUB.
`data` is the 0x2C read payload (125 B, the parser's kept escape bytes
in -- num_retries 3 arrives as 10 03), optionally + 00 00. `write_image`
removes the escapes once and makes the 126-byte image (N = 0x7C, + 2);
`write_call_home_image` sends it. The legacy multi-field path.
"""
rsp_sub_confirm = _expected_rsp_sub(SUB_CALL_HOME_CONFIRM) # 0xFF - 0x7F = 0x80
# 2026-10-27 (#46): the read payload holds the parser's kept escape bytes
# (num_retries 3 arrives as 10 03); write_image removes them, so the
# 127-byte "read + 00 00" goes out as its 126-byte image (N = 0x7C, + 2),
# escaped like every request. No Blastware call-home write is on record
# here to compare against -- inferred from the 77 other write frames.
self._write_block(SUB_CALL_HOME_WRITE, data)
log.debug("write_call_home_config: write acked; sending confirm 0x7F")
self.write_call_home_image(write_image(SUB_CALL_HOME_WRITE, data))
confirm_frame = build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")
self._send(confirm_frame)
self.recv_write_ack(expected_sub=rsp_sub_confirm)
log.debug("write_call_home_config: confirm acked — done")
def write_call_home_image(self, image: bytes) -> None:
"""
Send a call-home image that is already built (`call_home_image`:
unescaped, N + 2 bytes) -- 0x7E, ack 0x81, then the 0x7F confirm, ack 0x80.
Never through `write_image` again: unescaping is not idempotent, and a
real 0x10 before 02/03/04 in the image -- a call-in time of 16:02-16:04
-- would lose its 0x10 (phase-4 final review, 2026-11-02). Measured: the
frames equal Blastware's 2026-04-20 enable / disable writes (BE11529),
tests/test_s3_call_home_bw_frames.py and test_s3_call_home_wire.py.
Raises ImageRefused, before any byte is sent, unless the image is a whole
block: its header N plus the two trailing bytes.
"""
image = bytes(image)
n = int.from_bytes(image[:2], "big") if len(image) >= 2 else -1
if len(image) != n + 2:
raise ImageRefused(f"write SUB 0x{SUB_CALL_HOME_WRITE:02X}: {len(image)} bytes, but its "
f"header says {n} (+ 2) -- not a whole image; nothing sent")
self._send(build_bw_write_frame(SUB_CALL_HOME_WRITE, image))
self.recv_write_ack(expected_sub=_expected_rsp_sub(SUB_CALL_HOME_WRITE))
log.debug("write_call_home_image: write acked; sending confirm 0x7F")
self._send(build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b""))
self.recv_write_ack(expected_sub=_expected_rsp_sub(SUB_CALL_HOME_CONFIRM))
log.debug("write_call_home_image: confirm acked — done")
# ── Monitoring ────────────────────────────────────────────────────────────
+8 -8
View File
@@ -98,25 +98,25 @@ def _decode_delta_stream(buf: bytes) -> List[int]:
def _find_chain(body: bytes):
"""Locate the four length-prefixed sensor-check records.
"""Locate the length-prefixed sensor-check records.
Returns a list of ``(offset, id, length)`` or ``None``. The chain is
validated by walking the ids 0x3c → 0x3d → 0x3e → 0x3f via their own length
prefixes, so a stray 0x3c byte in the waveform data cannot match.
validated by walking the ids 0x3c → 0x3d → 0x3e (→ 0x3f) via their own
length prefixes, so a stray 0x3c byte in the waveform data cannot match.
A unit without a mic has no 0x3f (BE16352, all 8 of its DL2 events,
2026-11-06), so the three geophone records are enough.
"""
for p in range(len(body) - 6):
if body[p + 2] == 0x3C and body[p + 3] == 0 and body[p + 4] == 0:
q = p
recs = []
ok = True
for expect in _CHAIN_IDS:
if q + 3 > len(body) or body[q + 2] != expect:
ok = False
break
length = int.from_bytes(body[q:q + 2], "big")
recs.append((q, expect, length))
q = q + 2 + length
if ok and len(recs) == 4:
if len(recs) >= 3:
return recs
return None
@@ -124,8 +124,8 @@ def _find_chain(body: bytes):
def decode_sensor_check(raw: bytes) -> Dict[str, List[int]]:
"""Decode the four sensor self-check traces from a series-3 event binary.
Returns ``{"Tran": [...], "Vert": [...], "Long": [...], "MicL": [...]}`` in
raw decode units (same 16-count LSB as the main waveform), or ``{}`` if the
Returns ``{"Tran": [...], "Vert": [...], "Long": [...], "MicL": [...]}`` (no
"MicL" on a unit without a mic) in raw decode units (same 16-count LSB as the main waveform), or ``{}`` if the
binary carries no sensor-check block (a histogram event, a non-series-3
file, or a unit/firmware that doesn't store it).
"""
+25 -9
View File
@@ -628,23 +628,39 @@ def decoded_to_adc_counts(decoded: dict) -> dict:
}
# One MicL count is 0.25 Pa (measured 2026-10-31): count x 0.25 Pa matches
# Blastware's "MicL Peak psi(L)" on all 1,729,253 DL2 histogram intervals
# checked.
MIC_PA_PER_COUNT = 0.25
# Blastware's dB(L) offset sits a hair above the exact 20 log10(0.25 Pa /
# 20 uPa) = 81.93820: any value in [81.9383, 81.9385] matches its dB on
# 1,729,252 / 1,729,253 intervals (the one left printed "0.000"), while
# 81.93820 rounds count 129 (162 intervals) to 124.1 against Blastware's
# 124.2, and the 81.94 first fitted to a handful of values misses counts 119
# and 132. Its display chain presumably carries rounded constants; the
# window, not the physics, is what is measured.
# ⚠ CORRECTED 2026-11-09: that window was too high. Every count Blastware
# printed in DL2 -- 1,704 in waveform sample tables, 520 in histogram
# intervals, 494 histogram peaks -- leaves [81.9382058, 81.9382266]: count
# 129 (124.2) bounds it from below, 463 (135.2, which 81.9384 prints 135.3)
# and 677 (138.5) from above. One offset serves all three.
_MIC_DB_REF = 81.938216
def mic_count_to_db(count: int) -> float:
"""Convert a MicL ADC count to dB(L) for BW-display-compatible output.
Empirical formula (confirmed 2026-05-11 against V70 fixture: count=813
→ 140.1 dB; count=±1 → ±81.94 dB; count=±24 → ±109.5 dB):
dB = sign(count) × (81.938216 + 20 × log10(|count|)) for |count| ≥ 1
dB = 0.0 for count == 0
dB = sign(count) × (81.94 + 20 × log10(|count|)) for |count| ≥ 1
dB = 0.0 for count == 0
The constant 81.94 corresponds to 10^(81.94/20) ≈ 12490 mic ADC counts
being the dB(L) reference level — almost certainly a calibration
constant from the device's mic.
81.938216 ≈ 20 log10(0.25 Pa / 20 µPa); see _MIC_DB_REF.
count=±1 → ±81.94 dB; count=813 → 140.14 dB (the V70 fixture).
"""
if count == 0:
return 0.0
sign = 1.0 if count > 0 else -1.0
return sign * (81.94 + 20.0 * math.log10(abs(count)))
return sign * (_MIC_DB_REF + 20.0 * math.log10(abs(count)))
# ── A5-frame entry point ────────────────────────────────────────────────────
-68
View File
@@ -1,68 +0,0 @@
"""
poc_set_project.py — POC test for set_project_info() against a live MiniMate Plus.
Usage:
python poc_set_project.py [--host IP] [--port PORT]
Default target: BE11529 at 63.43.212.232:9034
"""
import argparse
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-7s %(name)s %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("poc_set_project")
from minimateplus import MiniMateClient
from minimateplus.transport import TcpTransport
DEFAULT_HOST = "63.43.212.232"
DEFAULT_PORT = 9034
def main() -> None:
ap = argparse.ArgumentParser(description="POC: write project info to MiniMate Plus")
ap.add_argument("--host", default=DEFAULT_HOST, help="Modem IP address")
ap.add_argument("--port", type=int, default=DEFAULT_PORT, help="TCP port")
ap.add_argument("--project", default="POC Write Test")
ap.add_argument("--client-name", default="Terra-Mechanics Inc.")
ap.add_argument("--operator", default="B. Harrison")
ap.add_argument("--seis-loc", default="Lab Bench - POC")
ap.add_argument("--notes", default="set_project_info POC 2026-04-07")
args = ap.parse_args()
log.info("Connecting to %s:%d", args.host, args.port)
transport = TcpTransport(args.host, port=args.port)
with MiniMateClient(transport=transport, timeout=60.0) as client:
log.info("Performing POLL handshake + identity read …")
info = client.connect()
log.info("Connected: serial=%s firmware=%s", info.serial, info.firmware_version)
log.info("Calling set_project_info() …")
client.set_project_info(
project=args.project,
client_name=args.client_name,
operator=args.operator,
seis_loc=args.seis_loc,
notes=args.notes,
)
log.info("set_project_info() returned — write sequence complete")
log.info("Done. Reconnect Blastware to verify the fields were written.")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)
except Exception as exc:
log.exception("Fatal: %s", exc)
sys.exit(1)
+9 -3
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "seismo-relay"
version = "0.31.0"
version = "0.35.0"
description = "Python client and REST server for MiniMate Plus seismographs"
requires-python = ">=3.10"
dependencies = [
@@ -18,7 +18,13 @@ dependencies = [
"matplotlib>=3.8",
]
[project.optional-dependencies]
# What the test suite needs beyond the runtime: `pip install -e .[test]`.
# httpx is FastAPI's TestClient transport (tests/test_db_snapshot_endpoints.py).
test = ["pytest>=7", "httpx>=0.24"]
[tool.setuptools.packages.find]
# Auto-discovers minimateplus/, micromate/, sfm/, bridges/ as packages
# The product's packages. bridges/ (bench tools) is not one of them: it runs
# from a checkout and stays out of the image (ADR 0003).
where = ["."]
include = ["minimateplus*", "micromate*", "sfm*", "bridges*"]
include = ["minimateplus*", "micromate*", "sfm*"]
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Cross-check .MLG records against Blastware event files, in both directions.
check_mlg_vs_events.py <mlg dir> <event dir>
Every .MLG record with the Event Recorded bit (not a "monitoring started" one)
should have an event file whose footer has the same stop time, flag word and
trigger source; and every event file inside a unit's .MLG period (its first
record's start to its last record's stop) should have such a record. The
footer is read straight from each event file's last 28 bytes, independently of
the event decoder, and its CRC-16/AUG-CCITT is checked on the way.
Spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §7. Read-only.
"""
from __future__ import annotations
import collections
import datetime
import os
import struct
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.crc import crc16_aug_ccitt
from minimateplus.mlg_file import MlgFormatError, read_mlg
from sfm.waveform_store import _serial_number_from_bw_filename
_FOOTER_HEAD = b"\x00\x1a\x0e\x08"
def _ts_be(raw: bytes):
try:
return datetime.datetime(struct.unpack(">H", raw[2:4])[0], raw[1], raw[0], raw[5], raw[6], raw[7])
except ValueError:
return None
def _serial_number(serial: str):
digits = "".join(ch for ch in serial if ch.isdigit())
return int(digits) if digits else None
def mlg_side(mlg_dir: Path):
"""{unit number: (serial, [(stop, flags, source)], first start, last stop)}"""
units = {}
for path in sorted(p for p in mlg_dir.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"):
try:
mlg = read_mlg(path)
except MlgFormatError as exc:
print(f" skipped {path}: {exc}")
continue
if not mlg.serial or not mlg.records:
continue
n = _serial_number(mlg.serial)
serial, keys, lo, hi = units.get(n, (mlg.serial, [], None, None))
for r in mlg.records:
lo = min(lo, r.start) if lo else r.start
if r.stop:
hi = max(hi, r.stop) if hi else r.stop
if not r.is_start and r.flags & 0x0001:
keys.append((r.stop, r.flags, r.trigger_source))
units[n] = (serial, keys, lo, hi)
return units
def event_side(event_dir: Path, wanted: set):
"""{unit number: [(stop, flags, source, file name)]}, plus footer CRC failures."""
files = collections.defaultdict(list)
crc_bad = 0
for entry in os.scandir(event_dir):
if not entry.is_file():
continue
n = _serial_number_from_bw_filename(entry.name)
if n not in wanted:
continue
with open(entry.path, "rb") as f:
f.seek(0, 2)
if f.tell() < 28:
continue
f.seek(-28, 2)
tail = f.read(28)
if not tail.startswith(_FOOTER_HEAD):
continue
if crc16_aug_ccitt(tail[0:24]) != struct.unpack(">H", tail[26:28])[0]:
crc_bad += 1
flags, source = struct.unpack(">HH", tail[20:24])
files[n].append((_ts_be(tail[12:20]), flags, source, entry.name))
return files, crc_bad
def main(argv=None) -> int:
argv = argv if argv is not None else sys.argv[1:]
if len(argv) != 2:
print(__doc__)
return 2
units = mlg_side(Path(argv[0]))
files, crc_bad = event_side(Path(argv[1]), set(units))
checked = sum(len(v) for v in files.values())
print(f"event-file footers checked (units with .MLGs only): {checked}, failing their CRC: {crc_bad}")
for n, (serial, keys, lo, hi) in sorted(units.items(), key=lambda kv: kv[1][0]):
in_period = [f for f in files.get(n, []) if f[0] and lo <= f[0] <= hi]
file_keys = {f[:3] for f in in_period}
rec_keys = set(keys)
matched = [k for k in keys if k in file_keys]
record_only = [k for k in keys if k not in file_keys]
file_only = [f for f in in_period if f[:3] not in rec_keys]
print(f"\n{serial}: .MLG period {lo} -> {hi}")
print(f" matched {len(matched)}, record-only {len(record_only)}, file-only {len(file_only)}")
for k in record_only[:5]:
print(f" record-only: stop {k[0]} flags {k[1]:#06x} source {k[2]:#06x}")
if record_only:
print(f" record-only stops run {min(k[0] for k in record_only)} -> {max(k[0] for k in record_only)}")
for f in file_only[:5]:
print(f" file-only: {f[3]} stop {f[0]} flags {f[1]:#06x} source {f[2]:#06x}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env python3
"""
The Series 3 decode checker: SFM's file-only decode of every event, compared
with Blastware's `_XML.XML` report of the same event.
python scratch/check_s3_decode.py <binaries dir> <xml dir> [options]
Each event is decoded the way SFM ingest does, from its bytes alone -- no
filename, no report -- and every field, waveform sample and histogram interval
is compared (minimateplus/decode_check.py). Results go to a run folder outside
the repo, because they carry customer project names:
~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/
results.jsonl.gz one line per event: file, attrs, results rows
run.json args, commit, event count, wall time
Partial runs: --serial BE9441, --year 2024, --type W|H, --field samples.,
--sample 2000 [--seed K]. Spec:
docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md.
A lab tool (ADR 0003): it may import from sfm/; the comparison it runs may not.
"""
from __future__ import annotations
import argparse
import gzip
import json
import logging
import os
import random
import re
import subprocess
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
_REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(_REPO))
from minimateplus.bw_xml_report import XmlReport, parse_xml_report_file # noqa: E402
from minimateplus.decode_check import compare, sfm_side # noqa: E402
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
from scratch import decode_check_report as report # noqa: E402
RUNS_DIR = Path.home() / "dl2-archive" / "checker-runs"
_BIN = re.compile(r"^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$", re.I)
_MODEL = re.compile(r"^V\s+\S+\s+(.*)$")
_EPOCH = datetime(1985, 1, 1)
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]:
"""(basename, binary, XML report or None) for every Series 3 event file
under `bin_dir`, deduped by basename -- an ACH folder's Sent/ mirrors its
root."""
xmls = {p.name.upper(): p for p in Path(xml_dir).iterdir() if p.is_file()}
seen: dict[str, tuple[str, Path]] = {}
for root, _, files in os.walk(bin_dir):
for f in files:
if _BIN.match(f) and f.upper() not in seen:
seen[f.upper()] = (f, Path(root) / f)
out = []
for key in sorted(seen):
name, path = seen[key]
stem, ext = name.split(".")
out.append((name, path, xmls.get(f"{stem}_{ext}_XML.XML".upper())))
return out
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]:
"""The keys failures are grouped by -- all from the reference or the file."""
s = ref.scalars
m = _MODEL.match(s.get("Version", ""))
date = s.get("EventDate") or s.get("HistogramStartDate") or ""
return {
"model": m.group(1) if m else s.get("Version", "?"),
"serial": s.get("SerialNumber", "?"),
"type": s.get("EventType", "?"),
"year": date[:4] or "?",
"sample_rate": s.get("SampleRate", "?").split(" ")[0],
"range": s.get("GeoRange", "?"),
"mic_units": ref.event_units or "?",
"interval": s.get("IntervalSize", "-"),
"setup_standard": "yes" if b"Standard Recording Setup" in raw else "no",
}
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict:
"""One event: its grouping attrs and one row per compared field. A missing
reference or any failure is a single row, so a run never stops on one file."""
if xml_path is None:
return {"file": name, "attrs": {},
"results": [["event", "no_reference", None, None, "no XML report", None]]}
try:
raw = Path(bin_path).read_bytes()
ref = parse_xml_report_file(xml_path)
rows = compare(sfm_side(raw), ref, CARVEOUTS)
return {"file": name, "attrs": event_attrs(name, ref, raw),
"results": [[r.field, r.verdict, r.bw, r.sfm, r.detail, r.carveout] for r in rows]}
except Exception as exc: # noqa: BLE001 -- one bad file must not stop a run
return {"file": name, "attrs": {},
"results": [["event", "error", None, None, repr(exc)[:300], None]]}
def _check_pair(pair: tuple[str, str, Optional[str]]) -> dict:
return check_event(*pair)
def _quiet() -> None:
logging.disable(logging.CRITICAL)
def _filename_prefix(serial: str) -> str:
"""BE9441 -> K441: the prefix Blastware's filenames encode a serial as."""
num = int(re.sub(r"\D", "", serial))
return f"{chr(ord('B') + num // 1000)}{num % 1000:03d}"
def _filename_year(name: str) -> int:
stem, ext = name.upper().split(".")
return (_EPOCH + timedelta(seconds=int(stem[4:8], 36) * 1296 + int(ext[:2], 36))).year
def _git_head() -> Optional[str]:
try:
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=_REPO, capture_output=True,
text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return None
_SCOPE = ("bin_dir", "xml_dir", "serial", "year", "type", "field", "sample", "seed")
def _scope(args: dict) -> dict:
return {k: args.get(k) for k in _SCOPE}
def _previous_run(out_dir: Path, args: dict) -> Optional[Path]:
"""The newest other completed run (run.json written) of the same scope in
the runs folder -- only for runs kept there. A sample or a one-serial run
is no baseline for a full run, nor the other way round."""
if out_dir.parent.resolve() != RUNS_DIR.resolve():
return None
want = _scope(args)
for p in sorted(RUNS_DIR.iterdir(), reverse=True):
if not p.is_dir() or p.resolve() == out_dir.resolve():
continue
try:
if _scope(json.loads((p / "run.json").read_text())["args"]) == want:
return p
except (OSError, KeyError, ValueError):
continue
return None
def _print_one(name: str, pairs: list[tuple[str, Path, Optional[Path]]]) -> int:
"""--file: check one event and print its table; no run folder."""
match = [p for p in pairs if p[0].upper() == name.upper()]
if not match:
print(f"{name}: no such event file under the binaries folder", file=sys.stderr)
return 1
n, b, x = match[0]
ev = check_event(n, str(b), str(x) if x else None)
print(f"{n} {ev['attrs']}")
print(f"{'field':30s} {'verdict':12s} {'Blastware':30s} {'SFM':30s} detail")
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
note = f"{detail} {('[' + carveout + ']') if carveout else ''}".strip()
print(f"{field:30.30s} {verdict:12s} {str(bw):30.30s} {str(sfm):30.30s} {note}")
return 0
def main(argv: Optional[list[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("bin_dir", type=Path)
ap.add_argument("xml_dir", type=Path)
ap.add_argument("--out", type=Path, help=f"run folder (default {RUNS_DIR}/<timestamp>)")
ap.add_argument("--serial", action="append", default=[], help="e.g. BE9441; repeatable")
ap.add_argument("--year", action="append", type=int, default=[], help="event year; repeatable")
ap.add_argument("--type", choices=("W", "H"), help="waveforms or histograms only")
ap.add_argument("--field", action="append", default=[], help="keep result rows whose field starts with this")
ap.add_argument("--sample", type=int, help="check a random sample of N events")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
ap.add_argument("--file", help="check one event and print its table")
ap.add_argument("--compare-to", type=Path, help="an earlier run folder to diff against")
args = ap.parse_args(argv)
started = time.monotonic()
pairs = find_pairs(args.bin_dir, args.xml_dir)
if args.file:
return _print_one(args.file, pairs)
if args.serial:
prefixes = tuple(_filename_prefix(s) for s in args.serial)
pairs = [p for p in pairs if p[0].upper().startswith(prefixes)]
if args.year:
pairs = [p for p in pairs if _filename_year(p[0]) in args.year]
if args.type:
pairs = [p for p in pairs if p[0].upper().endswith(args.type)]
if args.sample is not None and args.sample < len(pairs):
pairs = sorted(random.Random(args.seed).sample(pairs, args.sample))
out_dir = args.out or RUNS_DIR / datetime.now().strftime("%Y%m%d-%H%M%S")
out_dir.mkdir(parents=True, exist_ok=True)
work = [(n, str(b), str(x) if x else None) for n, b, x in pairs]
_quiet()
if args.jobs <= 1:
results = map(_check_pair, work)
pool = None
else:
pool = ProcessPoolExecutor(args.jobs, initializer=_quiet)
results = pool.map(_check_pair, work, chunksize=64)
try:
with gzip.open(out_dir / "results.jsonl.gz", "wt", encoding="utf-8") as fh:
for ev in results:
if args.field:
ev["results"] = [r for r in ev["results"] if r[0].startswith(tuple(args.field))]
fh.write(json.dumps(ev) + "\n")
finally:
if pool is not None:
pool.shutdown()
run = {"args": {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()},
"commit": _git_head(), "events": len(work),
"seconds": round(time.monotonic() - started, 1)}
(out_dir / "run.json").write_text(json.dumps(run, indent=2))
agg = report.aggregate(out_dir / "results.jsonl.gz")
prev = args.compare_to or _previous_run(out_dir, run["args"])
if prev is not None and (prev / "results.jsonl.gz").exists():
chg = report.compare_runs(prev / "results.jsonl.gz", out_dir / "results.jsonl.gz")
report.write_changes(chg, out_dir / "changes.md")
agg["regressions"] = len(chg["regressions"])
report.write_summary(agg, out_dir / "summary.md")
report.write_details(agg, out_dir / "details.json")
print(out_dir)
return 0
if __name__ == "__main__":
sys.exit(main())
+235
View File
@@ -0,0 +1,235 @@
"""
Reports for the Series 3 decode checker (scratch/check_s3_decode.py).
From a run's results.jsonl.gz:
summary.md for Brian: per field, how many events got each verdict; how many
fields fully match; non-matches by event year; carve-out counts
details.json for Claude: each non-matching (field, verdict) with the event
attributes its failures concentrate in, and example events, each
with a command that re-runs just that event
Streams the results file and holds only counters and a capped example list.
"""
from __future__ import annotations
import gzip
import json
from collections import Counter, defaultdict
from pathlib import Path
from typing import Optional
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
_NOT_DONE = ("mismatch", "sfm_blank", "error")
_GROUP_SHARE = 0.10 # an attribute value is shown when it holds >= 10% of a failure
_CONCENTRATED = 0.95 # ... and flagged when nearly every compared event with it fails
_EXAMPLES = 8
_KEEP = 60 # candidate examples kept per failure while streaming
def _run_dirs(results_path: Path) -> tuple[str, str]:
run = results_path.parent / "run.json"
try:
args = json.loads(run.read_text())["args"]
return args["bin_dir"], args["xml_dir"]
except (OSError, KeyError, ValueError):
return "<bin_dir>", "<xml_dir>"
def aggregate(results_path: Path) -> dict:
fields: dict[str, Counter] = defaultdict(Counter)
by_year: dict[str, Counter] = defaultdict(Counter)
compared: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
failing: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
examples: dict[str, list] = defaultdict(list)
carveouts: Counter = Counter()
events = 0
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
for line in fh:
ev = json.loads(line)
events += 1
attrs = ev.get("attrs") or {}
covered = set()
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
fields[field][verdict] += 1
if carveout:
covered.add(carveout)
if verdict != "no_reference":
for a, v in attrs.items():
compared[field][a][str(v)] += 1
if verdict in ("match", "accepted", "no_reference"):
continue
key = f"{field}|{verdict}"
by_year[field][attrs.get("year", "?")] += 1
for a, v in attrs.items():
failing[key][a][str(v)] += 1
if len(examples[key]) < _KEEP:
examples[key].append({"file": ev["file"], "attrs": attrs, "bw": bw,
"sfm": sfm, "detail": detail})
carveouts.update(covered)
bin_dir, xml_dir = _run_dirs(Path(results_path))
return {"events": events, "fields": fields, "by_year": by_year, "compared": compared,
"failing": failing, "examples": examples, "carveouts": carveouts,
"bin_dir": bin_dir, "xml_dir": xml_dir, "regressions": None}
def _fully_matching(counts: Counter) -> bool:
"""Matched somewhere and failed nowhere. A field that only ever has no
reference (an always-empty element) has proven nothing."""
return (counts["match"] + counts["accepted"]) > 0 and not any(counts[v] for v in _NOT_DONE)
def _events_line(event: Counter) -> str:
def n(k: int, what: str) -> str:
return f"{k} event{'' if k == 1 else 's'} {what}"
return " · ".join(s for s in (n(event["no_reference"], "without a report") if event["no_reference"] else "",
n(event["error"], "that failed to check") if event["error"] else "") if s)
def write_summary(agg: dict, path: Path, title: Optional[str] = None) -> None:
# The "event" pseudo-field is a whole event with no report or a failure,
# not a field: it is reported on its own line.
fields = {f: c for f, c in agg["fields"].items() if f != "event"}
order = sorted(fields, key=lambda f: (-sum(fields[f][v] for v in _NOT_DONE), f))
done = sum(_fully_matching(fields[f]) for f in fields)
lines = [f"# Decode check — {title or Path(path).parent.name}", "",
f"{agg['events']} events · {done} of {len(fields)} fields fully matching", ""]
events = _events_line(agg["fields"].get("event", Counter()))
if events:
lines += [events, ""]
if agg.get("regressions") is not None:
n = agg["regressions"]
lines += [f"**{n} regressions** since the previous run" + (" — see changes.md" if n else ""), ""]
lines += ["| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---:|" * len(VERDICTS)]
lines += [f"| {f} | " + " | ".join(str(fields[f][v]) for v in VERDICTS) + " |" for f in order]
years = sorted({y for c in agg["by_year"].values() for y in c})
bad = [f for f in order if not _fully_matching(fields[f])]
if bad:
lines += ["", "## Not matching, by event year", "",
"| field | " + " | ".join(years) + " |", "|---|" + "---:|" * len(years)]
lines += [f"| {f} | " + " | ".join(str(agg["by_year"][f][y] or "") for y in years) + " |"
for f in bad]
if agg["carveouts"]:
lines += ["", "## Carve-outs (events covered)", "", "| carve-out | events |", "|---|---:|"]
lines += [f"| {c} | {n} |" for c, n in agg["carveouts"].most_common()]
Path(path).write_text("\n".join(lines) + "\n")
def write_details(agg: dict, path: Path) -> None:
def total_of(key: str) -> int:
field, verdict = key.split("|", 1)
return agg["fields"][field][verdict]
out = {}
for key in sorted(agg["examples"], key=lambda k: (-total_of(k), k)):
field = key.split("|", 1)[0]
total = total_of(key)
groups = {}
for attr, values in agg["failing"].get(key, {}).items():
rows = []
for value, n in values.most_common():
if n < _GROUP_SHARE * total:
break
seen = agg["compared"][field][attr][value]
rate = round(n / seen, 3) if seen else 1.0
rows.append({"value": value, "failing": n, "compared": seen, "rate": rate,
"concentrated": rate >= _CONCENTRATED})
if rows:
groups[attr] = rows
out[key] = {"total": total, "groups": groups,
"examples": _pick_examples(agg, key, groups)}
Path(path).write_text(json.dumps(out, indent=1))
def _pick_examples(agg: dict, key: str, groups: dict) -> list[dict]:
"""One example per top group value first, then the rest in run order."""
pool, picked = agg["examples"][key], []
for attr, rows in groups.items():
for row in rows:
ex = next((e for e in pool if str(e["attrs"].get(attr)) == row["value"]
and e not in picked), None)
if ex is not None and len(picked) < _EXAMPLES:
picked.append(ex)
picked += [e for e in pool if e not in picked][: _EXAMPLES - len(picked)]
rerun = f"python scratch/check_s3_decode.py {agg['bin_dir']} {agg['xml_dir']} --file "
return [{"file": e["file"], "bw": e["bw"], "sfm": e["sfm"], "detail": e["detail"],
"rerun": rerun + e["file"]} for e in picked]
_MATCHING = ("match", "accepted")
def _verdicts(results_path: Path) -> tuple[dict[tuple[str, str], str], set[str], set[str]]:
"""(file, field) -> verdict, every file in the run, and the files whose
check failed outright (their field rows collapse to one "event" error)."""
out, files, errored = {}, set(), set()
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
for line in fh:
ev = json.loads(line)
files.add(ev["file"])
for row in ev["results"]:
out[(ev["file"], row[0])] = row[1]
if row[0] == "event" and row[1] == "error":
errored.add(ev["file"])
return out, files, errored
def compare_runs(prev_results: Path, cur_results: Path) -> dict:
"""What changed between two runs, over the events both checked: per-field
verdict counts before and after, every (event, field) that matched and no
longer does -- including events that now fail outright -- and how many
non-matches now match."""
before, files_before, _ = _verdicts(prev_results)
after, files_after, errored = _verdicts(cur_results)
shared = files_before & files_after
fields: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0]))
for (f, field), v in before.items():
if f in shared:
fields[field][v][0] += 1
for (f, field), v in after.items():
if f in shared:
fields[field][v][1] += 1
regressions = []
for (f, field), v in sorted(before.items()):
if v not in _MATCHING or f not in shared:
continue
now = after.get((f, field), "error" if f in errored else "missing")
if now not in _MATCHING:
regressions.append({"file": f, "field": field, "before": v, "after": now})
fixed = sum(1 for k, v in after.items()
if k[0] in shared and v in _MATCHING and before.get(k) not in (None,) + _MATCHING)
return {"fields": {f: dict(c) for f, c in fields.items()}, "regressions": regressions,
"fixed": fixed, "shared_events": len(shared), "prev": str(prev_results),
"prev_scope": _scope_of(Path(prev_results).parent)}
def _scope_of(run_dir: Path) -> Optional[dict]:
try:
args = json.loads((run_dir / "run.json").read_text())["args"]
except (OSError, KeyError, ValueError):
return None
return {k: args.get(k) for k in ("serial", "year", "type", "field", "sample", "seed") if args.get(k)}
def write_changes(chg: dict, path: Path) -> None:
regs = chg["regressions"]
scope = chg.get("prev_scope")
lines = [f"# Changes since {chg.get('prev', 'the previous run')}", "",
f"Previous run's scope: {scope or 'all events'} · compared over "
f"{chg.get('shared_events', '?')} events both runs checked", "",
f"{len(regs)} regressions · {chg['fixed']} fixed", ""]
if regs:
lines += ["## Regressions (matched before, not now)", "", "| file | field | now |", "|---|---|---|"]
lines += [f"| {r['file']} | {r['field']} | {r['after']} |" for r in regs[:500]]
if len(regs) > 500:
lines.append(f"| … {len(regs) - 500} more | | |")
lines.append("")
moved = {f: c for f, c in chg["fields"].items() if any(b != a for b, a in c.values())}
if moved:
lines += ["## Fields whose counts moved (before → after)", "",
"| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---|" * len(VERDICTS)]
for f in sorted(moved):
lines.append(f"| {f} | " + " | ".join(
f"{moved[f].get(v, [0, 0])[0]} → {moved[f].get(v, [0, 0])[1]}" for v in VERDICTS) + " |")
Path(path).write_text("\n".join(lines) + "\n")
-360
View File
@@ -1,360 +0,0 @@
"""
scratch/next_experiment_skeleton.py — segment-channel scoring analyzer.
This is the suggested NEXT EXPERIMENT for cracking the waveform body codec.
The goal is to figure out what segments 1+ contain, since segment 0 = Tran
is solved but multi-segment continuation diverges from truth at sample ~512.
────────────────────────────────────────────────────────────────────────────
The hypothesis to test
────────────────────────────────────────────────────────────────────────────
Segments rotate through channels:
segment 0 → Tran samples 0..509
segment 1 → Vert samples 0..507
segment 2 → Long samples 0..507
segment 3 → Mic samples 0..507
segment 4 → Tran samples 510..N (continuation)
...
This would explain why segment 0 works perfectly (it's pure Tran) and why
applying segment 1's blocks as Tran continuation gives wrong values
(it's actually Vert).
────────────────────────────────────────────────────────────────────────────
What the analyzer should do
────────────────────────────────────────────────────────────────────────────
For each segment in each fixture event:
1. Run the segment-0 block-walker + RLE decode (the same algorithm that
``decode_tran_initial`` uses) over the segment's blocks. Start from
some anchor value and produce a cumulative trajectory of length =
number-of-deltas-in-segment.
2. For each candidate channel C ∈ {Tran, Vert, Long, MicL}:
For each candidate anchor location in the segment-header payload
(try [0:2], [2:4], [4:6], [14:16], [16:18] as int16 BE):
Compare the decoded trajectory against truth[C] starting from
the segment's first sample index.
Score = number of matches (or sum of squared errors).
3. Report the best (channel, anchor-location) combination per segment.
If the rotation hypothesis is correct, you'll see:
segment 0 → best score for (Tran, preamble bytes [3:5]) ✓ already known
segment 1 → best score for (Vert, <some-header-byte>)
segment 2 → best score for (Long, <some-header-byte>)
segment 3 → best score for (MicL, <some-header-byte>)
segment 4 → best score for (Tran, continuing from segment 0's end)
If the rotation hypothesis is NOT correct, the scorer will at least narrow
down what segment 1 actually carries. Maybe channels interleave at finer
granularity, or maybe segments alternate by something other than channel.
────────────────────────────────────────────────────────────────────────────
Why this is a scoring analyzer, not a hand-written decoder
────────────────────────────────────────────────────────────────────────────
Direct hand-coding ("assume segment 1 is Vert with anchor at byte X") gets
stuck when the assumption is wrong because the failure mode is silent —
you get plausible-looking-but-wrong samples and have to manually diff
against truth to debug.
The scorer is brute-force but cheap: every fixture event × every segment ×
4 channels × 5 anchor-byte candidates is only ~hundreds of comparisons.
The winning combination jumps out by score.
────────────────────────────────────────────────────────────────────────────
Skeleton
────────────────────────────────────────────────────────────────────────────
"""
from __future__ import annotations
import os
import re
import sys
from dataclasses import dataclass
from typing import List, Optional, Tuple
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from minimateplus.waveform_codec import walk_body, find_data_start, WaveformBlock
# ── Reusable pieces ──────────────────────────────────────────────────────────
CHANNELS = ("Tran", "Vert", "Long", "MicL")
LSB_INV = 200 # 1 in/s / 0.005 in/s/LSB; multiply BW-export floats by this
# to get 16-count units (the body's native quantization).
@dataclass
class FixtureEvent:
name: str # e.g. "M529LL1A.SP0"
bin_path: str
txt_path: str
body: bytes
truth: dict # {channel: list of int16-quantized samples}
blocks: List[WaveformBlock]
segment_starts: List[int] # block indices of each 40 02 segment header
segment_sample_starts: List[int] # for each segment, the truth sample index it starts at
def s4(n: int) -> int:
"""4-bit signed nibble decode."""
return n if n < 8 else n - 16
def i8(b: int) -> int:
"""int8 reinterpret of unsigned byte."""
return b if b < 128 else b - 256
def load_fixture(name: str) -> FixtureEvent:
"""Load a fixture event with its truth values and parsed block stream."""
# Find the fixture (search both subdirs of tests/fixtures/).
base = os.path.join(os.path.dirname(__file__), "..", "tests", "fixtures")
candidates = [
os.path.join(base, "5-11-26", name),
os.path.join(base, "decode-re-5-8-26", "event-a", name), # not used directly
]
bin_path = next((c for c in candidates if os.path.exists(c)), None)
if bin_path is None:
# Try a glob walk for the 5-8 fixtures (they're in subdirs).
for root, _, files in os.walk(base):
if name in files:
bin_path = os.path.join(root, name)
break
if bin_path is None:
raise FileNotFoundError(name)
txt_path = bin_path + ".TXT"
with open(bin_path, "rb") as f:
raw = f.read()
body = raw[43:-26]
truth = _parse_txt(txt_path)
blocks = walk_body(body, find_data_start(body))
seg_idx = [i for i, b in enumerate(blocks) if b.tag_hi == 0x40]
# Segment 0 starts at sample 0; subsequent segments start at the
# cumulative sample count from previous segment(s). Tran's segment 0
# is N samples; if rotation hypothesis is correct, segment 1's data
# starts at sample 0 for a *different* channel. The analyzer should
# try both "continues from previous segment" and "starts at sample 0
# of a different channel."
seg_sample_starts = _compute_segment_sample_starts(blocks, seg_idx)
return FixtureEvent(
name=name, bin_path=bin_path, txt_path=txt_path,
body=body, truth=truth, blocks=blocks,
segment_starts=seg_idx, segment_sample_starts=seg_sample_starts,
)
def _parse_txt(path: str) -> dict:
"""Parse BW ASCII TXT export into {channel: [int_samples_in_16_count_units]}."""
with open(path, "r", encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
header_idx = next(
(i for i, l in enumerate(lines)
if all(c in l for c in CHANNELS)),
None,
)
if header_idx is None:
return {ch: [] for ch in CHANNELS}
out = {ch: [] for ch in CHANNELS}
for line in lines[header_idx + 1:]:
parts = re.split(r"\s+", line.strip())
if len(parts) < 4:
continue
try:
vals = [float(p) for p in parts[:4]]
except ValueError:
continue
for ch, v in zip(CHANNELS, vals):
# Multiply by LSB_INV; geo channels are in in/s, MicL is in dB(L)
# (which doesn't quantize the same way — leaving raw for MicL is fine,
# the scorer should treat MicL specially).
out[ch].append(round(v * LSB_INV) if ch != "MicL" else v)
return out
def _compute_segment_sample_starts(
blocks: List[WaveformBlock], seg_idx: List[int]
) -> List[int]:
"""Cumulative sample-count up to each segment header (if all blocks treated
as Tran continuation). Useful as one candidate for segment-1-Tran tests.
The scorer should ALSO try "segment 1 starts at sample 0 of a new channel"
as the rotation hypothesis predicts.
"""
starts = []
cum = 2 # T[0] + T[1] from preamble
for i, b in enumerate(blocks):
if i in seg_idx:
starts.append(cum)
if b.tag_hi == 0x10:
cum += b.tag_lo
elif b.tag_hi == 0x20:
cum += b.tag_lo
elif b.tag_hi == 0x00:
cum += b.tag_lo
# 30 NN and 40 02 don't contribute samples (for this hypothesis)
return starts
# ── The core algorithm: decode a segment's blocks as deltas ─────────────────
def decode_segment_as_channel(
blocks: List[WaveformBlock],
seg_start_block_idx: int,
seg_end_block_idx: int,
anchor: int,
) -> List[int]:
"""Apply the segment-0 codec rules to a range of blocks, starting from *anchor*.
Returns a list of cumulative sample values (one per delta). Does NOT include
the anchor itself in the output — the first returned value is anchor + first_delta.
"""
out = []
cur = anchor
for bi in range(seg_start_block_idx, seg_end_block_idx):
blk = blocks[bi]
if blk.tag_hi == 0x10:
for byte in blk.data:
for nib in ((byte >> 4) & 0xF, byte & 0xF):
cur += s4(nib)
out.append(cur)
elif blk.tag_hi == 0x20:
for byte in blk.data:
cur += i8(byte)
out.append(cur)
elif blk.tag_hi == 0x00:
for _ in range(blk.tag_lo):
out.append(cur)
# 30 NN: skip (content unknown)
# 40 02: shouldn't appear in segment data (it's the segment header)
return out
def score_against_truth(
decoded: List[int],
truth: List[int],
truth_start: int,
) -> Tuple[int, int]:
"""Compare *decoded* to truth[truth_start : truth_start + len(decoded)].
Returns (n_matches, n_compared).
"""
n = min(len(decoded), len(truth) - truth_start)
if n <= 0:
return (0, 0)
matches = sum(1 for i in range(n) if decoded[i] == truth[truth_start + i])
return (matches, n)
# ── TODO for the next pass ──────────────────────────────────────────────────
def score_segment_against_all_channels(
event: FixtureEvent,
segment_index: int,
) -> List[Tuple[str, int, int, int]]:
"""For segment *segment_index* of *event*, find the best (channel, start_sample)
fit.
For each candidate channel C and each candidate starting truth-sample index s,
we pick the anchor that makes the FIRST decoded value match truth[C][s], then
score the remaining decoded values against truth[C][s+1 : s+N].
Returns rows of (channel_name, start_sample, n_matches, n_compared)
sorted by match-count descending.
"""
# Block range of this segment: from the segment header (inclusive) up to
# the next segment header (exclusive), or end-of-blocks.
seg_header_idx = event.segment_starts[segment_index]
next_header_idx = (
event.segment_starts[segment_index + 1]
if segment_index + 1 < len(event.segment_starts)
else len(event.blocks)
)
# Decode the segment's data blocks (skip the segment-header block itself).
# Use anchor=0 — we'll re-anchor when scoring against each channel.
deltas_trajectory = decode_segment_as_channel(
event.blocks, seg_header_idx + 1, next_header_idx, anchor=0
)
if not deltas_trajectory:
return []
n = len(deltas_trajectory)
results = []
for ch in ("Tran", "Vert", "Long"):
truth = event.truth.get(ch)
if not truth or len(truth) < n + 1:
continue
# For each candidate starting sample s in truth, check if applying
# the deltas starting from truth[s] reproduces truth[s+1:s+n+1].
best = (0, -1)
for s in range(len(truth) - n):
anchor = truth[s]
offset = anchor - deltas_trajectory[0] + truth[s + 1] - anchor
# Recompute: trajectory[i] = anchor + cumulative_delta_through_i
# but we already have deltas_trajectory computed from anchor=0,
# so trajectory_relative[i] = anchor + deltas_trajectory[i].
matches = 0
for i in range(n):
if truth[s + i + 1] == anchor + deltas_trajectory[i]:
matches += 1
# Note: we could break early on first mismatch for "matches start",
# but counting total matches gives a more robust score.
if matches > best[0]:
best = (matches, s)
results.append((ch, best[1], best[0], n))
results.sort(key=lambda r: -r[2])
return results
# ── Driver ──────────────────────────────────────────────────────────────────
def main():
"""Run the analyzer on all loud-bundle events and print best scores."""
events = ["M529LL1A.SP0", "M529LL1A.SS0", "M529LL1A.SV0",
"M529LL1L.JQ0", "M529LL1L.V70"]
for name in events:
try:
event = load_fixture(name)
except FileNotFoundError:
print(f"{name}: fixture not found")
continue
print(f"\n=== {name} ===")
print(f" body bytes: {len(event.body)}")
print(f" blocks: {len(event.blocks)}")
print(f" segments: {len(event.segment_starts)}")
print(f" segment sample-starts (if all blocks are 1 channel):")
for si, sample_start in enumerate(event.segment_sample_starts):
print(f" seg {si}: sample {sample_start}")
for si in range(len(event.segment_starts)):
results = score_segment_against_all_channels(event, si)
if not results:
print(f" seg {si}: (no scorable data)")
continue
tag = "✓" if results[0][2] / max(results[0][3], 1) > 0.9 else " "
top = results[0]
print(f" seg {si}: best fit {tag} = {top[0]:<5} "
f"starting at sample {top[1]:>5}, {top[2]:>4}/{top[3]:<4} match"
+ (f" (next: {results[1][0]} @{results[1][1]} {results[1][2]}/{results[1][3]})"
if len(results) > 1 else ""))
if __name__ == "__main__":
main()
+275 -275
View File
@@ -1,275 +1,275 @@
event_id,serial,timestamp,filename,channel,offset_ips,peak_ips,mean_over_peak,trigger_level_ips,already_flagged_ft
1e7a7808-034c-423b-80e9-d6788da80993,BE18438,2025-11-15T08:57:40,T438LBX4.W40W,Vert,0.2722,0.2930,0.929,0.2,0
346e383f-c5a1-41d1-b972-3d652e599d39,BE18438,2025-11-15T09:13:15,T438LBX5.M30W,Vert,0.2747,0.2930,0.938,0.2,0
45ef3023-22c5-44a8-a606-a0900bc17861,BE18438,2025-11-15T09:16:13,T438LBX5.R10W,Vert,0.2929,0.3027,0.967,0.2,0
1cbcd2aa-ec55-4e2f-af42-7178f26cc6a1,BE18438,2025-11-15T09:19:29,T438LBX5.WH0W,Vert,0.2816,0.2979,0.945,0.2,0
caf43634-4528-4fd5-9674-5f4f563661c0,BE18438,2025-11-15T09:22:32,T438LBX6.1K0W,Vert,0.2883,0.2930,0.984,0.2,0
456ae646-c834-4e5c-82f1-7df18b3440a1,BE18438,2025-11-15T09:25:31,T438LBX6.6J0W,Vert,0.3189,0.3223,0.989,0.2,0
afb91ba2-351b-42a0-b33f-acebd5f1829d,BE18438,2025-11-15T09:28:29,T438LBX6.BH0W,Vert,0.3057,0.3076,0.994,0.2,0
39847146-3537-4300-943d-01c0c771e9cd,BE18438,2025-11-15T09:31:26,T438LBX6.GE0W,Vert,0.3225,0.3271,0.986,0.2,0
e47335c1-fc3f-4c90-88c6-8edd0f296ce4,BE18438,2025-11-15T09:34:24,T438LBX6.LC0W,Vert,0.3275,0.3320,0.986,0.2,0
25b6eda6-ba98-422f-8834-94b6cbe34971,BE18438,2025-11-15T09:37:22,T438LBX6.QA0W,Vert,0.3398,0.3418,0.994,0.2,0
7af99377-e47f-4914-8e91-ac7f7f50b8c6,BE18438,2025-11-15T09:40:20,T438LBX6.V80W,Vert,0.3515,0.3564,0.986,0.2,0
c4330605-c257-49ef-aede-20deb641e7d7,BE18438,2025-11-15T10:09:48,T438LBX8.8C0W,Vert,0.3605,0.3955,0.912,0.2,0
b665caf9-64ee-4352-a391-60c1ddeebc1e,BE18438,2026-02-25T10:58:04,T438LH66.GS0W,Vert,0.1803,0.1953,0.923,0.2,0
3b0c32c3-fd16-4b83-9917-942a56dea168,BE18438,2026-02-25T18:12:04,T438LH6Q.K40W,Vert,0.1869,0.1953,0.957,0.2,0
ca66e601-d10f-4424-9c26-08a688e7b08c,BE18438,2026-02-25T18:17:16,T438LH6Q.SS0W,Vert,0.1870,0.1953,0.958,0.2,0
31aa30ba-eb0a-49a9-98ca-c77d2cc31275,BE18438,2026-02-25T18:21:11,T438LH6Q.ZB0W,Vert,0.1868,0.1953,0.956,0.2,0
fdb55a93-fc91-4fdf-a7f4-fdd1a6b48f59,BE18438,2026-02-25T18:26:27,T438LH6R.830W,Vert,0.1893,0.1953,0.969,0.2,0
cbd718d7-2378-4d74-8656-842f229d19a8,BE18438,2026-02-25T18:33:25,T438LH6R.JP0W,Vert,0.1887,0.1953,0.966,0.2,0
bfaf58ec-6163-47eb-9d2a-70da880bd948,BE18438,2026-02-25T18:37:48,T438LH6R.R00W,Vert,0.1872,0.1953,0.959,0.2,0
ddaa530b-886e-4415-b93a-f4ebf4c4a882,BE18438,2026-02-25T18:59:54,T438LH6S.RU0W,Vert,0.1874,0.1953,0.959,0.2,0
57f15284-ab69-48fc-9660-8c347c80c681,BE18438,2026-02-25T19:15:58,T438LH6T.IM0W,Vert,0.1873,0.1953,0.959,0.2,0
03715718-7aa8-4e1d-9b0b-c2ab75fc1975,BE18438,2026-02-25T19:19:58,T438LH6T.PA0W,Vert,0.1891,0.1953,0.968,0.2,0
9f921cd5-1bf9-4713-aef6-41e7f780eff1,BE18438,2026-02-25T19:24:02,T438LH6T.W20W,Vert,0.1871,0.1953,0.958,0.2,0
44994949-58d4-44fa-bd78-ed75b8acc667,BE18438,2026-02-25T19:44:57,T438LH6U.UX0W,Vert,0.1877,0.1953,0.961,0.2,0
c4be01c3-1001-4e17-aecd-d6d26dbb09f3,BE18438,2026-02-25T19:49:19,T438LH6V.270W,Vert,0.1884,0.1953,0.964,0.2,0
3db004e6-ee34-43c5-ae8e-f22894ead5d0,BE18438,2026-02-25T20:08:22,T438LH6V.XY0W,Vert,0.1878,0.1953,0.962,0.2,0
d276ae48-0434-41e5-af43-e0fb366acf11,BE18438,2026-02-25T20:11:33,T438LH6W.390W,Vert,0.1880,0.1953,0.963,0.2,0
c027dc12-88fd-4a45-872b-a6a945f2008e,BE18438,2026-02-25T20:14:35,T438LH6W.8B0W,Vert,0.1874,0.1953,0.959,0.2,0
9665bc3a-3d08-4852-b008-37ef8bfd0023,BE18438,2026-02-25T20:18:51,T438LH6W.FF0W,Vert,0.1884,0.1953,0.965,0.2,0
5fb5a05e-d7e2-4268-9b85-cfe8d82aa6c9,BE18438,2026-02-25T20:29:50,T438LH6W.XQ0W,Vert,0.1890,0.1953,0.968,0.2,0
57ec0b10-9324-4459-a07e-0c8532b8928f,BE18438,2026-02-25T20:35:39,T438LH6X.7F0W,Vert,0.1889,0.1953,0.967,0.2,0
ac86f73f-1174-4fae-a206-ecdcb73e1ffc,BE18438,2026-02-25T20:39:12,T438LH6X.DC0W,Vert,0.1887,0.1953,0.966,0.2,0
dcf25ddd-9cf0-41c1-b109-f3ef2e490ce5,BE18438,2026-02-25T20:43:41,T438LH6X.KT0W,Vert,0.1871,0.1953,0.958,0.2,0
aa79bbdd-2392-4ef6-8a5c-873a9f72746d,BE18438,2026-02-25T20:46:51,T438LH6X.Q30W,Vert,0.1877,0.1953,0.961,0.2,0
ad46d1ce-b417-4c8c-b029-bb3b008ba809,BE18438,2026-02-25T20:53:33,T438LH6Y.190W,Vert,0.1882,0.1953,0.964,0.2,0
3d3a8f34-86a7-4d70-a7e8-fa768a723325,BE18438,2026-02-26T07:03:39,T438LH7Q.A30W,Vert,0.1809,0.1953,0.926,0.2,0
7817525f-dc3d-4f5e-b2cb-5af9ca12ede8,BE18438,2026-02-26T07:09:42,T438LH7Q.K60W,Vert,0.1814,0.1953,0.929,0.2,0
a2091302-0b34-46c1-ab83-174be2b59bcf,BE18438,2026-02-26T13:12:35,T438LH87.CZ0W,Vert,0.1896,0.1953,0.971,0.2,0
e1c0c9de-a900-479f-9572-9675b13296a9,BE18438,2026-02-26T13:24:46,T438LH87.XA0W,Vert,0.2237,0.2588,0.864,0.2,0
76a6dc6b-88e1-434b-a137-f5e9b63f248e,BE18438,2026-02-26T13:27:43,T438LH88.270W,Vert,0.3185,0.3223,0.988,0.2,0
281b508b-7982-4668-86af-9b0b28be608a,BE18438,2026-02-26T13:30:36,T438LH88.700W,Vert,0.3263,0.3320,0.983,0.2,0
68bbaf77-bb23-40fd-94f9-f928728d90dc,BE18438,2026-02-26T13:33:28,T438LH88.BS0W,Vert,0.3207,0.3271,0.980,0.2,0
5c975640-6ff1-441a-aa11-41642f6a6b31,BE18438,2026-02-26T13:36:21,T438LH88.GL0W,Vert,0.3261,0.3320,0.982,0.2,0
dea248ac-1124-4bba-b054-953f86c852b2,BE18438,2026-02-26T13:40:34,T438LH88.NM0W,Vert,0.3271,0.3320,0.985,0.2,0
4e463201-f008-41ad-9c52-11fcc3d93095,BE18438,2026-02-26T13:43:29,T438LH88.SH0W,Vert,0.3357,0.3418,0.982,0.2,0
507262c5-d58f-4a05-a6a3-a6cbb5b4de20,BE18438,2026-02-26T13:46:24,T438LH88.XC0W,Vert,0.3372,0.3418,0.987,0.2,0
4c2d8ee8-842f-4e44-9e03-ff34d26e4fdb,BE18438,2026-02-26T13:49:17,T438LH89.250W,Vert,0.3253,0.3320,0.980,0.2,0
b184b112-603f-44f4-ae97-087493fbd8ce,BE18438,2026-02-26T13:52:10,T438LH89.6Y0W,Vert,0.3321,0.3369,0.986,0.2,0
2ff1a552-5a2e-4396-9083-b9c8d334eed7,BE18438,2026-02-26T13:55:04,T438LH89.BS0W,Vert,0.3378,0.3418,0.988,0.2,0
928e21a7-1990-4792-803e-58014d8140ce,BE18438,2026-02-26T13:57:57,T438LH89.GL0W,Vert,0.3341,0.3369,0.992,0.2,0
f521b5db-6100-41e6-954e-0abdbf9660c1,BE18438,2026-02-26T14:00:51,T438LH89.LF0W,Vert,0.3421,0.3467,0.987,0.2,0
efba962f-e511-41ef-9fc5-313f202a9d96,BE18438,2026-02-26T14:03:46,T438LH89.QA0W,Vert,0.3506,0.3564,0.984,0.2,0
0b51e273-8d10-4494-bda6-8c75eaeec66f,BE18438,2026-02-26T14:06:41,T438LH89.V50W,Vert,0.3448,0.3516,0.981,0.2,0
6d46e4ee-1647-4169-b6b2-33da32240eb9,BE18438,2026-02-26T14:09:35,T438LH89.ZZ0W,Vert,0.3463,0.3516,0.985,0.2,0
1ca294cd-4dc2-41fb-9374-e277d4550761,BE18438,2026-02-26T14:12:28,T438LH8A.4S0W,Vert,0.3442,0.3467,0.993,0.2,0
7b683dcf-1aed-4d9b-be1e-b10f92374398,BE18438,2026-02-26T14:15:23,T438LH8A.9N0W,Vert,0.3486,0.3516,0.992,0.2,0
2b5cb8e7-c947-4914-bcb5-504f74603547,BE18438,2026-02-26T14:18:21,T438LH8A.EL0W,Vert,0.3519,0.3613,0.974,0.2,0
5ea3a6bf-10de-4911-aedc-66daecf86b76,BE18438,2026-02-26T14:21:16,T438LH8A.JG0W,Vert,0.3460,0.3564,0.971,0.2,0
d93be7f5-39ec-45fd-9949-fa531f2f9d34,BE18438,2026-02-26T14:24:13,T438LH8A.OD0W,Vert,0.3457,0.3516,0.983,0.2,0
cfa113f2-8cee-4a1d-b1e7-0e936fa771e2,BE18438,2026-02-26T14:28:21,T438LH8A.V90W,Vert,0.3485,0.3564,0.978,0.2,0
46d322ac-38cb-4c99-a4c2-9e9d7ad06171,BE18438,2026-02-26T14:31:17,T438LH8B.050W,Vert,0.3367,0.3467,0.971,0.2,0
42500a83-bd67-4deb-8bb2-963ee2b8a7ce,BE18438,2026-02-26T14:34:11,T438LH8B.4Z0W,Vert,0.3365,0.3516,0.957,0.2,0
3ccf6bda-2e88-473c-951d-9ea86d0d9363,BE18438,2026-02-26T14:37:05,T438LH8B.9T0W,Vert,0.3472,0.3564,0.974,0.2,0
9050487d-d238-4631-b8e1-5a693a026542,BE18438,2026-02-26T14:39:58,T438LH8B.EM0W,Vert,0.3420,0.3564,0.959,0.2,0
e62989e4-a326-4bae-8d47-a8becee96462,BE18438,2026-02-26T14:42:52,T438LH8B.JG0W,Vert,0.3430,0.3564,0.962,0.2,0
f0e30fab-dc57-4189-8439-48df17007a2c,BE18438,2026-02-26T14:45:46,T438LH8B.OA0W,Vert,0.3389,0.3516,0.964,0.2,0
03e1ca09-78df-4c6f-9915-0b6e4f2141d2,BE18438,2026-02-26T14:48:43,T438LH8B.T70W,Vert,0.3449,0.3564,0.968,0.2,0
945d39f7-1b98-4a1f-80a8-6a18fd9df25f,BE18438,2026-02-26T14:51:37,T438LH8B.Y10W,Vert,0.3522,0.3613,0.975,0.2,0
d27eb2e3-e313-4125-98f4-f9d6d3737d28,BE18438,2026-02-26T14:54:32,T438LH8C.2W0W,Vert,0.3502,0.3613,0.969,0.2,0
916901cb-ebea-441e-a2a1-40f4e49f32f4,BE18438,2026-02-26T14:57:25,T438LH8C.7P0W,Vert,0.3524,0.3662,0.962,0.2,0
5d8d7e29-fdbb-4fa3-bd25-506c9352a354,BE18438,2026-02-26T15:01:35,T438LH8C.EN0W,Vert,0.3530,0.3613,0.977,0.2,0
c6c7a3af-b03b-43dc-97de-024f8e09b62f,BE18438,2026-02-26T15:04:27,T438LH8C.JF0W,Vert,0.3514,0.3613,0.973,0.2,0
b6856898-3d10-4967-9577-7f17902f77ea,BE18438,2026-02-26T15:11:34,T438LH8C.VA0W,Vert,0.3566,0.3613,0.987,0.2,0
7a4802f6-621e-4230-8d8c-d7f0c9a65bf2,BE18438,2026-02-26T15:14:24,T438LH8D.000W,Vert,0.3594,0.3711,0.968,0.2,0
79f38b7e-ec56-417e-943a-8c944252c2b8,BE18438,2026-02-26T15:18:32,T438LH8D.6W0W,Vert,0.3550,0.3613,0.983,0.2,0
1b4190c4-0d54-48ba-8ff5-8ddb0eb91e50,BE18438,2026-02-26T15:22:22,T438LH8D.DA0W,Vert,0.3571,0.3613,0.988,0.2,0
de57b5ae-a3a1-4ede-9d2b-3e87bfb3fd19,BE9558,2026-04-14T11:16:32,K558LJN3.BK0W,Tran,0.3448,0.3662,0.942,0.2,0
43afeaf5-02ec-41f6-9e23-0c9772821ed4,BE9558,2026-04-14T11:27:15,K558LJN3.TF0W,Tran,0.3094,0.3223,0.960,0.2,0
8123c0ef-84c9-4f6c-8d82-9dc32e2e470d,BE9558,2026-04-14T14:45:30,K558LJNC.ZU0W,Tran,0.2721,0.3564,0.763,0.2,0
8c787af3-596e-411b-9e10-29485fa5114f,BE9558,2026-04-29T16:18:47,K558LKF9.BB0W,Tran,0.2943,0.3027,0.972,0.2,0
431928ff-b4c4-4caa-b933-acc917f3717c,BE9558,2026-05-04T15:02:30,K558LKOF.460W,Tran,0.4364,0.5225,0.835,0.2,0
6c3c07f8-c36a-4493-acce-7441c9d22cec,BE9558,2026-05-15T08:50:06,K558LL8B.7I0W,Long,0.2892,0.2930,0.987,0.2,0
13c268df-b652-422e-a642-6453f6a314aa,BE9558,2026-05-15T10:18:34,K558LL8F.AY0W,Long,0.2907,0.2979,0.976,0.2,0
9b0d0871-8810-467d-806a-5bbfa4e667fe,BE9558,2026-05-15T15:52:00,K558LL8U.QO0W,Long,0.2659,0.2979,0.893,0.2,0
092640f9-a944-48b7-b872-364d75c2c5e7,BE9558,2026-05-15T16:13:12,K558LL8V.Q00W,Long,0.2428,0.2979,0.815,0.2,0
0573741a-96ab-4b36-af7a-b5bc11a79009,BE9558,2026-05-16T03:23:26,K558LL9Q.R20W,Long,0.2861,0.2930,0.976,0.2,0
321f03ea-6696-47de-ad46-2be43d4d6cae,BE9558,2026-05-16T03:30:49,K558LL9R.3D0W,Long,0.2886,0.2930,0.985,0.2,0
cc423a6a-3e3c-466a-b39c-6146ca7f34c8,BE9558,2026-05-16T03:33:55,K558LL9R.8J0W,Long,0.2880,0.2881,1.000,0.2,0
efa52a14-cc68-4bea-aab4-4ee3a3cbff3a,BE9558,2026-05-16T03:36:55,K558LL9R.DJ0W,Long,0.2890,0.2930,0.986,0.2,0
92895bfe-122f-4cdc-bd3d-40609633d278,BE9558,2026-05-16T03:43:41,K558LL9R.OT0W,Long,0.2880,0.2881,1.000,0.2,0
2a4c81db-2307-44e5-9b27-d5154d98e38d,BE9558,2026-05-16T03:46:36,K558LL9R.TO0W,Long,0.2921,0.2979,0.981,0.2,0
656b0fdc-e275-4c9c-8936-9eee267ea04e,BE9558,2026-05-16T03:49:28,K558LL9R.YG0W,Long,0.2966,0.2979,0.996,0.2,0
3b9989ae-e0f2-4652-9724-c145603543d2,BE9558,2026-05-16T03:52:29,K558LL9S.3H0W,Long,0.2880,0.2930,0.983,0.2,0
837d0d84-d609-4f4a-b542-b7e2b064ea22,BE9558,2026-05-16T03:56:32,K558LL9S.A80W,Long,0.2880,0.2930,0.983,0.2,0
affcb008-ab99-4bc5-8f35-83dbe620499d,BE9558,2026-05-16T04:02:50,K558LL9S.KQ0W,Long,0.2896,0.2930,0.989,0.2,0
e1f1c6d2-545c-451f-9018-714d52e20a05,BE9558,2026-05-16T04:05:47,K558LL9S.PN0W,Long,0.3024,0.3076,0.983,0.2,0
93ef80f1-7e83-4703-a0f9-89bbfeeae6c3,BE9558,2026-05-16T04:08:41,K558LL9S.UH0W,Long,0.2976,0.2979,0.999,0.2,0
5c118ca9-fc37-4080-876d-b3f57ce0b121,BE9558,2026-05-16T04:11:42,K558LL9S.ZI0W,Long,0.2881,0.2930,0.983,0.2,0
d98b2eaa-7763-4c78-88fb-c21195cb9978,BE9558,2026-05-16T04:14:38,K558LL9T.4E0W,Long,0.2898,0.2930,0.989,0.2,0
6a146a01-0d02-4413-b231-ecb4a6fde776,BE9558,2026-05-16T04:17:35,K558LL9T.9B0W,Long,0.2880,0.2930,0.983,0.2,0
f6587a55-27e3-454f-997e-57e7516a296c,BE9558,2026-05-16T04:20:32,K558LL9T.E80W,Long,0.3046,0.3076,0.990,0.2,0
1fb48250-2214-41e6-92cb-362aff1ba62b,BE9558,2026-05-16T04:26:05,K558LL9T.NH0W,Long,0.2876,0.2930,0.982,0.2,0
2f4f3d06-1189-4e28-a1ac-5454ea586a0c,BE9558,2026-05-16T04:59:47,K558LL9V.7N0W,Long,0.2961,0.3027,0.978,0.2,0
62b7bdab-b744-41e4-8d0e-c9141b9d4821,BE9558,2026-05-16T05:02:46,K558LL9V.CM0W,Long,0.2903,0.2930,0.991,0.2,0
cadcb6dc-74c0-48b5-974c-87bb7a57816c,BE9558,2026-05-16T05:05:43,K558LL9V.HJ0W,Long,0.3090,0.3125,0.989,0.2,0
a0235177-be5a-4f11-b741-c65744698e5b,BE9558,2026-05-16T05:08:35,K558LL9V.MB0W,Long,0.3167,0.3223,0.983,0.2,0
1968c2f6-f52c-4544-a0ed-f79b91ce0da0,BE9558,2026-05-16T05:11:28,K558LL9V.R40W,Long,0.3446,0.3516,0.980,0.2,0
caa06b94-8813-4949-b47b-61ffb16e61c4,BE9558,2026-05-16T05:14:22,K558LL9V.VY0W,Long,0.3318,0.3320,0.999,0.2,0
fdaa8101-f033-47e6-9c65-abd76dea1870,BE9558,2026-05-16T05:17:16,K558LL9W.0S0W,Long,0.3407,0.3418,0.997,0.2,0
29bd16bd-81b9-4ccd-a981-f1a80858536c,BE9558,2026-05-16T05:23:05,K558LL9W.AH0W,Long,0.3450,0.3516,0.981,0.2,0
1f8bc862-d5fd-4cce-abc0-e2bd8c2f11fa,BE9558,2026-05-16T05:26:00,K558LL9W.FC0W,Long,0.3417,0.3467,0.986,0.2,0
20220068-d498-4fca-9a2a-a7fd2ee52ab1,BE9558,2026-05-16T05:28:53,K558LL9W.K50W,Long,0.3516,0.3564,0.986,0.2,0
9816a261-3118-417a-8334-ace36687ad8f,BE9558,2026-05-16T05:31:47,K558LL9W.OZ0W,Long,0.3416,0.3467,0.985,0.2,0
5d2c76d7-543d-4557-9caf-996a69ab00bd,BE9558,2026-05-16T05:34:42,K558LL9W.TU0W,Long,0.3537,0.3564,0.992,0.2,0
c7b5ae00-52e7-4920-aa27-49d3b3daff92,BE9558,2026-05-16T05:37:36,K558LL9W.YO0W,Long,0.3517,0.3564,0.987,0.2,0
07db8fd8-ccef-4a5a-9d97-9f318f73a478,BE9558,2026-05-16T05:40:31,K558LL9X.3J0W,Long,0.3574,0.3613,0.989,0.2,0
790fcff9-e266-4a12-87f0-a072990d2533,BE9558,2026-05-16T05:43:26,K558LL9X.8E0W,Long,0.3650,0.3662,0.997,0.2,0
f4245f61-1dde-43dc-a121-98e102f6a193,BE9558,2026-05-16T05:50:28,K558LL9X.K40W,Long,0.3856,0.3906,0.987,0.2,0
5a3bce7b-358e-4260-876f-3f853163d7cf,BE9558,2026-05-16T05:53:22,K558LL9X.OY0W,Long,0.3847,0.3857,0.997,0.2,0
37c2b4b1-7a1b-43e7-b513-2c16f582109c,BE9558,2026-05-16T05:56:15,K558LL9X.TR0W,Long,0.3906,0.3955,0.988,0.2,0
57fde109-1d8a-45a1-b398-5bd28c3e47f1,BE9558,2026-05-16T05:59:10,K558LL9X.YM0W,Long,0.4000,0.4004,0.999,0.2,0
1e41ab40-93be-405c-a464-f7a57524d3b3,BE9558,2026-05-16T06:02:02,K558LL9Y.3E0W,Long,0.3825,0.3857,0.992,0.2,0
e9d61eb5-fae8-4902-8fab-4828ffa8e6da,BE9558,2026-05-16T06:04:57,K558LL9Y.890W,Long,0.3802,0.3809,0.998,0.2,0
c0e964e0-7788-4e41-bc41-6e479c3dc81b,BE9558,2026-05-16T06:07:51,K558LL9Y.D30W,Long,0.3954,0.4004,0.987,0.2,0
0b2df8e5-1689-4fe6-abad-30970ba10aa6,BE9558,2026-05-16T06:16:06,K558LL9Y.QU0W,Long,0.4051,0.4053,1.000,0.2,0
2bc6ce73-464b-469c-9e8f-3bf6f6cfae1d,BE9558,2026-05-16T06:21:51,K558LL9Z.0F0W,Long,0.3910,0.3955,0.989,0.2,0
b8603ee1-616a-451e-a2cd-61f8f2634cd0,BE9558,2026-05-16T06:24:44,K558LL9Z.580W,Long,0.3969,0.4004,0.991,0.2,0
1aecf582-66a2-4ebb-80f9-04b3aeba331a,BE9558,2026-05-16T06:27:39,K558LL9Z.A30W,Long,0.3915,0.3955,0.990,0.2,0
885aedfd-7a1a-4120-8176-7c344dd3d8fe,BE9558,2026-05-16T06:30:30,K558LL9Z.EU0W,Long,0.4025,0.4053,0.993,0.2,0
ec15930f-47f5-4752-afc2-427ee156ac95,BE9558,2026-05-16T06:33:25,K558LL9Z.JP0W,Long,0.4060,0.4102,0.990,0.2,0
5ca23f47-2a38-4a54-99dd-041287aa9510,BE9558,2026-05-16T06:36:17,K558LL9Z.OH0W,Long,0.4054,0.4102,0.988,0.2,0
03f371cf-81bc-4681-80f0-ef6fa437da85,BE9558,2026-05-16T06:39:09,K558LL9Z.T90W,Long,0.4052,0.4102,0.988,0.2,0
ed386f54-140d-45e8-ad51-6585a58b4375,BE9558,2026-05-16T06:44:54,K558LLA0.2U0W,Long,0.3993,0.4004,0.997,0.2,0
579f1c3f-4c1e-42a3-aa89-69aa93514033,BE9558,2026-05-16T06:47:47,K558LLA0.7N0W,Long,0.4001,0.4053,0.987,0.2,0
57024de6-07ea-41f4-b916-c6adc3f51636,BE9558,2026-05-16T06:50:40,K558LLA0.CG0W,Long,0.4103,0.4150,0.989,0.2,0
36bf5adf-afb5-4a5e-a106-1afbd1f56c7b,BE9558,2026-05-16T06:54:49,K558LLA0.JD0W,Long,0.4069,0.4150,0.980,0.2,0
3e2f831b-5228-46ff-9acb-75d8c86f8bc1,BE9558,2026-05-16T06:57:43,K558LLA0.O70W,Long,0.4108,0.4150,0.990,0.2,0
1775fa20-568b-4294-b9ca-561201a66c5b,BE9558,2026-05-16T07:00:38,K558LLA0.T20W,Long,0.3967,0.4004,0.991,0.2,0
fd391469-03f9-4d8d-bccd-3af50c91e5b7,BE9558,2026-05-16T07:03:33,K558LLA0.XX0W,Long,0.3927,0.3955,0.993,0.2,0
02b52ef6-b707-4dcb-b58f-43da02698832,BE9558,2026-05-16T07:06:27,K558LLA1.2R0W,Long,0.3824,0.3857,0.991,0.2,0
8d45333f-e101-4249-9e27-913c583a0a8d,BE9558,2026-05-16T07:09:21,K558LLA1.7L0W,Long,0.4085,0.4150,0.984,0.2,0
361d11ce-f42a-4d04-8270-ee3771fe4f09,BE9558,2026-05-16T07:12:14,K558LLA1.CE0W,Long,0.4017,0.4053,0.991,0.2,0
59218125-ed5d-4457-aa8b-35ba03441363,BE9558,2026-05-16T07:15:07,K558LLA1.H70W,Long,0.3934,0.3955,0.995,0.2,0
a603e55a-2ad6-4fc9-8c8c-0dc7be95c3e7,BE9558,2026-05-16T07:23:43,K558LLA1.VJ0W,Long,0.3806,0.3857,0.987,0.2,0
c8d07902-93ea-4b03-9e69-9ad6ed5bffb1,BE9558,2026-05-16T07:26:36,K558LLA2.0C0W,Long,0.3807,0.3857,0.987,0.2,0
4c46c0c7-42f0-4648-827e-1995f733b18f,BE9558,2026-05-16T07:30:44,K558LLA2.780W,Long,0.3667,0.3711,0.988,0.2,0
04759a00-ba3e-4959-a4cb-be8fc1f3004e,BE9558,2026-05-16T07:36:28,K558LLA2.GS0W,Long,0.3514,0.3516,1.000,0.2,0
0b6b0856-bd87-4a07-a5b4-f13d99e04a12,BE9558,2026-05-16T07:39:20,K558LLA2.LK0W,Long,0.3512,0.3516,0.999,0.2,0
3d81a8bd-464d-4050-8a76-25e8373d1ddb,BE9558,2026-05-16T07:42:12,K558LLA2.QC0W,Long,0.3350,0.3369,0.994,0.2,0
b8b9c0c4-c388-4acb-955a-be4ac356afce,BE9558,2026-05-16T07:45:04,K558LLA2.V40W,Long,0.3563,0.3564,1.000,0.2,0
cb3d142a-fb84-4a21-a298-f61bb869b036,BE9558,2026-05-16T07:49:13,K558LLA3.210W,Long,0.3663,0.3711,0.987,0.2,0
7401b19b-bc9d-43f0-b395-f4323aca5c72,BE9558,2026-05-16T07:52:06,K558LLA3.6U0W,Long,0.3612,0.3662,0.986,0.2,0
2236df76-a9e6-401f-9176-ad565242f2cf,BE9558,2026-05-16T07:57:52,K558LLA3.GG0W,Long,0.3366,0.3369,0.999,0.2,0
a645846c-cae4-4aa5-a2e6-85166bd4dd62,BE9558,2026-05-16T08:00:44,K558LLA3.L80W,Long,0.3265,0.3271,0.998,0.2,0
7212bd33-99a9-4659-9f0b-c98cc8d1e8bc,BE9558,2026-05-16T08:04:51,K558LLA3.S30W,Long,0.3418,0.3467,0.986,0.2,0
2cc4bf33-c63a-4c65-b0e2-5e61a9146a5d,BE9558,2026-05-16T08:07:43,K558LLA3.WV0W,Long,0.3405,0.3418,0.996,0.2,0
4fedb486-5f1f-4623-a01f-083e829f0565,BE9558,2026-05-16T08:10:35,K558LLA4.1N0W,Long,0.3515,0.3564,0.986,0.2,0
58aff0ba-0f9b-45e1-9bbe-a990d16192ae,BE9558,2026-05-16T08:13:27,K558LLA4.6F0W,Long,0.3513,0.3516,0.999,0.2,0
e56d87e5-e1d4-4947-b6a5-3bbd2773c54a,BE9558,2026-05-16T08:20:03,K558LLA4.HF0W,Long,0.3564,0.3613,0.986,0.2,0
0e96e61e-6a21-4e07-8e09-72d09dbfa1e6,BE9558,2026-05-16T08:25:21,K558LLA4.Q90W,Long,0.3565,0.3613,0.987,0.2,0
19611f28-2da8-4362-a58e-dbed2e061379,BE9558,2026-05-16T08:34:19,K558LLA5.570W,Long,0.3647,0.3662,0.996,0.2,0
bd580c1d-44d4-41fd-9f83-f462cda4099a,BE9558,2026-05-16T08:37:15,K558LLA5.A30W,Long,0.3536,0.3564,0.992,0.2,0
2782df3b-3cb4-471a-a6f5-bbc4903a8ab9,BE9558,2026-05-16T08:44:00,K558LLA5.LC0W,Long,0.3612,0.3662,0.986,0.2,0
d15a08f3-1c7c-4f80-8d9b-f5008c58c3d9,BE9558,2026-05-16T08:49:18,K558LLA5.U60W,Long,0.3610,0.3613,0.999,0.2,0
03a10a6a-193a-476c-9543-f63818f69417,BE9558,2026-05-16T08:54:36,K558LLA6.300W,Long,0.3515,0.3516,1.000,0.2,0
1c271856-8100-4c0d-bc8c-9357b47d7626,BE9558,2026-05-16T08:59:54,K558LLA6.BU0W,Long,0.3617,0.3662,0.988,0.2,0
a85f125e-bfa2-42be-b877-2604b8d068c8,BE9558,2026-05-16T09:05:17,K558LLA6.KT0W,Long,0.3510,0.3516,0.998,0.2,0
dde9aa71-d2e3-41ac-8388-f2bbddb6dae6,BE9558,2026-05-16T09:08:11,K558LLA6.PN0W,Long,0.3447,0.3467,0.994,0.2,0
2f3f2be2-0ee3-422e-b3ad-83fb87512a2b,BE9558,2026-05-16T09:14:39,K558LLA7.0F0W,Long,0.3580,0.3613,0.991,0.2,0
357a3034-8a9c-485e-8cb6-f526dd2baf6f,BE9558,2026-05-16T09:29:11,K558LLA7.ON0W,Long,0.3708,0.3760,0.986,0.2,0
f8ad0274-8e6f-4714-82ff-d229e60f1442,BE9558,2026-05-16T09:32:06,K558LLA7.TI0W,Long,0.3567,0.3613,0.987,0.2,0
42bb007a-2726-401a-b085-c25151b0dc24,BE9558,2026-05-16T09:35:02,K558LLA7.YE0W,Long,0.3575,0.3613,0.989,0.2,0
c99bfc4a-db02-4bea-bea4-943c67485dba,BE9558,2026-05-16T09:37:58,K558LLA8.3A0W,Long,0.3527,0.3564,0.989,0.2,0
8fc17de0-73f7-48bd-8d93-5451dce47e8e,BE9558,2026-05-16T09:40:52,K558LLA8.840W,Long,0.3613,0.3662,0.987,0.2,0
bbee5276-03dd-4ca4-a7b9-aec02baac7e8,BE9558,2026-05-16T09:48:13,K558LLA8.KD0W,Long,0.3590,0.3613,0.993,0.2,0
8dcdee10-db01-4224-9506-4181c3105d6f,BE9558,2026-05-16T09:53:31,K558LLA8.T70W,Long,0.3588,0.3613,0.993,0.2,0
48c8be72-64d9-4da3-95b5-bbec2c5e1dbd,BE9558,2026-05-16T09:58:49,K558LLA9.210W,Long,0.3582,0.3662,0.978,0.2,0
0da20919-7ce9-4feb-8ae9-12d9bb40c2b5,BE9558,2026-05-16T10:04:07,K558LLA9.AV0W,Long,0.3506,0.3516,0.997,0.2,0
c2f7e9bc-8b93-42c3-96d3-e3af217dde35,BE9558,2026-05-16T10:09:25,K558LLA9.JP0W,Long,0.3506,0.3516,0.997,0.2,0
522a0e42-d443-4447-bc71-af1832c6604e,BE9558,2026-05-16T10:14:43,K558LLA9.SJ0W,Long,0.3624,0.3662,0.990,0.2,0
67f7e732-3c0b-439f-87c5-3c478a381418,BE9558,2026-05-16T10:20:01,K558LLAA.1D0W,Long,0.3494,0.3516,0.994,0.2,0
251767e8-56f7-4091-a001-364d8e75c15c,BE9558,2026-05-16T10:25:19,K558LLAA.A70W,Long,0.3463,0.3516,0.985,0.2,0
9457239d-a4ca-4476-b385-5e01fc8f6420,BE9558,2026-05-16T10:30:37,K558LLAA.J10W,Long,0.3436,0.3467,0.991,0.2,0
43718d7c-9353-49e1-89b6-0841aeb1b276,BE9558,2026-05-16T10:35:55,K558LLAA.RV0W,Long,0.3452,0.3516,0.982,0.2,0
f54ba557-ddfe-41d3-8f4c-8bbec9a3783c,BE9558,2026-05-16T10:41:13,K558LLAB.0P0W,Long,0.3419,0.3467,0.986,0.2,0
dc26c758-ad99-49c1-b518-931368cdf8cf,BE9558,2026-05-16T10:46:31,K558LLAB.9J0W,Long,0.3463,0.3516,0.985,0.2,0
10917eb2-d151-461c-a8cb-e9660da5a5b0,BE9558,2026-05-16T10:51:49,K558LLAB.ID0W,Long,0.3520,0.3564,0.987,0.2,0
4938a5e6-d53b-40ee-be2b-06ec0e60398c,BE9558,2026-05-16T10:57:07,K558LLAB.R70W,Long,0.3541,0.3564,0.993,0.2,0
0711b51d-55bd-48be-b51e-2aad67107a60,BE9558,2026-05-16T11:13:01,K558LLAC.HP0W,Long,0.3661,0.3711,0.986,0.2,0
065564b6-aa49-40e7-9ea6-c75defdc60fe,BE9558,2026-05-16T11:18:19,K558LLAC.QJ0W,Long,0.3622,0.3662,0.989,0.2,0
ffb6b230-1d70-4e0e-ba30-e945339a122a,BE9558,2026-05-16T11:23:37,K558LLAC.ZD0W,Long,0.3711,0.3760,0.987,0.2,0
52b4da82-c1e0-4a8a-8365-51b090787005,BE9558,2026-05-16T11:28:55,K558LLAD.870W,Long,0.3644,0.3662,0.995,0.2,0
cdbff3d8-fbfe-4bea-8bd6-c898800e81ba,BE9558,2026-05-16T11:39:31,K558LLAD.PV0W,Long,0.3609,0.3662,0.986,0.2,0
3fb0bc30-1463-4cfc-9e7f-386c0eb2a34a,BE9558,2026-05-16T11:44:49,K558LLAD.YP0W,Long,0.3553,0.3564,0.997,0.2,0
ba1f5ec8-aef7-4a9e-ac1f-276cf016e285,BE9558,2026-05-16T11:50:07,K558LLAE.7J0W,Long,0.3479,0.3516,0.990,0.2,0
b1dd4df7-34a9-4512-a903-f8242b236fd2,BE9558,2026-05-16T11:55:25,K558LLAE.GD0W,Long,0.3427,0.3467,0.988,0.2,0
1f23aa28-c026-4bc7-b3d1-7c78fd76a673,BE9558,2026-05-16T12:00:43,K558LLAE.P70W,Long,0.3454,0.3467,0.996,0.2,0
0d91f54d-b20d-4a50-b7dd-d071c39a0690,BE9558,2026-05-16T12:06:01,K558LLAE.Y10W,Long,0.3431,0.3467,0.990,0.2,0
12ccdecd-5fd9-4465-9813-3d6006ec32f3,BE9558,2026-05-16T12:11:19,K558LLAF.6V0W,Long,0.3433,0.3467,0.990,0.2,0
a7024f1a-f071-48ab-820f-99bdf87366b5,BE9558,2026-05-16T12:16:37,K558LLAF.FP0W,Long,0.3361,0.3369,0.998,0.2,0
de0fa439-30b8-4607-a3c3-7e17191e4624,BE9558,2026-05-16T12:21:55,K558LLAF.OJ0W,Long,0.3274,0.3320,0.986,0.2,0
f9374ec3-05e5-477f-8e1a-0c862fed2a50,BE9558,2026-05-16T12:27:13,K558LLAF.XD0W,Long,0.3449,0.3467,0.995,0.2,0
424cb275-3743-4174-95f0-0ca1205b374c,BE9558,2026-05-16T12:32:31,K558LLAG.670W,Long,0.3370,0.3418,0.986,0.2,0
9accde13-cefa-41b8-bd0a-cef2ffed59b0,BE9558,2026-05-16T12:37:49,K558LLAG.F10W,Long,0.3465,0.3467,0.999,0.2,0
4665be38-1956-4b14-b931-068ba9af5c5e,BE9558,2026-05-16T12:48:25,K558LLAG.WP0W,Long,0.3453,0.3516,0.982,0.2,0
1aedf624-1a99-43e1-a8f2-f9d358b97f61,BE9558,2026-05-16T12:53:43,K558LLAH.5J0W,Long,0.3366,0.3418,0.985,0.2,0
c15e1799-91d7-425e-ad17-2ba3d170d81e,BE9558,2026-05-16T13:04:19,K558LLAH.N70W,Long,0.3348,0.3369,0.994,0.2,0
72d4c4ea-19ca-4cc6-9b04-7a2b70122c67,BE9558,2026-05-16T13:09:37,K558LLAH.W10W,Long,0.3272,0.3320,0.986,0.2,0
b4ebf2c9-1f6d-4594-9810-40479e87c0a5,BE9558,2026-05-16T13:14:55,K558LLAI.4V0W,Long,0.3297,0.3320,0.993,0.2,0
bb297e9e-548f-4dae-8b1a-0f161af2e766,BE9558,2026-05-16T13:20:13,K558LLAI.DP0W,Long,0.3272,0.3320,0.986,0.2,0
87562c24-63db-48bd-9962-72a20a40f2ff,BE9558,2026-05-16T13:36:07,K558LLAJ.470W,Long,0.3174,0.3223,0.985,0.2,0
01e9cc58-3bea-4f38-8499-a2c20e5f8550,BE9558,2026-05-16T13:46:52,K558LLAJ.M40W,Long,0.2880,0.2930,0.983,0.2,0
5ae7503d-ae17-4063-9208-6a420699e1ab,BE9558,2026-05-16T14:00:35,K558LLAK.8Z0W,Long,0.2879,0.2930,0.983,0.2,0
e009ea3c-1534-4154-8623-e180ed4db9fb,BE9558,2026-05-16T14:06:19,K558LLAK.IJ0W,Long,0.2882,0.2930,0.984,0.2,0
cd4e21f5-512b-4b2b-8054-bec01aa06400,BE9558,2026-05-16T14:12:03,K558LLAK.S30W,Long,0.2857,0.2930,0.975,0.2,0
ae5b780f-2038-4ccf-8bfc-b15b87be139e,BE9558,2026-05-16T14:17:22,K558LLAL.0Y0W,Long,0.2899,0.2930,0.989,0.2,0
d8c3fb81-8c66-4ebc-b33a-0559bc03334b,BE9558,2026-05-16T14:22:40,K558LLAL.9S0W,Long,0.3009,0.3027,0.994,0.2,0
990a4c7a-3c51-4d4a-8ab7-416ccb97d29c,BE9558,2026-05-16T14:27:58,K558LLAL.IM0W,Long,0.3057,0.3076,0.994,0.2,0
68d7a2c3-d899-4e75-96fb-3bf16ae6ea6f,BE9558,2026-05-16T14:33:16,K558LLAL.RG0W,Long,0.3110,0.3125,0.995,0.2,0
73505b8c-f912-4116-b903-a8a4c75524d3,BE9558,2026-05-16T14:38:34,K558LLAM.0A0W,Long,0.3172,0.3223,0.984,0.2,0
8d3c9602-7efa-488a-801b-3228bd85ab14,BE9558,2026-05-16T14:43:51,K558LLAM.930W,Long,0.3136,0.3174,0.988,0.2,0
243e16ee-860a-4960-bc15-b797ad7e9735,BE9558,2026-05-16T14:49:08,K558LLAM.HW0W,Long,0.3135,0.3174,0.988,0.2,0
e90c8d90-6d41-4788-9ee6-a29e4bfcc16b,BE9558,2026-05-16T15:19:35,K558LLAN.WN0W,Long,0.3132,0.3174,0.987,0.2,0
4182b0e7-7811-46b8-87d1-a4dd0c152f3b,BE9558,2026-05-16T15:28:45,K558LLAO.BX0W,Long,0.3023,0.3076,0.983,0.2,0
28a790da-0e48-4fe4-b8ba-2c82cc6bfa79,BE9558,2026-05-16T15:34:02,K558LLAO.KQ0W,Long,0.3176,0.3223,0.985,0.2,0
093d2fa3-7a4b-4f0f-abda-71155ebe2dfb,BE9558,2026-05-16T15:39:19,K558LLAO.TJ0W,Long,0.3223,0.3271,0.985,0.2,0
68dc9560-4082-49b6-af04-9244773ffbc1,BE9558,2026-05-16T15:44:36,K558LLAP.2C0W,Long,0.3227,0.3271,0.986,0.2,0
ad6b268a-165d-4b1d-b0b3-f58db7c9b0e4,BE9558,2026-05-16T15:49:53,K558LLAP.B50W,Long,0.3177,0.3223,0.986,0.2,0
046c5cb4-56b3-48c0-83c2-bf1f30837940,BE9558,2026-05-16T15:55:10,K558LLAP.JY0W,Long,0.3174,0.3223,0.985,0.2,0
1b76edf4-3b1c-4bcb-a73c-27334981c350,BE9558,2026-05-16T16:00:27,K558LLAP.SR0W,Long,0.3127,0.3174,0.985,0.2,0
a0264171-a682-4396-ad8a-cda3b2964533,BE9558,2026-05-16T16:06:55,K558LLAQ.3J0W,Long,0.2885,0.2930,0.985,0.2,0
707da1f6-ee81-4e57-abd5-98295c14651b,BE9558,2026-05-16T16:12:30,K558LLAQ.CU0W,Long,0.2880,0.2930,0.983,0.2,0
b8115b64-8739-42c8-b541-713ab6b68bcd,BE9558,2026-05-16T16:17:53,K558LLAQ.LT0W,Long,0.2881,0.2930,0.983,0.2,0
fb179c36-fef1-4df6-b0a0-2bd7792ea910,BE9558,2026-05-16T16:23:11,K558LLAQ.UN0W,Long,0.2933,0.2979,0.985,0.2,0
0cec8793-c3c1-486b-a33a-4dbf9cb069b0,BE9558,2026-05-16T16:33:46,K558LLAR.CA0W,Long,0.3017,0.3027,0.997,0.2,0
c531b052-ee04-4c66-888b-21e97445a615,BE9558,2026-05-16T16:49:37,K558LLAS.2P0W,Long,0.2922,0.2979,0.981,0.2,0
0dc402f9-cab6-4c4a-8317-b8fc3c4b1ced,BE9558,2026-05-16T16:55:08,K558LLAS.BW0W,Long,0.2898,0.2930,0.989,0.2,0
fd73733e-b42d-4a51-81d0-4acad6edfbd4,BE9558,2026-05-16T17:16:17,K558LLAT.B50W,Long,0.3115,0.3125,0.997,0.2,0
6a254daa-ae27-4ac1-b334-58f776a6b276,BE9558,2026-05-16T17:26:51,K558LLAT.SR0W,Long,0.3174,0.3223,0.985,0.2,0
0cc8e82f-5270-4508-beae-0d3af56095ca,BE9558,2026-05-16T17:37:27,K558LLAU.AF0W,Long,0.2899,0.2930,0.989,0.2,0
00557a73-8dc3-4cd2-b880-c7820dc8b171,BE9558,2026-05-16T17:43:17,K558LLAU.K50W,Long,0.2881,0.2930,0.983,0.2,0
8e5518d9-ff0a-4c09-9cf9-a681c84c0b6e,BE9558,2026-05-16T17:53:53,K558LLAV.1T0W,Long,0.2898,0.2930,0.989,0.2,0
91dbd7e9-7344-400b-82b1-379f2ac4b49a,BE9558,2026-05-16T17:59:11,K558LLAV.AN0W,Long,0.2925,0.2930,0.998,0.2,0
fa256408-d480-4376-95b5-d1a549c483ea,BE9558,2026-05-16T18:04:29,K558LLAV.JH0W,Long,0.2977,0.3027,0.983,0.2,0
4ab6e66a-8364-49b6-82f1-86e86199e676,BE9558,2026-05-16T18:09:46,K558LLAV.SA0W,Long,0.2944,0.2979,0.988,0.2,0
0a65fb7c-96e1-4ba0-85de-4620d88658c1,BE9558,2026-05-16T18:15:03,K558LLAW.130W,Long,0.2965,0.2979,0.995,0.2,0
92b1ef3e-1696-4123-8662-163947737c83,BE9558,2026-05-16T18:20:20,K558LLAW.9W0W,Long,0.2976,0.3027,0.983,0.2,0
9e3cb24c-4426-4220-9a73-389d0a96c94f,BE9558,2026-05-16T18:25:37,K558LLAW.IP0W,Long,0.2983,0.3027,0.985,0.2,0
a3473215-4c46-45ab-9aa7-1720486ec4a8,BE9558,2026-05-16T18:30:54,K558LLAW.RI0W,Long,0.2956,0.2979,0.993,0.2,0
449665b1-47c8-4bd2-984c-8f45b627e6d8,BE9558,2026-05-16T18:36:11,K558LLAX.0B0W,Long,0.2989,0.3027,0.987,0.2,0
600cfabc-cffd-42e1-800c-70e75f312316,BE9558,2026-05-16T20:00:12,K558LLB0.WC0W,Long,0.3077,0.3125,0.985,0.2,0
12bf5944-0194-4f5b-b486-a7acd7141c7f,BE9558,2026-05-16T20:04:28,K558LLB1.3G0W,Long,0.2888,0.2930,0.986,0.2,0
f1fc913a-91bc-4240-a595-7dfe3091f9a2,BE9558,2026-05-16T20:07:29,K558LLB1.8H0W,Long,0.2977,0.3027,0.983,0.2,0
e74f7ec3-20bb-4177-beb2-e802e5f801fd,BE9558,2026-05-16T20:10:26,K558LLB1.DE0W,Long,0.2978,0.3027,0.984,0.2,0
27491c3a-b631-4643-818a-714523911178,BE9558,2026-05-16T20:16:21,K558LLB1.N90W,Long,0.2921,0.2930,0.997,0.2,0
9d9196ce-11e2-4f28-b01c-3dcc60e60d42,BE9558,2026-05-16T20:22:28,K558LLB1.XG0W,Long,0.2881,0.2930,0.983,0.2,0
a592d7c8-b643-4b25-9186-3d611ae22709,BE9558,2026-05-16T20:25:37,K558LLB2.2P0W,Long,0.2893,0.2930,0.987,0.2,0
f709a3d5-27cd-4bb1-b91c-669e8ea11d77,BE9558,2026-05-16T20:28:57,K558LLB2.890W,Long,0.2880,0.2930,0.983,0.2,0
cc9cad87-b87f-4b67-854a-ffb21e876a92,BE9558,2026-05-16T20:32:45,K558LLB2.EL0W,Long,0.2873,0.2930,0.980,0.2,0
10732d26-6b49-4b14-a474-6c75e259d278,BE9558,2026-05-16T20:49:32,K558LLB3.6K0W,Long,0.2881,0.2930,0.983,0.2,0
aa63957a-fdb2-4f17-af52-a63bb015119d,BE9558,2026-05-16T21:21:45,K558LLB4.O90W,Long,0.2880,0.2930,0.983,0.2,0
8350440f-019d-45a4-b9f9-23058628e6f0,BE9558,2026-05-16T21:32:43,K558LLB5.6J0W,Long,0.2925,0.2930,0.999,0.2,0
edfc10b2-dbe1-4527-a061-b0d670b5e5d2,BE9558,2026-05-16T21:35:37,K558LLB5.BD0W,Long,0.2891,0.2930,0.987,0.2,0
f98001a3-88b2-4830-8112-b7c5164e99c3,BE9558,2026-05-16T21:38:40,K558LLB5.GG0W,Long,0.2877,0.2930,0.982,0.2,0
f1e53e7b-b124-4fc5-82c2-504fb0c8b80d,BE9558,2026-05-16T21:41:46,K558LLB5.LM0W,Long,0.2881,0.2930,0.983,0.2,0
7890637f-142e-4775-b48c-fd4f3b8ada77,BE9558,2026-05-16T21:45:14,K558LLB5.RE0W,Long,0.2880,0.2930,0.983,0.2,0
7c97c10f-b413-467c-9b56-c18e423cdcfa,BE9558,2026-05-16T21:48:26,K558LLB5.WQ0W,Long,0.2886,0.2930,0.985,0.2,0
8178cf22-8428-4f85-8199-0a43f7334a8f,BE9558,2026-05-16T21:51:47,K558LLB6.2B0W,Long,0.2881,0.2930,0.983,0.2,0
eceb2997-deb4-403a-802f-50e93d23d423,BE9558,2026-05-16T21:57:18,K558LLB6.BI0W,Long,0.2881,0.2930,0.984,0.2,0
9c26690c-1983-4b21-b8af-7c7967c014c3,BE9558,2026-05-16T22:12:21,K558LLB7.0L0W,Long,0.2876,0.2930,0.982,0.2,0
78f67fc3-08b7-4317-96ba-ee5544e0b95b,BE9558,2026-05-16T22:19:34,K558LLB7.CM0W,Long,0.2880,0.2930,0.983,0.2,0
7f9dad14-4f1b-492d-aa26-845a908ea894,BE9558,2026-05-16T22:27:40,K558LLB7.Q40W,Long,0.2881,0.2930,0.983,0.2,0
f75c52b4-21b9-4065-baeb-5cfbd27d130a,BE9558,2026-05-16T22:33:50,K558LLB8.0E0W,Long,0.2881,0.2930,0.984,0.2,0
10f7496d-fa76-40a7-8bef-dc14e8a41869,BE9558,2026-05-16T22:40:48,K558LLB8.C00W,Long,0.2878,0.2930,0.982,0.2,0
event_id,serial,timestamp,filename,channel,offset_ips,peak_ips,mean_over_peak,trigger_level_ips,already_flagged_ft
1e7a7808-034c-423b-80e9-d6788da80993,BE18438,2025-11-15T08:57:40,T438LBX4.W40W,Vert,0.2722,0.2930,0.929,0.2,0
346e383f-c5a1-41d1-b972-3d652e599d39,BE18438,2025-11-15T09:13:15,T438LBX5.M30W,Vert,0.2747,0.2930,0.938,0.2,0
45ef3023-22c5-44a8-a606-a0900bc17861,BE18438,2025-11-15T09:16:13,T438LBX5.R10W,Vert,0.2929,0.3027,0.967,0.2,0
1cbcd2aa-ec55-4e2f-af42-7178f26cc6a1,BE18438,2025-11-15T09:19:29,T438LBX5.WH0W,Vert,0.2816,0.2979,0.945,0.2,0
caf43634-4528-4fd5-9674-5f4f563661c0,BE18438,2025-11-15T09:22:32,T438LBX6.1K0W,Vert,0.2883,0.2930,0.984,0.2,0
456ae646-c834-4e5c-82f1-7df18b3440a1,BE18438,2025-11-15T09:25:31,T438LBX6.6J0W,Vert,0.3189,0.3223,0.989,0.2,0
afb91ba2-351b-42a0-b33f-acebd5f1829d,BE18438,2025-11-15T09:28:29,T438LBX6.BH0W,Vert,0.3057,0.3076,0.994,0.2,0
39847146-3537-4300-943d-01c0c771e9cd,BE18438,2025-11-15T09:31:26,T438LBX6.GE0W,Vert,0.3225,0.3271,0.986,0.2,0
e47335c1-fc3f-4c90-88c6-8edd0f296ce4,BE18438,2025-11-15T09:34:24,T438LBX6.LC0W,Vert,0.3275,0.3320,0.986,0.2,0
25b6eda6-ba98-422f-8834-94b6cbe34971,BE18438,2025-11-15T09:37:22,T438LBX6.QA0W,Vert,0.3398,0.3418,0.994,0.2,0
7af99377-e47f-4914-8e91-ac7f7f50b8c6,BE18438,2025-11-15T09:40:20,T438LBX6.V80W,Vert,0.3515,0.3564,0.986,0.2,0
c4330605-c257-49ef-aede-20deb641e7d7,BE18438,2025-11-15T10:09:48,T438LBX8.8C0W,Vert,0.3605,0.3955,0.912,0.2,0
b665caf9-64ee-4352-a391-60c1ddeebc1e,BE18438,2026-02-25T10:58:04,T438LH66.GS0W,Vert,0.1803,0.1953,0.923,0.2,0
3b0c32c3-fd16-4b83-9917-942a56dea168,BE18438,2026-02-25T18:12:04,T438LH6Q.K40W,Vert,0.1869,0.1953,0.957,0.2,0
ca66e601-d10f-4424-9c26-08a688e7b08c,BE18438,2026-02-25T18:17:16,T438LH6Q.SS0W,Vert,0.1870,0.1953,0.958,0.2,0
31aa30ba-eb0a-49a9-98ca-c77d2cc31275,BE18438,2026-02-25T18:21:11,T438LH6Q.ZB0W,Vert,0.1868,0.1953,0.956,0.2,0
fdb55a93-fc91-4fdf-a7f4-fdd1a6b48f59,BE18438,2026-02-25T18:26:27,T438LH6R.830W,Vert,0.1893,0.1953,0.969,0.2,0
cbd718d7-2378-4d74-8656-842f229d19a8,BE18438,2026-02-25T18:33:25,T438LH6R.JP0W,Vert,0.1887,0.1953,0.966,0.2,0
bfaf58ec-6163-47eb-9d2a-70da880bd948,BE18438,2026-02-25T18:37:48,T438LH6R.R00W,Vert,0.1872,0.1953,0.959,0.2,0
ddaa530b-886e-4415-b93a-f4ebf4c4a882,BE18438,2026-02-25T18:59:54,T438LH6S.RU0W,Vert,0.1874,0.1953,0.959,0.2,0
57f15284-ab69-48fc-9660-8c347c80c681,BE18438,2026-02-25T19:15:58,T438LH6T.IM0W,Vert,0.1873,0.1953,0.959,0.2,0
03715718-7aa8-4e1d-9b0b-c2ab75fc1975,BE18438,2026-02-25T19:19:58,T438LH6T.PA0W,Vert,0.1891,0.1953,0.968,0.2,0
9f921cd5-1bf9-4713-aef6-41e7f780eff1,BE18438,2026-02-25T19:24:02,T438LH6T.W20W,Vert,0.1871,0.1953,0.958,0.2,0
44994949-58d4-44fa-bd78-ed75b8acc667,BE18438,2026-02-25T19:44:57,T438LH6U.UX0W,Vert,0.1877,0.1953,0.961,0.2,0
c4be01c3-1001-4e17-aecd-d6d26dbb09f3,BE18438,2026-02-25T19:49:19,T438LH6V.270W,Vert,0.1884,0.1953,0.964,0.2,0
3db004e6-ee34-43c5-ae8e-f22894ead5d0,BE18438,2026-02-25T20:08:22,T438LH6V.XY0W,Vert,0.1878,0.1953,0.962,0.2,0
d276ae48-0434-41e5-af43-e0fb366acf11,BE18438,2026-02-25T20:11:33,T438LH6W.390W,Vert,0.1880,0.1953,0.963,0.2,0
c027dc12-88fd-4a45-872b-a6a945f2008e,BE18438,2026-02-25T20:14:35,T438LH6W.8B0W,Vert,0.1874,0.1953,0.959,0.2,0
9665bc3a-3d08-4852-b008-37ef8bfd0023,BE18438,2026-02-25T20:18:51,T438LH6W.FF0W,Vert,0.1884,0.1953,0.965,0.2,0
5fb5a05e-d7e2-4268-9b85-cfe8d82aa6c9,BE18438,2026-02-25T20:29:50,T438LH6W.XQ0W,Vert,0.1890,0.1953,0.968,0.2,0
57ec0b10-9324-4459-a07e-0c8532b8928f,BE18438,2026-02-25T20:35:39,T438LH6X.7F0W,Vert,0.1889,0.1953,0.967,0.2,0
ac86f73f-1174-4fae-a206-ecdcb73e1ffc,BE18438,2026-02-25T20:39:12,T438LH6X.DC0W,Vert,0.1887,0.1953,0.966,0.2,0
dcf25ddd-9cf0-41c1-b109-f3ef2e490ce5,BE18438,2026-02-25T20:43:41,T438LH6X.KT0W,Vert,0.1871,0.1953,0.958,0.2,0
aa79bbdd-2392-4ef6-8a5c-873a9f72746d,BE18438,2026-02-25T20:46:51,T438LH6X.Q30W,Vert,0.1877,0.1953,0.961,0.2,0
ad46d1ce-b417-4c8c-b029-bb3b008ba809,BE18438,2026-02-25T20:53:33,T438LH6Y.190W,Vert,0.1882,0.1953,0.964,0.2,0
3d3a8f34-86a7-4d70-a7e8-fa768a723325,BE18438,2026-02-26T07:03:39,T438LH7Q.A30W,Vert,0.1809,0.1953,0.926,0.2,0
7817525f-dc3d-4f5e-b2cb-5af9ca12ede8,BE18438,2026-02-26T07:09:42,T438LH7Q.K60W,Vert,0.1814,0.1953,0.929,0.2,0
a2091302-0b34-46c1-ab83-174be2b59bcf,BE18438,2026-02-26T13:12:35,T438LH87.CZ0W,Vert,0.1896,0.1953,0.971,0.2,0
e1c0c9de-a900-479f-9572-9675b13296a9,BE18438,2026-02-26T13:24:46,T438LH87.XA0W,Vert,0.2237,0.2588,0.864,0.2,0
76a6dc6b-88e1-434b-a137-f5e9b63f248e,BE18438,2026-02-26T13:27:43,T438LH88.270W,Vert,0.3185,0.3223,0.988,0.2,0
281b508b-7982-4668-86af-9b0b28be608a,BE18438,2026-02-26T13:30:36,T438LH88.700W,Vert,0.3263,0.3320,0.983,0.2,0
68bbaf77-bb23-40fd-94f9-f928728d90dc,BE18438,2026-02-26T13:33:28,T438LH88.BS0W,Vert,0.3207,0.3271,0.980,0.2,0
5c975640-6ff1-441a-aa11-41642f6a6b31,BE18438,2026-02-26T13:36:21,T438LH88.GL0W,Vert,0.3261,0.3320,0.982,0.2,0
dea248ac-1124-4bba-b054-953f86c852b2,BE18438,2026-02-26T13:40:34,T438LH88.NM0W,Vert,0.3271,0.3320,0.985,0.2,0
4e463201-f008-41ad-9c52-11fcc3d93095,BE18438,2026-02-26T13:43:29,T438LH88.SH0W,Vert,0.3357,0.3418,0.982,0.2,0
507262c5-d58f-4a05-a6a3-a6cbb5b4de20,BE18438,2026-02-26T13:46:24,T438LH88.XC0W,Vert,0.3372,0.3418,0.987,0.2,0
4c2d8ee8-842f-4e44-9e03-ff34d26e4fdb,BE18438,2026-02-26T13:49:17,T438LH89.250W,Vert,0.3253,0.3320,0.980,0.2,0
b184b112-603f-44f4-ae97-087493fbd8ce,BE18438,2026-02-26T13:52:10,T438LH89.6Y0W,Vert,0.3321,0.3369,0.986,0.2,0
2ff1a552-5a2e-4396-9083-b9c8d334eed7,BE18438,2026-02-26T13:55:04,T438LH89.BS0W,Vert,0.3378,0.3418,0.988,0.2,0
928e21a7-1990-4792-803e-58014d8140ce,BE18438,2026-02-26T13:57:57,T438LH89.GL0W,Vert,0.3341,0.3369,0.992,0.2,0
f521b5db-6100-41e6-954e-0abdbf9660c1,BE18438,2026-02-26T14:00:51,T438LH89.LF0W,Vert,0.3421,0.3467,0.987,0.2,0
efba962f-e511-41ef-9fc5-313f202a9d96,BE18438,2026-02-26T14:03:46,T438LH89.QA0W,Vert,0.3506,0.3564,0.984,0.2,0
0b51e273-8d10-4494-bda6-8c75eaeec66f,BE18438,2026-02-26T14:06:41,T438LH89.V50W,Vert,0.3448,0.3516,0.981,0.2,0
6d46e4ee-1647-4169-b6b2-33da32240eb9,BE18438,2026-02-26T14:09:35,T438LH89.ZZ0W,Vert,0.3463,0.3516,0.985,0.2,0
1ca294cd-4dc2-41fb-9374-e277d4550761,BE18438,2026-02-26T14:12:28,T438LH8A.4S0W,Vert,0.3442,0.3467,0.993,0.2,0
7b683dcf-1aed-4d9b-be1e-b10f92374398,BE18438,2026-02-26T14:15:23,T438LH8A.9N0W,Vert,0.3486,0.3516,0.992,0.2,0
2b5cb8e7-c947-4914-bcb5-504f74603547,BE18438,2026-02-26T14:18:21,T438LH8A.EL0W,Vert,0.3519,0.3613,0.974,0.2,0
5ea3a6bf-10de-4911-aedc-66daecf86b76,BE18438,2026-02-26T14:21:16,T438LH8A.JG0W,Vert,0.3460,0.3564,0.971,0.2,0
d93be7f5-39ec-45fd-9949-fa531f2f9d34,BE18438,2026-02-26T14:24:13,T438LH8A.OD0W,Vert,0.3457,0.3516,0.983,0.2,0
cfa113f2-8cee-4a1d-b1e7-0e936fa771e2,BE18438,2026-02-26T14:28:21,T438LH8A.V90W,Vert,0.3485,0.3564,0.978,0.2,0
46d322ac-38cb-4c99-a4c2-9e9d7ad06171,BE18438,2026-02-26T14:31:17,T438LH8B.050W,Vert,0.3367,0.3467,0.971,0.2,0
42500a83-bd67-4deb-8bb2-963ee2b8a7ce,BE18438,2026-02-26T14:34:11,T438LH8B.4Z0W,Vert,0.3365,0.3516,0.957,0.2,0
3ccf6bda-2e88-473c-951d-9ea86d0d9363,BE18438,2026-02-26T14:37:05,T438LH8B.9T0W,Vert,0.3472,0.3564,0.974,0.2,0
9050487d-d238-4631-b8e1-5a693a026542,BE18438,2026-02-26T14:39:58,T438LH8B.EM0W,Vert,0.3420,0.3564,0.959,0.2,0
e62989e4-a326-4bae-8d47-a8becee96462,BE18438,2026-02-26T14:42:52,T438LH8B.JG0W,Vert,0.3430,0.3564,0.962,0.2,0
f0e30fab-dc57-4189-8439-48df17007a2c,BE18438,2026-02-26T14:45:46,T438LH8B.OA0W,Vert,0.3389,0.3516,0.964,0.2,0
03e1ca09-78df-4c6f-9915-0b6e4f2141d2,BE18438,2026-02-26T14:48:43,T438LH8B.T70W,Vert,0.3449,0.3564,0.968,0.2,0
945d39f7-1b98-4a1f-80a8-6a18fd9df25f,BE18438,2026-02-26T14:51:37,T438LH8B.Y10W,Vert,0.3522,0.3613,0.975,0.2,0
d27eb2e3-e313-4125-98f4-f9d6d3737d28,BE18438,2026-02-26T14:54:32,T438LH8C.2W0W,Vert,0.3502,0.3613,0.969,0.2,0
916901cb-ebea-441e-a2a1-40f4e49f32f4,BE18438,2026-02-26T14:57:25,T438LH8C.7P0W,Vert,0.3524,0.3662,0.962,0.2,0
5d8d7e29-fdbb-4fa3-bd25-506c9352a354,BE18438,2026-02-26T15:01:35,T438LH8C.EN0W,Vert,0.3530,0.3613,0.977,0.2,0
c6c7a3af-b03b-43dc-97de-024f8e09b62f,BE18438,2026-02-26T15:04:27,T438LH8C.JF0W,Vert,0.3514,0.3613,0.973,0.2,0
b6856898-3d10-4967-9577-7f17902f77ea,BE18438,2026-02-26T15:11:34,T438LH8C.VA0W,Vert,0.3566,0.3613,0.987,0.2,0
7a4802f6-621e-4230-8d8c-d7f0c9a65bf2,BE18438,2026-02-26T15:14:24,T438LH8D.000W,Vert,0.3594,0.3711,0.968,0.2,0
79f38b7e-ec56-417e-943a-8c944252c2b8,BE18438,2026-02-26T15:18:32,T438LH8D.6W0W,Vert,0.3550,0.3613,0.983,0.2,0
1b4190c4-0d54-48ba-8ff5-8ddb0eb91e50,BE18438,2026-02-26T15:22:22,T438LH8D.DA0W,Vert,0.3571,0.3613,0.988,0.2,0
de57b5ae-a3a1-4ede-9d2b-3e87bfb3fd19,BE9558,2026-04-14T11:16:32,K558LJN3.BK0W,Tran,0.3448,0.3662,0.942,0.2,0
43afeaf5-02ec-41f6-9e23-0c9772821ed4,BE9558,2026-04-14T11:27:15,K558LJN3.TF0W,Tran,0.3094,0.3223,0.960,0.2,0
8123c0ef-84c9-4f6c-8d82-9dc32e2e470d,BE9558,2026-04-14T14:45:30,K558LJNC.ZU0W,Tran,0.2721,0.3564,0.763,0.2,0
8c787af3-596e-411b-9e10-29485fa5114f,BE9558,2026-04-29T16:18:47,K558LKF9.BB0W,Tran,0.2943,0.3027,0.972,0.2,0
431928ff-b4c4-4caa-b933-acc917f3717c,BE9558,2026-05-04T15:02:30,K558LKOF.460W,Tran,0.4364,0.5225,0.835,0.2,0
6c3c07f8-c36a-4493-acce-7441c9d22cec,BE9558,2026-05-15T08:50:06,K558LL8B.7I0W,Long,0.2892,0.2930,0.987,0.2,0
13c268df-b652-422e-a642-6453f6a314aa,BE9558,2026-05-15T10:18:34,K558LL8F.AY0W,Long,0.2907,0.2979,0.976,0.2,0
9b0d0871-8810-467d-806a-5bbfa4e667fe,BE9558,2026-05-15T15:52:00,K558LL8U.QO0W,Long,0.2659,0.2979,0.893,0.2,0
092640f9-a944-48b7-b872-364d75c2c5e7,BE9558,2026-05-15T16:13:12,K558LL8V.Q00W,Long,0.2428,0.2979,0.815,0.2,0
0573741a-96ab-4b36-af7a-b5bc11a79009,BE9558,2026-05-16T03:23:26,K558LL9Q.R20W,Long,0.2861,0.2930,0.976,0.2,0
321f03ea-6696-47de-ad46-2be43d4d6cae,BE9558,2026-05-16T03:30:49,K558LL9R.3D0W,Long,0.2886,0.2930,0.985,0.2,0
cc423a6a-3e3c-466a-b39c-6146ca7f34c8,BE9558,2026-05-16T03:33:55,K558LL9R.8J0W,Long,0.2880,0.2881,1.000,0.2,0
efa52a14-cc68-4bea-aab4-4ee3a3cbff3a,BE9558,2026-05-16T03:36:55,K558LL9R.DJ0W,Long,0.2890,0.2930,0.986,0.2,0
92895bfe-122f-4cdc-bd3d-40609633d278,BE9558,2026-05-16T03:43:41,K558LL9R.OT0W,Long,0.2880,0.2881,1.000,0.2,0
2a4c81db-2307-44e5-9b27-d5154d98e38d,BE9558,2026-05-16T03:46:36,K558LL9R.TO0W,Long,0.2921,0.2979,0.981,0.2,0
656b0fdc-e275-4c9c-8936-9eee267ea04e,BE9558,2026-05-16T03:49:28,K558LL9R.YG0W,Long,0.2966,0.2979,0.996,0.2,0
3b9989ae-e0f2-4652-9724-c145603543d2,BE9558,2026-05-16T03:52:29,K558LL9S.3H0W,Long,0.2880,0.2930,0.983,0.2,0
837d0d84-d609-4f4a-b542-b7e2b064ea22,BE9558,2026-05-16T03:56:32,K558LL9S.A80W,Long,0.2880,0.2930,0.983,0.2,0
affcb008-ab99-4bc5-8f35-83dbe620499d,BE9558,2026-05-16T04:02:50,K558LL9S.KQ0W,Long,0.2896,0.2930,0.989,0.2,0
e1f1c6d2-545c-451f-9018-714d52e20a05,BE9558,2026-05-16T04:05:47,K558LL9S.PN0W,Long,0.3024,0.3076,0.983,0.2,0
93ef80f1-7e83-4703-a0f9-89bbfeeae6c3,BE9558,2026-05-16T04:08:41,K558LL9S.UH0W,Long,0.2976,0.2979,0.999,0.2,0
5c118ca9-fc37-4080-876d-b3f57ce0b121,BE9558,2026-05-16T04:11:42,K558LL9S.ZI0W,Long,0.2881,0.2930,0.983,0.2,0
d98b2eaa-7763-4c78-88fb-c21195cb9978,BE9558,2026-05-16T04:14:38,K558LL9T.4E0W,Long,0.2898,0.2930,0.989,0.2,0
6a146a01-0d02-4413-b231-ecb4a6fde776,BE9558,2026-05-16T04:17:35,K558LL9T.9B0W,Long,0.2880,0.2930,0.983,0.2,0
f6587a55-27e3-454f-997e-57e7516a296c,BE9558,2026-05-16T04:20:32,K558LL9T.E80W,Long,0.3046,0.3076,0.990,0.2,0
1fb48250-2214-41e6-92cb-362aff1ba62b,BE9558,2026-05-16T04:26:05,K558LL9T.NH0W,Long,0.2876,0.2930,0.982,0.2,0
2f4f3d06-1189-4e28-a1ac-5454ea586a0c,BE9558,2026-05-16T04:59:47,K558LL9V.7N0W,Long,0.2961,0.3027,0.978,0.2,0
62b7bdab-b744-41e4-8d0e-c9141b9d4821,BE9558,2026-05-16T05:02:46,K558LL9V.CM0W,Long,0.2903,0.2930,0.991,0.2,0
cadcb6dc-74c0-48b5-974c-87bb7a57816c,BE9558,2026-05-16T05:05:43,K558LL9V.HJ0W,Long,0.3090,0.3125,0.989,0.2,0
a0235177-be5a-4f11-b741-c65744698e5b,BE9558,2026-05-16T05:08:35,K558LL9V.MB0W,Long,0.3167,0.3223,0.983,0.2,0
1968c2f6-f52c-4544-a0ed-f79b91ce0da0,BE9558,2026-05-16T05:11:28,K558LL9V.R40W,Long,0.3446,0.3516,0.980,0.2,0
caa06b94-8813-4949-b47b-61ffb16e61c4,BE9558,2026-05-16T05:14:22,K558LL9V.VY0W,Long,0.3318,0.3320,0.999,0.2,0
fdaa8101-f033-47e6-9c65-abd76dea1870,BE9558,2026-05-16T05:17:16,K558LL9W.0S0W,Long,0.3407,0.3418,0.997,0.2,0
29bd16bd-81b9-4ccd-a981-f1a80858536c,BE9558,2026-05-16T05:23:05,K558LL9W.AH0W,Long,0.3450,0.3516,0.981,0.2,0
1f8bc862-d5fd-4cce-abc0-e2bd8c2f11fa,BE9558,2026-05-16T05:26:00,K558LL9W.FC0W,Long,0.3417,0.3467,0.986,0.2,0
20220068-d498-4fca-9a2a-a7fd2ee52ab1,BE9558,2026-05-16T05:28:53,K558LL9W.K50W,Long,0.3516,0.3564,0.986,0.2,0
9816a261-3118-417a-8334-ace36687ad8f,BE9558,2026-05-16T05:31:47,K558LL9W.OZ0W,Long,0.3416,0.3467,0.985,0.2,0
5d2c76d7-543d-4557-9caf-996a69ab00bd,BE9558,2026-05-16T05:34:42,K558LL9W.TU0W,Long,0.3537,0.3564,0.992,0.2,0
c7b5ae00-52e7-4920-aa27-49d3b3daff92,BE9558,2026-05-16T05:37:36,K558LL9W.YO0W,Long,0.3517,0.3564,0.987,0.2,0
07db8fd8-ccef-4a5a-9d97-9f318f73a478,BE9558,2026-05-16T05:40:31,K558LL9X.3J0W,Long,0.3574,0.3613,0.989,0.2,0
790fcff9-e266-4a12-87f0-a072990d2533,BE9558,2026-05-16T05:43:26,K558LL9X.8E0W,Long,0.3650,0.3662,0.997,0.2,0
f4245f61-1dde-43dc-a121-98e102f6a193,BE9558,2026-05-16T05:50:28,K558LL9X.K40W,Long,0.3856,0.3906,0.987,0.2,0
5a3bce7b-358e-4260-876f-3f853163d7cf,BE9558,2026-05-16T05:53:22,K558LL9X.OY0W,Long,0.3847,0.3857,0.997,0.2,0
37c2b4b1-7a1b-43e7-b513-2c16f582109c,BE9558,2026-05-16T05:56:15,K558LL9X.TR0W,Long,0.3906,0.3955,0.988,0.2,0
57fde109-1d8a-45a1-b398-5bd28c3e47f1,BE9558,2026-05-16T05:59:10,K558LL9X.YM0W,Long,0.4000,0.4004,0.999,0.2,0
1e41ab40-93be-405c-a464-f7a57524d3b3,BE9558,2026-05-16T06:02:02,K558LL9Y.3E0W,Long,0.3825,0.3857,0.992,0.2,0
e9d61eb5-fae8-4902-8fab-4828ffa8e6da,BE9558,2026-05-16T06:04:57,K558LL9Y.890W,Long,0.3802,0.3809,0.998,0.2,0
c0e964e0-7788-4e41-bc41-6e479c3dc81b,BE9558,2026-05-16T06:07:51,K558LL9Y.D30W,Long,0.3954,0.4004,0.987,0.2,0
0b2df8e5-1689-4fe6-abad-30970ba10aa6,BE9558,2026-05-16T06:16:06,K558LL9Y.QU0W,Long,0.4051,0.4053,1.000,0.2,0
2bc6ce73-464b-469c-9e8f-3bf6f6cfae1d,BE9558,2026-05-16T06:21:51,K558LL9Z.0F0W,Long,0.3910,0.3955,0.989,0.2,0
b8603ee1-616a-451e-a2cd-61f8f2634cd0,BE9558,2026-05-16T06:24:44,K558LL9Z.580W,Long,0.3969,0.4004,0.991,0.2,0
1aecf582-66a2-4ebb-80f9-04b3aeba331a,BE9558,2026-05-16T06:27:39,K558LL9Z.A30W,Long,0.3915,0.3955,0.990,0.2,0
885aedfd-7a1a-4120-8176-7c344dd3d8fe,BE9558,2026-05-16T06:30:30,K558LL9Z.EU0W,Long,0.4025,0.4053,0.993,0.2,0
ec15930f-47f5-4752-afc2-427ee156ac95,BE9558,2026-05-16T06:33:25,K558LL9Z.JP0W,Long,0.4060,0.4102,0.990,0.2,0
5ca23f47-2a38-4a54-99dd-041287aa9510,BE9558,2026-05-16T06:36:17,K558LL9Z.OH0W,Long,0.4054,0.4102,0.988,0.2,0
03f371cf-81bc-4681-80f0-ef6fa437da85,BE9558,2026-05-16T06:39:09,K558LL9Z.T90W,Long,0.4052,0.4102,0.988,0.2,0
ed386f54-140d-45e8-ad51-6585a58b4375,BE9558,2026-05-16T06:44:54,K558LLA0.2U0W,Long,0.3993,0.4004,0.997,0.2,0
579f1c3f-4c1e-42a3-aa89-69aa93514033,BE9558,2026-05-16T06:47:47,K558LLA0.7N0W,Long,0.4001,0.4053,0.987,0.2,0
57024de6-07ea-41f4-b916-c6adc3f51636,BE9558,2026-05-16T06:50:40,K558LLA0.CG0W,Long,0.4103,0.4150,0.989,0.2,0
36bf5adf-afb5-4a5e-a106-1afbd1f56c7b,BE9558,2026-05-16T06:54:49,K558LLA0.JD0W,Long,0.4069,0.4150,0.980,0.2,0
3e2f831b-5228-46ff-9acb-75d8c86f8bc1,BE9558,2026-05-16T06:57:43,K558LLA0.O70W,Long,0.4108,0.4150,0.990,0.2,0
1775fa20-568b-4294-b9ca-561201a66c5b,BE9558,2026-05-16T07:00:38,K558LLA0.T20W,Long,0.3967,0.4004,0.991,0.2,0
fd391469-03f9-4d8d-bccd-3af50c91e5b7,BE9558,2026-05-16T07:03:33,K558LLA0.XX0W,Long,0.3927,0.3955,0.993,0.2,0
02b52ef6-b707-4dcb-b58f-43da02698832,BE9558,2026-05-16T07:06:27,K558LLA1.2R0W,Long,0.3824,0.3857,0.991,0.2,0
8d45333f-e101-4249-9e27-913c583a0a8d,BE9558,2026-05-16T07:09:21,K558LLA1.7L0W,Long,0.4085,0.4150,0.984,0.2,0
361d11ce-f42a-4d04-8270-ee3771fe4f09,BE9558,2026-05-16T07:12:14,K558LLA1.CE0W,Long,0.4017,0.4053,0.991,0.2,0
59218125-ed5d-4457-aa8b-35ba03441363,BE9558,2026-05-16T07:15:07,K558LLA1.H70W,Long,0.3934,0.3955,0.995,0.2,0
a603e55a-2ad6-4fc9-8c8c-0dc7be95c3e7,BE9558,2026-05-16T07:23:43,K558LLA1.VJ0W,Long,0.3806,0.3857,0.987,0.2,0
c8d07902-93ea-4b03-9e69-9ad6ed5bffb1,BE9558,2026-05-16T07:26:36,K558LLA2.0C0W,Long,0.3807,0.3857,0.987,0.2,0
4c46c0c7-42f0-4648-827e-1995f733b18f,BE9558,2026-05-16T07:30:44,K558LLA2.780W,Long,0.3667,0.3711,0.988,0.2,0
04759a00-ba3e-4959-a4cb-be8fc1f3004e,BE9558,2026-05-16T07:36:28,K558LLA2.GS0W,Long,0.3514,0.3516,1.000,0.2,0
0b6b0856-bd87-4a07-a5b4-f13d99e04a12,BE9558,2026-05-16T07:39:20,K558LLA2.LK0W,Long,0.3512,0.3516,0.999,0.2,0
3d81a8bd-464d-4050-8a76-25e8373d1ddb,BE9558,2026-05-16T07:42:12,K558LLA2.QC0W,Long,0.3350,0.3369,0.994,0.2,0
b8b9c0c4-c388-4acb-955a-be4ac356afce,BE9558,2026-05-16T07:45:04,K558LLA2.V40W,Long,0.3563,0.3564,1.000,0.2,0
cb3d142a-fb84-4a21-a298-f61bb869b036,BE9558,2026-05-16T07:49:13,K558LLA3.210W,Long,0.3663,0.3711,0.987,0.2,0
7401b19b-bc9d-43f0-b395-f4323aca5c72,BE9558,2026-05-16T07:52:06,K558LLA3.6U0W,Long,0.3612,0.3662,0.986,0.2,0
2236df76-a9e6-401f-9176-ad565242f2cf,BE9558,2026-05-16T07:57:52,K558LLA3.GG0W,Long,0.3366,0.3369,0.999,0.2,0
a645846c-cae4-4aa5-a2e6-85166bd4dd62,BE9558,2026-05-16T08:00:44,K558LLA3.L80W,Long,0.3265,0.3271,0.998,0.2,0
7212bd33-99a9-4659-9f0b-c98cc8d1e8bc,BE9558,2026-05-16T08:04:51,K558LLA3.S30W,Long,0.3418,0.3467,0.986,0.2,0
2cc4bf33-c63a-4c65-b0e2-5e61a9146a5d,BE9558,2026-05-16T08:07:43,K558LLA3.WV0W,Long,0.3405,0.3418,0.996,0.2,0
4fedb486-5f1f-4623-a01f-083e829f0565,BE9558,2026-05-16T08:10:35,K558LLA4.1N0W,Long,0.3515,0.3564,0.986,0.2,0
58aff0ba-0f9b-45e1-9bbe-a990d16192ae,BE9558,2026-05-16T08:13:27,K558LLA4.6F0W,Long,0.3513,0.3516,0.999,0.2,0
e56d87e5-e1d4-4947-b6a5-3bbd2773c54a,BE9558,2026-05-16T08:20:03,K558LLA4.HF0W,Long,0.3564,0.3613,0.986,0.2,0
0e96e61e-6a21-4e07-8e09-72d09dbfa1e6,BE9558,2026-05-16T08:25:21,K558LLA4.Q90W,Long,0.3565,0.3613,0.987,0.2,0
19611f28-2da8-4362-a58e-dbed2e061379,BE9558,2026-05-16T08:34:19,K558LLA5.570W,Long,0.3647,0.3662,0.996,0.2,0
bd580c1d-44d4-41fd-9f83-f462cda4099a,BE9558,2026-05-16T08:37:15,K558LLA5.A30W,Long,0.3536,0.3564,0.992,0.2,0
2782df3b-3cb4-471a-a6f5-bbc4903a8ab9,BE9558,2026-05-16T08:44:00,K558LLA5.LC0W,Long,0.3612,0.3662,0.986,0.2,0
d15a08f3-1c7c-4f80-8d9b-f5008c58c3d9,BE9558,2026-05-16T08:49:18,K558LLA5.U60W,Long,0.3610,0.3613,0.999,0.2,0
03a10a6a-193a-476c-9543-f63818f69417,BE9558,2026-05-16T08:54:36,K558LLA6.300W,Long,0.3515,0.3516,1.000,0.2,0
1c271856-8100-4c0d-bc8c-9357b47d7626,BE9558,2026-05-16T08:59:54,K558LLA6.BU0W,Long,0.3617,0.3662,0.988,0.2,0
a85f125e-bfa2-42be-b877-2604b8d068c8,BE9558,2026-05-16T09:05:17,K558LLA6.KT0W,Long,0.3510,0.3516,0.998,0.2,0
dde9aa71-d2e3-41ac-8388-f2bbddb6dae6,BE9558,2026-05-16T09:08:11,K558LLA6.PN0W,Long,0.3447,0.3467,0.994,0.2,0
2f3f2be2-0ee3-422e-b3ad-83fb87512a2b,BE9558,2026-05-16T09:14:39,K558LLA7.0F0W,Long,0.3580,0.3613,0.991,0.2,0
357a3034-8a9c-485e-8cb6-f526dd2baf6f,BE9558,2026-05-16T09:29:11,K558LLA7.ON0W,Long,0.3708,0.3760,0.986,0.2,0
f8ad0274-8e6f-4714-82ff-d229e60f1442,BE9558,2026-05-16T09:32:06,K558LLA7.TI0W,Long,0.3567,0.3613,0.987,0.2,0
42bb007a-2726-401a-b085-c25151b0dc24,BE9558,2026-05-16T09:35:02,K558LLA7.YE0W,Long,0.3575,0.3613,0.989,0.2,0
c99bfc4a-db02-4bea-bea4-943c67485dba,BE9558,2026-05-16T09:37:58,K558LLA8.3A0W,Long,0.3527,0.3564,0.989,0.2,0
8fc17de0-73f7-48bd-8d93-5451dce47e8e,BE9558,2026-05-16T09:40:52,K558LLA8.840W,Long,0.3613,0.3662,0.987,0.2,0
bbee5276-03dd-4ca4-a7b9-aec02baac7e8,BE9558,2026-05-16T09:48:13,K558LLA8.KD0W,Long,0.3590,0.3613,0.993,0.2,0
8dcdee10-db01-4224-9506-4181c3105d6f,BE9558,2026-05-16T09:53:31,K558LLA8.T70W,Long,0.3588,0.3613,0.993,0.2,0
48c8be72-64d9-4da3-95b5-bbec2c5e1dbd,BE9558,2026-05-16T09:58:49,K558LLA9.210W,Long,0.3582,0.3662,0.978,0.2,0
0da20919-7ce9-4feb-8ae9-12d9bb40c2b5,BE9558,2026-05-16T10:04:07,K558LLA9.AV0W,Long,0.3506,0.3516,0.997,0.2,0
c2f7e9bc-8b93-42c3-96d3-e3af217dde35,BE9558,2026-05-16T10:09:25,K558LLA9.JP0W,Long,0.3506,0.3516,0.997,0.2,0
522a0e42-d443-4447-bc71-af1832c6604e,BE9558,2026-05-16T10:14:43,K558LLA9.SJ0W,Long,0.3624,0.3662,0.990,0.2,0
67f7e732-3c0b-439f-87c5-3c478a381418,BE9558,2026-05-16T10:20:01,K558LLAA.1D0W,Long,0.3494,0.3516,0.994,0.2,0
251767e8-56f7-4091-a001-364d8e75c15c,BE9558,2026-05-16T10:25:19,K558LLAA.A70W,Long,0.3463,0.3516,0.985,0.2,0
9457239d-a4ca-4476-b385-5e01fc8f6420,BE9558,2026-05-16T10:30:37,K558LLAA.J10W,Long,0.3436,0.3467,0.991,0.2,0
43718d7c-9353-49e1-89b6-0841aeb1b276,BE9558,2026-05-16T10:35:55,K558LLAA.RV0W,Long,0.3452,0.3516,0.982,0.2,0
f54ba557-ddfe-41d3-8f4c-8bbec9a3783c,BE9558,2026-05-16T10:41:13,K558LLAB.0P0W,Long,0.3419,0.3467,0.986,0.2,0
dc26c758-ad99-49c1-b518-931368cdf8cf,BE9558,2026-05-16T10:46:31,K558LLAB.9J0W,Long,0.3463,0.3516,0.985,0.2,0
10917eb2-d151-461c-a8cb-e9660da5a5b0,BE9558,2026-05-16T10:51:49,K558LLAB.ID0W,Long,0.3520,0.3564,0.987,0.2,0
4938a5e6-d53b-40ee-be2b-06ec0e60398c,BE9558,2026-05-16T10:57:07,K558LLAB.R70W,Long,0.3541,0.3564,0.993,0.2,0
0711b51d-55bd-48be-b51e-2aad67107a60,BE9558,2026-05-16T11:13:01,K558LLAC.HP0W,Long,0.3661,0.3711,0.986,0.2,0
065564b6-aa49-40e7-9ea6-c75defdc60fe,BE9558,2026-05-16T11:18:19,K558LLAC.QJ0W,Long,0.3622,0.3662,0.989,0.2,0
ffb6b230-1d70-4e0e-ba30-e945339a122a,BE9558,2026-05-16T11:23:37,K558LLAC.ZD0W,Long,0.3711,0.3760,0.987,0.2,0
52b4da82-c1e0-4a8a-8365-51b090787005,BE9558,2026-05-16T11:28:55,K558LLAD.870W,Long,0.3644,0.3662,0.995,0.2,0
cdbff3d8-fbfe-4bea-8bd6-c898800e81ba,BE9558,2026-05-16T11:39:31,K558LLAD.PV0W,Long,0.3609,0.3662,0.986,0.2,0
3fb0bc30-1463-4cfc-9e7f-386c0eb2a34a,BE9558,2026-05-16T11:44:49,K558LLAD.YP0W,Long,0.3553,0.3564,0.997,0.2,0
ba1f5ec8-aef7-4a9e-ac1f-276cf016e285,BE9558,2026-05-16T11:50:07,K558LLAE.7J0W,Long,0.3479,0.3516,0.990,0.2,0
b1dd4df7-34a9-4512-a903-f8242b236fd2,BE9558,2026-05-16T11:55:25,K558LLAE.GD0W,Long,0.3427,0.3467,0.988,0.2,0
1f23aa28-c026-4bc7-b3d1-7c78fd76a673,BE9558,2026-05-16T12:00:43,K558LLAE.P70W,Long,0.3454,0.3467,0.996,0.2,0
0d91f54d-b20d-4a50-b7dd-d071c39a0690,BE9558,2026-05-16T12:06:01,K558LLAE.Y10W,Long,0.3431,0.3467,0.990,0.2,0
12ccdecd-5fd9-4465-9813-3d6006ec32f3,BE9558,2026-05-16T12:11:19,K558LLAF.6V0W,Long,0.3433,0.3467,0.990,0.2,0
a7024f1a-f071-48ab-820f-99bdf87366b5,BE9558,2026-05-16T12:16:37,K558LLAF.FP0W,Long,0.3361,0.3369,0.998,0.2,0
de0fa439-30b8-4607-a3c3-7e17191e4624,BE9558,2026-05-16T12:21:55,K558LLAF.OJ0W,Long,0.3274,0.3320,0.986,0.2,0
f9374ec3-05e5-477f-8e1a-0c862fed2a50,BE9558,2026-05-16T12:27:13,K558LLAF.XD0W,Long,0.3449,0.3467,0.995,0.2,0
424cb275-3743-4174-95f0-0ca1205b374c,BE9558,2026-05-16T12:32:31,K558LLAG.670W,Long,0.3370,0.3418,0.986,0.2,0
9accde13-cefa-41b8-bd0a-cef2ffed59b0,BE9558,2026-05-16T12:37:49,K558LLAG.F10W,Long,0.3465,0.3467,0.999,0.2,0
4665be38-1956-4b14-b931-068ba9af5c5e,BE9558,2026-05-16T12:48:25,K558LLAG.WP0W,Long,0.3453,0.3516,0.982,0.2,0
1aedf624-1a99-43e1-a8f2-f9d358b97f61,BE9558,2026-05-16T12:53:43,K558LLAH.5J0W,Long,0.3366,0.3418,0.985,0.2,0
c15e1799-91d7-425e-ad17-2ba3d170d81e,BE9558,2026-05-16T13:04:19,K558LLAH.N70W,Long,0.3348,0.3369,0.994,0.2,0
72d4c4ea-19ca-4cc6-9b04-7a2b70122c67,BE9558,2026-05-16T13:09:37,K558LLAH.W10W,Long,0.3272,0.3320,0.986,0.2,0
b4ebf2c9-1f6d-4594-9810-40479e87c0a5,BE9558,2026-05-16T13:14:55,K558LLAI.4V0W,Long,0.3297,0.3320,0.993,0.2,0
bb297e9e-548f-4dae-8b1a-0f161af2e766,BE9558,2026-05-16T13:20:13,K558LLAI.DP0W,Long,0.3272,0.3320,0.986,0.2,0
87562c24-63db-48bd-9962-72a20a40f2ff,BE9558,2026-05-16T13:36:07,K558LLAJ.470W,Long,0.3174,0.3223,0.985,0.2,0
01e9cc58-3bea-4f38-8499-a2c20e5f8550,BE9558,2026-05-16T13:46:52,K558LLAJ.M40W,Long,0.2880,0.2930,0.983,0.2,0
5ae7503d-ae17-4063-9208-6a420699e1ab,BE9558,2026-05-16T14:00:35,K558LLAK.8Z0W,Long,0.2879,0.2930,0.983,0.2,0
e009ea3c-1534-4154-8623-e180ed4db9fb,BE9558,2026-05-16T14:06:19,K558LLAK.IJ0W,Long,0.2882,0.2930,0.984,0.2,0
cd4e21f5-512b-4b2b-8054-bec01aa06400,BE9558,2026-05-16T14:12:03,K558LLAK.S30W,Long,0.2857,0.2930,0.975,0.2,0
ae5b780f-2038-4ccf-8bfc-b15b87be139e,BE9558,2026-05-16T14:17:22,K558LLAL.0Y0W,Long,0.2899,0.2930,0.989,0.2,0
d8c3fb81-8c66-4ebc-b33a-0559bc03334b,BE9558,2026-05-16T14:22:40,K558LLAL.9S0W,Long,0.3009,0.3027,0.994,0.2,0
990a4c7a-3c51-4d4a-8ab7-416ccb97d29c,BE9558,2026-05-16T14:27:58,K558LLAL.IM0W,Long,0.3057,0.3076,0.994,0.2,0
68d7a2c3-d899-4e75-96fb-3bf16ae6ea6f,BE9558,2026-05-16T14:33:16,K558LLAL.RG0W,Long,0.3110,0.3125,0.995,0.2,0
73505b8c-f912-4116-b903-a8a4c75524d3,BE9558,2026-05-16T14:38:34,K558LLAM.0A0W,Long,0.3172,0.3223,0.984,0.2,0
8d3c9602-7efa-488a-801b-3228bd85ab14,BE9558,2026-05-16T14:43:51,K558LLAM.930W,Long,0.3136,0.3174,0.988,0.2,0
243e16ee-860a-4960-bc15-b797ad7e9735,BE9558,2026-05-16T14:49:08,K558LLAM.HW0W,Long,0.3135,0.3174,0.988,0.2,0
e90c8d90-6d41-4788-9ee6-a29e4bfcc16b,BE9558,2026-05-16T15:19:35,K558LLAN.WN0W,Long,0.3132,0.3174,0.987,0.2,0
4182b0e7-7811-46b8-87d1-a4dd0c152f3b,BE9558,2026-05-16T15:28:45,K558LLAO.BX0W,Long,0.3023,0.3076,0.983,0.2,0
28a790da-0e48-4fe4-b8ba-2c82cc6bfa79,BE9558,2026-05-16T15:34:02,K558LLAO.KQ0W,Long,0.3176,0.3223,0.985,0.2,0
093d2fa3-7a4b-4f0f-abda-71155ebe2dfb,BE9558,2026-05-16T15:39:19,K558LLAO.TJ0W,Long,0.3223,0.3271,0.985,0.2,0
68dc9560-4082-49b6-af04-9244773ffbc1,BE9558,2026-05-16T15:44:36,K558LLAP.2C0W,Long,0.3227,0.3271,0.986,0.2,0
ad6b268a-165d-4b1d-b0b3-f58db7c9b0e4,BE9558,2026-05-16T15:49:53,K558LLAP.B50W,Long,0.3177,0.3223,0.986,0.2,0
046c5cb4-56b3-48c0-83c2-bf1f30837940,BE9558,2026-05-16T15:55:10,K558LLAP.JY0W,Long,0.3174,0.3223,0.985,0.2,0
1b76edf4-3b1c-4bcb-a73c-27334981c350,BE9558,2026-05-16T16:00:27,K558LLAP.SR0W,Long,0.3127,0.3174,0.985,0.2,0
a0264171-a682-4396-ad8a-cda3b2964533,BE9558,2026-05-16T16:06:55,K558LLAQ.3J0W,Long,0.2885,0.2930,0.985,0.2,0
707da1f6-ee81-4e57-abd5-98295c14651b,BE9558,2026-05-16T16:12:30,K558LLAQ.CU0W,Long,0.2880,0.2930,0.983,0.2,0
b8115b64-8739-42c8-b541-713ab6b68bcd,BE9558,2026-05-16T16:17:53,K558LLAQ.LT0W,Long,0.2881,0.2930,0.983,0.2,0
fb179c36-fef1-4df6-b0a0-2bd7792ea910,BE9558,2026-05-16T16:23:11,K558LLAQ.UN0W,Long,0.2933,0.2979,0.985,0.2,0
0cec8793-c3c1-486b-a33a-4dbf9cb069b0,BE9558,2026-05-16T16:33:46,K558LLAR.CA0W,Long,0.3017,0.3027,0.997,0.2,0
c531b052-ee04-4c66-888b-21e97445a615,BE9558,2026-05-16T16:49:37,K558LLAS.2P0W,Long,0.2922,0.2979,0.981,0.2,0
0dc402f9-cab6-4c4a-8317-b8fc3c4b1ced,BE9558,2026-05-16T16:55:08,K558LLAS.BW0W,Long,0.2898,0.2930,0.989,0.2,0
fd73733e-b42d-4a51-81d0-4acad6edfbd4,BE9558,2026-05-16T17:16:17,K558LLAT.B50W,Long,0.3115,0.3125,0.997,0.2,0
6a254daa-ae27-4ac1-b334-58f776a6b276,BE9558,2026-05-16T17:26:51,K558LLAT.SR0W,Long,0.3174,0.3223,0.985,0.2,0
0cc8e82f-5270-4508-beae-0d3af56095ca,BE9558,2026-05-16T17:37:27,K558LLAU.AF0W,Long,0.2899,0.2930,0.989,0.2,0
00557a73-8dc3-4cd2-b880-c7820dc8b171,BE9558,2026-05-16T17:43:17,K558LLAU.K50W,Long,0.2881,0.2930,0.983,0.2,0
8e5518d9-ff0a-4c09-9cf9-a681c84c0b6e,BE9558,2026-05-16T17:53:53,K558LLAV.1T0W,Long,0.2898,0.2930,0.989,0.2,0
91dbd7e9-7344-400b-82b1-379f2ac4b49a,BE9558,2026-05-16T17:59:11,K558LLAV.AN0W,Long,0.2925,0.2930,0.998,0.2,0
fa256408-d480-4376-95b5-d1a549c483ea,BE9558,2026-05-16T18:04:29,K558LLAV.JH0W,Long,0.2977,0.3027,0.983,0.2,0
4ab6e66a-8364-49b6-82f1-86e86199e676,BE9558,2026-05-16T18:09:46,K558LLAV.SA0W,Long,0.2944,0.2979,0.988,0.2,0
0a65fb7c-96e1-4ba0-85de-4620d88658c1,BE9558,2026-05-16T18:15:03,K558LLAW.130W,Long,0.2965,0.2979,0.995,0.2,0
92b1ef3e-1696-4123-8662-163947737c83,BE9558,2026-05-16T18:20:20,K558LLAW.9W0W,Long,0.2976,0.3027,0.983,0.2,0
9e3cb24c-4426-4220-9a73-389d0a96c94f,BE9558,2026-05-16T18:25:37,K558LLAW.IP0W,Long,0.2983,0.3027,0.985,0.2,0
a3473215-4c46-45ab-9aa7-1720486ec4a8,BE9558,2026-05-16T18:30:54,K558LLAW.RI0W,Long,0.2956,0.2979,0.993,0.2,0
449665b1-47c8-4bd2-984c-8f45b627e6d8,BE9558,2026-05-16T18:36:11,K558LLAX.0B0W,Long,0.2989,0.3027,0.987,0.2,0
600cfabc-cffd-42e1-800c-70e75f312316,BE9558,2026-05-16T20:00:12,K558LLB0.WC0W,Long,0.3077,0.3125,0.985,0.2,0
12bf5944-0194-4f5b-b486-a7acd7141c7f,BE9558,2026-05-16T20:04:28,K558LLB1.3G0W,Long,0.2888,0.2930,0.986,0.2,0
f1fc913a-91bc-4240-a595-7dfe3091f9a2,BE9558,2026-05-16T20:07:29,K558LLB1.8H0W,Long,0.2977,0.3027,0.983,0.2,0
e74f7ec3-20bb-4177-beb2-e802e5f801fd,BE9558,2026-05-16T20:10:26,K558LLB1.DE0W,Long,0.2978,0.3027,0.984,0.2,0
27491c3a-b631-4643-818a-714523911178,BE9558,2026-05-16T20:16:21,K558LLB1.N90W,Long,0.2921,0.2930,0.997,0.2,0
9d9196ce-11e2-4f28-b01c-3dcc60e60d42,BE9558,2026-05-16T20:22:28,K558LLB1.XG0W,Long,0.2881,0.2930,0.983,0.2,0
a592d7c8-b643-4b25-9186-3d611ae22709,BE9558,2026-05-16T20:25:37,K558LLB2.2P0W,Long,0.2893,0.2930,0.987,0.2,0
f709a3d5-27cd-4bb1-b91c-669e8ea11d77,BE9558,2026-05-16T20:28:57,K558LLB2.890W,Long,0.2880,0.2930,0.983,0.2,0
cc9cad87-b87f-4b67-854a-ffb21e876a92,BE9558,2026-05-16T20:32:45,K558LLB2.EL0W,Long,0.2873,0.2930,0.980,0.2,0
10732d26-6b49-4b14-a474-6c75e259d278,BE9558,2026-05-16T20:49:32,K558LLB3.6K0W,Long,0.2881,0.2930,0.983,0.2,0
aa63957a-fdb2-4f17-af52-a63bb015119d,BE9558,2026-05-16T21:21:45,K558LLB4.O90W,Long,0.2880,0.2930,0.983,0.2,0
8350440f-019d-45a4-b9f9-23058628e6f0,BE9558,2026-05-16T21:32:43,K558LLB5.6J0W,Long,0.2925,0.2930,0.999,0.2,0
edfc10b2-dbe1-4527-a061-b0d670b5e5d2,BE9558,2026-05-16T21:35:37,K558LLB5.BD0W,Long,0.2891,0.2930,0.987,0.2,0
f98001a3-88b2-4830-8112-b7c5164e99c3,BE9558,2026-05-16T21:38:40,K558LLB5.GG0W,Long,0.2877,0.2930,0.982,0.2,0
f1e53e7b-b124-4fc5-82c2-504fb0c8b80d,BE9558,2026-05-16T21:41:46,K558LLB5.LM0W,Long,0.2881,0.2930,0.983,0.2,0
7890637f-142e-4775-b48c-fd4f3b8ada77,BE9558,2026-05-16T21:45:14,K558LLB5.RE0W,Long,0.2880,0.2930,0.983,0.2,0
7c97c10f-b413-467c-9b56-c18e423cdcfa,BE9558,2026-05-16T21:48:26,K558LLB5.WQ0W,Long,0.2886,0.2930,0.985,0.2,0
8178cf22-8428-4f85-8199-0a43f7334a8f,BE9558,2026-05-16T21:51:47,K558LLB6.2B0W,Long,0.2881,0.2930,0.983,0.2,0
eceb2997-deb4-403a-802f-50e93d23d423,BE9558,2026-05-16T21:57:18,K558LLB6.BI0W,Long,0.2881,0.2930,0.984,0.2,0
9c26690c-1983-4b21-b8af-7c7967c014c3,BE9558,2026-05-16T22:12:21,K558LLB7.0L0W,Long,0.2876,0.2930,0.982,0.2,0
78f67fc3-08b7-4317-96ba-ee5544e0b95b,BE9558,2026-05-16T22:19:34,K558LLB7.CM0W,Long,0.2880,0.2930,0.983,0.2,0
7f9dad14-4f1b-492d-aa26-845a908ea894,BE9558,2026-05-16T22:27:40,K558LLB7.Q40W,Long,0.2881,0.2930,0.983,0.2,0
f75c52b4-21b9-4065-baeb-5cfbd27d130a,BE9558,2026-05-16T22:33:50,K558LLB8.0E0W,Long,0.2881,0.2930,0.984,0.2,0
10f7496d-fa76-40a7-8bef-dc14e8a41869,BE9558,2026-05-16T22:40:48,K558LLB8.C00W,Long,0.2878,0.2930,0.982,0.2,0
1 event_id serial timestamp filename channel offset_ips peak_ips mean_over_peak trigger_level_ips already_flagged_ft
2 1e7a7808-034c-423b-80e9-d6788da80993 BE18438 2025-11-15T08:57:40 T438LBX4.W40W Vert 0.2722 0.2930 0.929 0.2 0
3 346e383f-c5a1-41d1-b972-3d652e599d39 BE18438 2025-11-15T09:13:15 T438LBX5.M30W Vert 0.2747 0.2930 0.938 0.2 0
4 45ef3023-22c5-44a8-a606-a0900bc17861 BE18438 2025-11-15T09:16:13 T438LBX5.R10W Vert 0.2929 0.3027 0.967 0.2 0
5 1cbcd2aa-ec55-4e2f-af42-7178f26cc6a1 BE18438 2025-11-15T09:19:29 T438LBX5.WH0W Vert 0.2816 0.2979 0.945 0.2 0
6 caf43634-4528-4fd5-9674-5f4f563661c0 BE18438 2025-11-15T09:22:32 T438LBX6.1K0W Vert 0.2883 0.2930 0.984 0.2 0
7 456ae646-c834-4e5c-82f1-7df18b3440a1 BE18438 2025-11-15T09:25:31 T438LBX6.6J0W Vert 0.3189 0.3223 0.989 0.2 0
8 afb91ba2-351b-42a0-b33f-acebd5f1829d BE18438 2025-11-15T09:28:29 T438LBX6.BH0W Vert 0.3057 0.3076 0.994 0.2 0
9 39847146-3537-4300-943d-01c0c771e9cd BE18438 2025-11-15T09:31:26 T438LBX6.GE0W Vert 0.3225 0.3271 0.986 0.2 0
10 e47335c1-fc3f-4c90-88c6-8edd0f296ce4 BE18438 2025-11-15T09:34:24 T438LBX6.LC0W Vert 0.3275 0.3320 0.986 0.2 0
11 25b6eda6-ba98-422f-8834-94b6cbe34971 BE18438 2025-11-15T09:37:22 T438LBX6.QA0W Vert 0.3398 0.3418 0.994 0.2 0
12 7af99377-e47f-4914-8e91-ac7f7f50b8c6 BE18438 2025-11-15T09:40:20 T438LBX6.V80W Vert 0.3515 0.3564 0.986 0.2 0
13 c4330605-c257-49ef-aede-20deb641e7d7 BE18438 2025-11-15T10:09:48 T438LBX8.8C0W Vert 0.3605 0.3955 0.912 0.2 0
14 b665caf9-64ee-4352-a391-60c1ddeebc1e BE18438 2026-02-25T10:58:04 T438LH66.GS0W Vert 0.1803 0.1953 0.923 0.2 0
15 3b0c32c3-fd16-4b83-9917-942a56dea168 BE18438 2026-02-25T18:12:04 T438LH6Q.K40W Vert 0.1869 0.1953 0.957 0.2 0
16 ca66e601-d10f-4424-9c26-08a688e7b08c BE18438 2026-02-25T18:17:16 T438LH6Q.SS0W Vert 0.1870 0.1953 0.958 0.2 0
17 31aa30ba-eb0a-49a9-98ca-c77d2cc31275 BE18438 2026-02-25T18:21:11 T438LH6Q.ZB0W Vert 0.1868 0.1953 0.956 0.2 0
18 fdb55a93-fc91-4fdf-a7f4-fdd1a6b48f59 BE18438 2026-02-25T18:26:27 T438LH6R.830W Vert 0.1893 0.1953 0.969 0.2 0
19 cbd718d7-2378-4d74-8656-842f229d19a8 BE18438 2026-02-25T18:33:25 T438LH6R.JP0W Vert 0.1887 0.1953 0.966 0.2 0
20 bfaf58ec-6163-47eb-9d2a-70da880bd948 BE18438 2026-02-25T18:37:48 T438LH6R.R00W Vert 0.1872 0.1953 0.959 0.2 0
21 ddaa530b-886e-4415-b93a-f4ebf4c4a882 BE18438 2026-02-25T18:59:54 T438LH6S.RU0W Vert 0.1874 0.1953 0.959 0.2 0
22 57f15284-ab69-48fc-9660-8c347c80c681 BE18438 2026-02-25T19:15:58 T438LH6T.IM0W Vert 0.1873 0.1953 0.959 0.2 0
23 03715718-7aa8-4e1d-9b0b-c2ab75fc1975 BE18438 2026-02-25T19:19:58 T438LH6T.PA0W Vert 0.1891 0.1953 0.968 0.2 0
24 9f921cd5-1bf9-4713-aef6-41e7f780eff1 BE18438 2026-02-25T19:24:02 T438LH6T.W20W Vert 0.1871 0.1953 0.958 0.2 0
25 44994949-58d4-44fa-bd78-ed75b8acc667 BE18438 2026-02-25T19:44:57 T438LH6U.UX0W Vert 0.1877 0.1953 0.961 0.2 0
26 c4be01c3-1001-4e17-aecd-d6d26dbb09f3 BE18438 2026-02-25T19:49:19 T438LH6V.270W Vert 0.1884 0.1953 0.964 0.2 0
27 3db004e6-ee34-43c5-ae8e-f22894ead5d0 BE18438 2026-02-25T20:08:22 T438LH6V.XY0W Vert 0.1878 0.1953 0.962 0.2 0
28 d276ae48-0434-41e5-af43-e0fb366acf11 BE18438 2026-02-25T20:11:33 T438LH6W.390W Vert 0.1880 0.1953 0.963 0.2 0
29 c027dc12-88fd-4a45-872b-a6a945f2008e BE18438 2026-02-25T20:14:35 T438LH6W.8B0W Vert 0.1874 0.1953 0.959 0.2 0
30 9665bc3a-3d08-4852-b008-37ef8bfd0023 BE18438 2026-02-25T20:18:51 T438LH6W.FF0W Vert 0.1884 0.1953 0.965 0.2 0
31 5fb5a05e-d7e2-4268-9b85-cfe8d82aa6c9 BE18438 2026-02-25T20:29:50 T438LH6W.XQ0W Vert 0.1890 0.1953 0.968 0.2 0
32 57ec0b10-9324-4459-a07e-0c8532b8928f BE18438 2026-02-25T20:35:39 T438LH6X.7F0W Vert 0.1889 0.1953 0.967 0.2 0
33 ac86f73f-1174-4fae-a206-ecdcb73e1ffc BE18438 2026-02-25T20:39:12 T438LH6X.DC0W Vert 0.1887 0.1953 0.966 0.2 0
34 dcf25ddd-9cf0-41c1-b109-f3ef2e490ce5 BE18438 2026-02-25T20:43:41 T438LH6X.KT0W Vert 0.1871 0.1953 0.958 0.2 0
35 aa79bbdd-2392-4ef6-8a5c-873a9f72746d BE18438 2026-02-25T20:46:51 T438LH6X.Q30W Vert 0.1877 0.1953 0.961 0.2 0
36 ad46d1ce-b417-4c8c-b029-bb3b008ba809 BE18438 2026-02-25T20:53:33 T438LH6Y.190W Vert 0.1882 0.1953 0.964 0.2 0
37 3d3a8f34-86a7-4d70-a7e8-fa768a723325 BE18438 2026-02-26T07:03:39 T438LH7Q.A30W Vert 0.1809 0.1953 0.926 0.2 0
38 7817525f-dc3d-4f5e-b2cb-5af9ca12ede8 BE18438 2026-02-26T07:09:42 T438LH7Q.K60W Vert 0.1814 0.1953 0.929 0.2 0
39 a2091302-0b34-46c1-ab83-174be2b59bcf BE18438 2026-02-26T13:12:35 T438LH87.CZ0W Vert 0.1896 0.1953 0.971 0.2 0
40 e1c0c9de-a900-479f-9572-9675b13296a9 BE18438 2026-02-26T13:24:46 T438LH87.XA0W Vert 0.2237 0.2588 0.864 0.2 0
41 76a6dc6b-88e1-434b-a137-f5e9b63f248e BE18438 2026-02-26T13:27:43 T438LH88.270W Vert 0.3185 0.3223 0.988 0.2 0
42 281b508b-7982-4668-86af-9b0b28be608a BE18438 2026-02-26T13:30:36 T438LH88.700W Vert 0.3263 0.3320 0.983 0.2 0
43 68bbaf77-bb23-40fd-94f9-f928728d90dc BE18438 2026-02-26T13:33:28 T438LH88.BS0W Vert 0.3207 0.3271 0.980 0.2 0
44 5c975640-6ff1-441a-aa11-41642f6a6b31 BE18438 2026-02-26T13:36:21 T438LH88.GL0W Vert 0.3261 0.3320 0.982 0.2 0
45 dea248ac-1124-4bba-b054-953f86c852b2 BE18438 2026-02-26T13:40:34 T438LH88.NM0W Vert 0.3271 0.3320 0.985 0.2 0
46 4e463201-f008-41ad-9c52-11fcc3d93095 BE18438 2026-02-26T13:43:29 T438LH88.SH0W Vert 0.3357 0.3418 0.982 0.2 0
47 507262c5-d58f-4a05-a6a3-a6cbb5b4de20 BE18438 2026-02-26T13:46:24 T438LH88.XC0W Vert 0.3372 0.3418 0.987 0.2 0
48 4c2d8ee8-842f-4e44-9e03-ff34d26e4fdb BE18438 2026-02-26T13:49:17 T438LH89.250W Vert 0.3253 0.3320 0.980 0.2 0
49 b184b112-603f-44f4-ae97-087493fbd8ce BE18438 2026-02-26T13:52:10 T438LH89.6Y0W Vert 0.3321 0.3369 0.986 0.2 0
50 2ff1a552-5a2e-4396-9083-b9c8d334eed7 BE18438 2026-02-26T13:55:04 T438LH89.BS0W Vert 0.3378 0.3418 0.988 0.2 0
51 928e21a7-1990-4792-803e-58014d8140ce BE18438 2026-02-26T13:57:57 T438LH89.GL0W Vert 0.3341 0.3369 0.992 0.2 0
52 f521b5db-6100-41e6-954e-0abdbf9660c1 BE18438 2026-02-26T14:00:51 T438LH89.LF0W Vert 0.3421 0.3467 0.987 0.2 0
53 efba962f-e511-41ef-9fc5-313f202a9d96 BE18438 2026-02-26T14:03:46 T438LH89.QA0W Vert 0.3506 0.3564 0.984 0.2 0
54 0b51e273-8d10-4494-bda6-8c75eaeec66f BE18438 2026-02-26T14:06:41 T438LH89.V50W Vert 0.3448 0.3516 0.981 0.2 0
55 6d46e4ee-1647-4169-b6b2-33da32240eb9 BE18438 2026-02-26T14:09:35 T438LH89.ZZ0W Vert 0.3463 0.3516 0.985 0.2 0
56 1ca294cd-4dc2-41fb-9374-e277d4550761 BE18438 2026-02-26T14:12:28 T438LH8A.4S0W Vert 0.3442 0.3467 0.993 0.2 0
57 7b683dcf-1aed-4d9b-be1e-b10f92374398 BE18438 2026-02-26T14:15:23 T438LH8A.9N0W Vert 0.3486 0.3516 0.992 0.2 0
58 2b5cb8e7-c947-4914-bcb5-504f74603547 BE18438 2026-02-26T14:18:21 T438LH8A.EL0W Vert 0.3519 0.3613 0.974 0.2 0
59 5ea3a6bf-10de-4911-aedc-66daecf86b76 BE18438 2026-02-26T14:21:16 T438LH8A.JG0W Vert 0.3460 0.3564 0.971 0.2 0
60 d93be7f5-39ec-45fd-9949-fa531f2f9d34 BE18438 2026-02-26T14:24:13 T438LH8A.OD0W Vert 0.3457 0.3516 0.983 0.2 0
61 cfa113f2-8cee-4a1d-b1e7-0e936fa771e2 BE18438 2026-02-26T14:28:21 T438LH8A.V90W Vert 0.3485 0.3564 0.978 0.2 0
62 46d322ac-38cb-4c99-a4c2-9e9d7ad06171 BE18438 2026-02-26T14:31:17 T438LH8B.050W Vert 0.3367 0.3467 0.971 0.2 0
63 42500a83-bd67-4deb-8bb2-963ee2b8a7ce BE18438 2026-02-26T14:34:11 T438LH8B.4Z0W Vert 0.3365 0.3516 0.957 0.2 0
64 3ccf6bda-2e88-473c-951d-9ea86d0d9363 BE18438 2026-02-26T14:37:05 T438LH8B.9T0W Vert 0.3472 0.3564 0.974 0.2 0
65 9050487d-d238-4631-b8e1-5a693a026542 BE18438 2026-02-26T14:39:58 T438LH8B.EM0W Vert 0.3420 0.3564 0.959 0.2 0
66 e62989e4-a326-4bae-8d47-a8becee96462 BE18438 2026-02-26T14:42:52 T438LH8B.JG0W Vert 0.3430 0.3564 0.962 0.2 0
67 f0e30fab-dc57-4189-8439-48df17007a2c BE18438 2026-02-26T14:45:46 T438LH8B.OA0W Vert 0.3389 0.3516 0.964 0.2 0
68 03e1ca09-78df-4c6f-9915-0b6e4f2141d2 BE18438 2026-02-26T14:48:43 T438LH8B.T70W Vert 0.3449 0.3564 0.968 0.2 0
69 945d39f7-1b98-4a1f-80a8-6a18fd9df25f BE18438 2026-02-26T14:51:37 T438LH8B.Y10W Vert 0.3522 0.3613 0.975 0.2 0
70 d27eb2e3-e313-4125-98f4-f9d6d3737d28 BE18438 2026-02-26T14:54:32 T438LH8C.2W0W Vert 0.3502 0.3613 0.969 0.2 0
71 916901cb-ebea-441e-a2a1-40f4e49f32f4 BE18438 2026-02-26T14:57:25 T438LH8C.7P0W Vert 0.3524 0.3662 0.962 0.2 0
72 5d8d7e29-fdbb-4fa3-bd25-506c9352a354 BE18438 2026-02-26T15:01:35 T438LH8C.EN0W Vert 0.3530 0.3613 0.977 0.2 0
73 c6c7a3af-b03b-43dc-97de-024f8e09b62f BE18438 2026-02-26T15:04:27 T438LH8C.JF0W Vert 0.3514 0.3613 0.973 0.2 0
74 b6856898-3d10-4967-9577-7f17902f77ea BE18438 2026-02-26T15:11:34 T438LH8C.VA0W Vert 0.3566 0.3613 0.987 0.2 0
75 7a4802f6-621e-4230-8d8c-d7f0c9a65bf2 BE18438 2026-02-26T15:14:24 T438LH8D.000W Vert 0.3594 0.3711 0.968 0.2 0
76 79f38b7e-ec56-417e-943a-8c944252c2b8 BE18438 2026-02-26T15:18:32 T438LH8D.6W0W Vert 0.3550 0.3613 0.983 0.2 0
77 1b4190c4-0d54-48ba-8ff5-8ddb0eb91e50 BE18438 2026-02-26T15:22:22 T438LH8D.DA0W Vert 0.3571 0.3613 0.988 0.2 0
78 de57b5ae-a3a1-4ede-9d2b-3e87bfb3fd19 BE9558 2026-04-14T11:16:32 K558LJN3.BK0W Tran 0.3448 0.3662 0.942 0.2 0
79 43afeaf5-02ec-41f6-9e23-0c9772821ed4 BE9558 2026-04-14T11:27:15 K558LJN3.TF0W Tran 0.3094 0.3223 0.960 0.2 0
80 8123c0ef-84c9-4f6c-8d82-9dc32e2e470d BE9558 2026-04-14T14:45:30 K558LJNC.ZU0W Tran 0.2721 0.3564 0.763 0.2 0
81 8c787af3-596e-411b-9e10-29485fa5114f BE9558 2026-04-29T16:18:47 K558LKF9.BB0W Tran 0.2943 0.3027 0.972 0.2 0
82 431928ff-b4c4-4caa-b933-acc917f3717c BE9558 2026-05-04T15:02:30 K558LKOF.460W Tran 0.4364 0.5225 0.835 0.2 0
83 6c3c07f8-c36a-4493-acce-7441c9d22cec BE9558 2026-05-15T08:50:06 K558LL8B.7I0W Long 0.2892 0.2930 0.987 0.2 0
84 13c268df-b652-422e-a642-6453f6a314aa BE9558 2026-05-15T10:18:34 K558LL8F.AY0W Long 0.2907 0.2979 0.976 0.2 0
85 9b0d0871-8810-467d-806a-5bbfa4e667fe BE9558 2026-05-15T15:52:00 K558LL8U.QO0W Long 0.2659 0.2979 0.893 0.2 0
86 092640f9-a944-48b7-b872-364d75c2c5e7 BE9558 2026-05-15T16:13:12 K558LL8V.Q00W Long 0.2428 0.2979 0.815 0.2 0
87 0573741a-96ab-4b36-af7a-b5bc11a79009 BE9558 2026-05-16T03:23:26 K558LL9Q.R20W Long 0.2861 0.2930 0.976 0.2 0
88 321f03ea-6696-47de-ad46-2be43d4d6cae BE9558 2026-05-16T03:30:49 K558LL9R.3D0W Long 0.2886 0.2930 0.985 0.2 0
89 cc423a6a-3e3c-466a-b39c-6146ca7f34c8 BE9558 2026-05-16T03:33:55 K558LL9R.8J0W Long 0.2880 0.2881 1.000 0.2 0
90 efa52a14-cc68-4bea-aab4-4ee3a3cbff3a BE9558 2026-05-16T03:36:55 K558LL9R.DJ0W Long 0.2890 0.2930 0.986 0.2 0
91 92895bfe-122f-4cdc-bd3d-40609633d278 BE9558 2026-05-16T03:43:41 K558LL9R.OT0W Long 0.2880 0.2881 1.000 0.2 0
92 2a4c81db-2307-44e5-9b27-d5154d98e38d BE9558 2026-05-16T03:46:36 K558LL9R.TO0W Long 0.2921 0.2979 0.981 0.2 0
93 656b0fdc-e275-4c9c-8936-9eee267ea04e BE9558 2026-05-16T03:49:28 K558LL9R.YG0W Long 0.2966 0.2979 0.996 0.2 0
94 3b9989ae-e0f2-4652-9724-c145603543d2 BE9558 2026-05-16T03:52:29 K558LL9S.3H0W Long 0.2880 0.2930 0.983 0.2 0
95 837d0d84-d609-4f4a-b542-b7e2b064ea22 BE9558 2026-05-16T03:56:32 K558LL9S.A80W Long 0.2880 0.2930 0.983 0.2 0
96 affcb008-ab99-4bc5-8f35-83dbe620499d BE9558 2026-05-16T04:02:50 K558LL9S.KQ0W Long 0.2896 0.2930 0.989 0.2 0
97 e1f1c6d2-545c-451f-9018-714d52e20a05 BE9558 2026-05-16T04:05:47 K558LL9S.PN0W Long 0.3024 0.3076 0.983 0.2 0
98 93ef80f1-7e83-4703-a0f9-89bbfeeae6c3 BE9558 2026-05-16T04:08:41 K558LL9S.UH0W Long 0.2976 0.2979 0.999 0.2 0
99 5c118ca9-fc37-4080-876d-b3f57ce0b121 BE9558 2026-05-16T04:11:42 K558LL9S.ZI0W Long 0.2881 0.2930 0.983 0.2 0
100 d98b2eaa-7763-4c78-88fb-c21195cb9978 BE9558 2026-05-16T04:14:38 K558LL9T.4E0W Long 0.2898 0.2930 0.989 0.2 0
101 6a146a01-0d02-4413-b231-ecb4a6fde776 BE9558 2026-05-16T04:17:35 K558LL9T.9B0W Long 0.2880 0.2930 0.983 0.2 0
102 f6587a55-27e3-454f-997e-57e7516a296c BE9558 2026-05-16T04:20:32 K558LL9T.E80W Long 0.3046 0.3076 0.990 0.2 0
103 1fb48250-2214-41e6-92cb-362aff1ba62b BE9558 2026-05-16T04:26:05 K558LL9T.NH0W Long 0.2876 0.2930 0.982 0.2 0
104 2f4f3d06-1189-4e28-a1ac-5454ea586a0c BE9558 2026-05-16T04:59:47 K558LL9V.7N0W Long 0.2961 0.3027 0.978 0.2 0
105 62b7bdab-b744-41e4-8d0e-c9141b9d4821 BE9558 2026-05-16T05:02:46 K558LL9V.CM0W Long 0.2903 0.2930 0.991 0.2 0
106 cadcb6dc-74c0-48b5-974c-87bb7a57816c BE9558 2026-05-16T05:05:43 K558LL9V.HJ0W Long 0.3090 0.3125 0.989 0.2 0
107 a0235177-be5a-4f11-b741-c65744698e5b BE9558 2026-05-16T05:08:35 K558LL9V.MB0W Long 0.3167 0.3223 0.983 0.2 0
108 1968c2f6-f52c-4544-a0ed-f79b91ce0da0 BE9558 2026-05-16T05:11:28 K558LL9V.R40W Long 0.3446 0.3516 0.980 0.2 0
109 caa06b94-8813-4949-b47b-61ffb16e61c4 BE9558 2026-05-16T05:14:22 K558LL9V.VY0W Long 0.3318 0.3320 0.999 0.2 0
110 fdaa8101-f033-47e6-9c65-abd76dea1870 BE9558 2026-05-16T05:17:16 K558LL9W.0S0W Long 0.3407 0.3418 0.997 0.2 0
111 29bd16bd-81b9-4ccd-a981-f1a80858536c BE9558 2026-05-16T05:23:05 K558LL9W.AH0W Long 0.3450 0.3516 0.981 0.2 0
112 1f8bc862-d5fd-4cce-abc0-e2bd8c2f11fa BE9558 2026-05-16T05:26:00 K558LL9W.FC0W Long 0.3417 0.3467 0.986 0.2 0
113 20220068-d498-4fca-9a2a-a7fd2ee52ab1 BE9558 2026-05-16T05:28:53 K558LL9W.K50W Long 0.3516 0.3564 0.986 0.2 0
114 9816a261-3118-417a-8334-ace36687ad8f BE9558 2026-05-16T05:31:47 K558LL9W.OZ0W Long 0.3416 0.3467 0.985 0.2 0
115 5d2c76d7-543d-4557-9caf-996a69ab00bd BE9558 2026-05-16T05:34:42 K558LL9W.TU0W Long 0.3537 0.3564 0.992 0.2 0
116 c7b5ae00-52e7-4920-aa27-49d3b3daff92 BE9558 2026-05-16T05:37:36 K558LL9W.YO0W Long 0.3517 0.3564 0.987 0.2 0
117 07db8fd8-ccef-4a5a-9d97-9f318f73a478 BE9558 2026-05-16T05:40:31 K558LL9X.3J0W Long 0.3574 0.3613 0.989 0.2 0
118 790fcff9-e266-4a12-87f0-a072990d2533 BE9558 2026-05-16T05:43:26 K558LL9X.8E0W Long 0.3650 0.3662 0.997 0.2 0
119 f4245f61-1dde-43dc-a121-98e102f6a193 BE9558 2026-05-16T05:50:28 K558LL9X.K40W Long 0.3856 0.3906 0.987 0.2 0
120 5a3bce7b-358e-4260-876f-3f853163d7cf BE9558 2026-05-16T05:53:22 K558LL9X.OY0W Long 0.3847 0.3857 0.997 0.2 0
121 37c2b4b1-7a1b-43e7-b513-2c16f582109c BE9558 2026-05-16T05:56:15 K558LL9X.TR0W Long 0.3906 0.3955 0.988 0.2 0
122 57fde109-1d8a-45a1-b398-5bd28c3e47f1 BE9558 2026-05-16T05:59:10 K558LL9X.YM0W Long 0.4000 0.4004 0.999 0.2 0
123 1e41ab40-93be-405c-a464-f7a57524d3b3 BE9558 2026-05-16T06:02:02 K558LL9Y.3E0W Long 0.3825 0.3857 0.992 0.2 0
124 e9d61eb5-fae8-4902-8fab-4828ffa8e6da BE9558 2026-05-16T06:04:57 K558LL9Y.890W Long 0.3802 0.3809 0.998 0.2 0
125 c0e964e0-7788-4e41-bc41-6e479c3dc81b BE9558 2026-05-16T06:07:51 K558LL9Y.D30W Long 0.3954 0.4004 0.987 0.2 0
126 0b2df8e5-1689-4fe6-abad-30970ba10aa6 BE9558 2026-05-16T06:16:06 K558LL9Y.QU0W Long 0.4051 0.4053 1.000 0.2 0
127 2bc6ce73-464b-469c-9e8f-3bf6f6cfae1d BE9558 2026-05-16T06:21:51 K558LL9Z.0F0W Long 0.3910 0.3955 0.989 0.2 0
128 b8603ee1-616a-451e-a2cd-61f8f2634cd0 BE9558 2026-05-16T06:24:44 K558LL9Z.580W Long 0.3969 0.4004 0.991 0.2 0
129 1aecf582-66a2-4ebb-80f9-04b3aeba331a BE9558 2026-05-16T06:27:39 K558LL9Z.A30W Long 0.3915 0.3955 0.990 0.2 0
130 885aedfd-7a1a-4120-8176-7c344dd3d8fe BE9558 2026-05-16T06:30:30 K558LL9Z.EU0W Long 0.4025 0.4053 0.993 0.2 0
131 ec15930f-47f5-4752-afc2-427ee156ac95 BE9558 2026-05-16T06:33:25 K558LL9Z.JP0W Long 0.4060 0.4102 0.990 0.2 0
132 5ca23f47-2a38-4a54-99dd-041287aa9510 BE9558 2026-05-16T06:36:17 K558LL9Z.OH0W Long 0.4054 0.4102 0.988 0.2 0
133 03f371cf-81bc-4681-80f0-ef6fa437da85 BE9558 2026-05-16T06:39:09 K558LL9Z.T90W Long 0.4052 0.4102 0.988 0.2 0
134 ed386f54-140d-45e8-ad51-6585a58b4375 BE9558 2026-05-16T06:44:54 K558LLA0.2U0W Long 0.3993 0.4004 0.997 0.2 0
135 579f1c3f-4c1e-42a3-aa89-69aa93514033 BE9558 2026-05-16T06:47:47 K558LLA0.7N0W Long 0.4001 0.4053 0.987 0.2 0
136 57024de6-07ea-41f4-b916-c6adc3f51636 BE9558 2026-05-16T06:50:40 K558LLA0.CG0W Long 0.4103 0.4150 0.989 0.2 0
137 36bf5adf-afb5-4a5e-a106-1afbd1f56c7b BE9558 2026-05-16T06:54:49 K558LLA0.JD0W Long 0.4069 0.4150 0.980 0.2 0
138 3e2f831b-5228-46ff-9acb-75d8c86f8bc1 BE9558 2026-05-16T06:57:43 K558LLA0.O70W Long 0.4108 0.4150 0.990 0.2 0
139 1775fa20-568b-4294-b9ca-561201a66c5b BE9558 2026-05-16T07:00:38 K558LLA0.T20W Long 0.3967 0.4004 0.991 0.2 0
140 fd391469-03f9-4d8d-bccd-3af50c91e5b7 BE9558 2026-05-16T07:03:33 K558LLA0.XX0W Long 0.3927 0.3955 0.993 0.2 0
141 02b52ef6-b707-4dcb-b58f-43da02698832 BE9558 2026-05-16T07:06:27 K558LLA1.2R0W Long 0.3824 0.3857 0.991 0.2 0
142 8d45333f-e101-4249-9e27-913c583a0a8d BE9558 2026-05-16T07:09:21 K558LLA1.7L0W Long 0.4085 0.4150 0.984 0.2 0
143 361d11ce-f42a-4d04-8270-ee3771fe4f09 BE9558 2026-05-16T07:12:14 K558LLA1.CE0W Long 0.4017 0.4053 0.991 0.2 0
144 59218125-ed5d-4457-aa8b-35ba03441363 BE9558 2026-05-16T07:15:07 K558LLA1.H70W Long 0.3934 0.3955 0.995 0.2 0
145 a603e55a-2ad6-4fc9-8c8c-0dc7be95c3e7 BE9558 2026-05-16T07:23:43 K558LLA1.VJ0W Long 0.3806 0.3857 0.987 0.2 0
146 c8d07902-93ea-4b03-9e69-9ad6ed5bffb1 BE9558 2026-05-16T07:26:36 K558LLA2.0C0W Long 0.3807 0.3857 0.987 0.2 0
147 4c46c0c7-42f0-4648-827e-1995f733b18f BE9558 2026-05-16T07:30:44 K558LLA2.780W Long 0.3667 0.3711 0.988 0.2 0
148 04759a00-ba3e-4959-a4cb-be8fc1f3004e BE9558 2026-05-16T07:36:28 K558LLA2.GS0W Long 0.3514 0.3516 1.000 0.2 0
149 0b6b0856-bd87-4a07-a5b4-f13d99e04a12 BE9558 2026-05-16T07:39:20 K558LLA2.LK0W Long 0.3512 0.3516 0.999 0.2 0
150 3d81a8bd-464d-4050-8a76-25e8373d1ddb BE9558 2026-05-16T07:42:12 K558LLA2.QC0W Long 0.3350 0.3369 0.994 0.2 0
151 b8b9c0c4-c388-4acb-955a-be4ac356afce BE9558 2026-05-16T07:45:04 K558LLA2.V40W Long 0.3563 0.3564 1.000 0.2 0
152 cb3d142a-fb84-4a21-a298-f61bb869b036 BE9558 2026-05-16T07:49:13 K558LLA3.210W Long 0.3663 0.3711 0.987 0.2 0
153 7401b19b-bc9d-43f0-b395-f4323aca5c72 BE9558 2026-05-16T07:52:06 K558LLA3.6U0W Long 0.3612 0.3662 0.986 0.2 0
154 2236df76-a9e6-401f-9176-ad565242f2cf BE9558 2026-05-16T07:57:52 K558LLA3.GG0W Long 0.3366 0.3369 0.999 0.2 0
155 a645846c-cae4-4aa5-a2e6-85166bd4dd62 BE9558 2026-05-16T08:00:44 K558LLA3.L80W Long 0.3265 0.3271 0.998 0.2 0
156 7212bd33-99a9-4659-9f0b-c98cc8d1e8bc BE9558 2026-05-16T08:04:51 K558LLA3.S30W Long 0.3418 0.3467 0.986 0.2 0
157 2cc4bf33-c63a-4c65-b0e2-5e61a9146a5d BE9558 2026-05-16T08:07:43 K558LLA3.WV0W Long 0.3405 0.3418 0.996 0.2 0
158 4fedb486-5f1f-4623-a01f-083e829f0565 BE9558 2026-05-16T08:10:35 K558LLA4.1N0W Long 0.3515 0.3564 0.986 0.2 0
159 58aff0ba-0f9b-45e1-9bbe-a990d16192ae BE9558 2026-05-16T08:13:27 K558LLA4.6F0W Long 0.3513 0.3516 0.999 0.2 0
160 e56d87e5-e1d4-4947-b6a5-3bbd2773c54a BE9558 2026-05-16T08:20:03 K558LLA4.HF0W Long 0.3564 0.3613 0.986 0.2 0
161 0e96e61e-6a21-4e07-8e09-72d09dbfa1e6 BE9558 2026-05-16T08:25:21 K558LLA4.Q90W Long 0.3565 0.3613 0.987 0.2 0
162 19611f28-2da8-4362-a58e-dbed2e061379 BE9558 2026-05-16T08:34:19 K558LLA5.570W Long 0.3647 0.3662 0.996 0.2 0
163 bd580c1d-44d4-41fd-9f83-f462cda4099a BE9558 2026-05-16T08:37:15 K558LLA5.A30W Long 0.3536 0.3564 0.992 0.2 0
164 2782df3b-3cb4-471a-a6f5-bbc4903a8ab9 BE9558 2026-05-16T08:44:00 K558LLA5.LC0W Long 0.3612 0.3662 0.986 0.2 0
165 d15a08f3-1c7c-4f80-8d9b-f5008c58c3d9 BE9558 2026-05-16T08:49:18 K558LLA5.U60W Long 0.3610 0.3613 0.999 0.2 0
166 03a10a6a-193a-476c-9543-f63818f69417 BE9558 2026-05-16T08:54:36 K558LLA6.300W Long 0.3515 0.3516 1.000 0.2 0
167 1c271856-8100-4c0d-bc8c-9357b47d7626 BE9558 2026-05-16T08:59:54 K558LLA6.BU0W Long 0.3617 0.3662 0.988 0.2 0
168 a85f125e-bfa2-42be-b877-2604b8d068c8 BE9558 2026-05-16T09:05:17 K558LLA6.KT0W Long 0.3510 0.3516 0.998 0.2 0
169 dde9aa71-d2e3-41ac-8388-f2bbddb6dae6 BE9558 2026-05-16T09:08:11 K558LLA6.PN0W Long 0.3447 0.3467 0.994 0.2 0
170 2f3f2be2-0ee3-422e-b3ad-83fb87512a2b BE9558 2026-05-16T09:14:39 K558LLA7.0F0W Long 0.3580 0.3613 0.991 0.2 0
171 357a3034-8a9c-485e-8cb6-f526dd2baf6f BE9558 2026-05-16T09:29:11 K558LLA7.ON0W Long 0.3708 0.3760 0.986 0.2 0
172 f8ad0274-8e6f-4714-82ff-d229e60f1442 BE9558 2026-05-16T09:32:06 K558LLA7.TI0W Long 0.3567 0.3613 0.987 0.2 0
173 42bb007a-2726-401a-b085-c25151b0dc24 BE9558 2026-05-16T09:35:02 K558LLA7.YE0W Long 0.3575 0.3613 0.989 0.2 0
174 c99bfc4a-db02-4bea-bea4-943c67485dba BE9558 2026-05-16T09:37:58 K558LLA8.3A0W Long 0.3527 0.3564 0.989 0.2 0
175 8fc17de0-73f7-48bd-8d93-5451dce47e8e BE9558 2026-05-16T09:40:52 K558LLA8.840W Long 0.3613 0.3662 0.987 0.2 0
176 bbee5276-03dd-4ca4-a7b9-aec02baac7e8 BE9558 2026-05-16T09:48:13 K558LLA8.KD0W Long 0.3590 0.3613 0.993 0.2 0
177 8dcdee10-db01-4224-9506-4181c3105d6f BE9558 2026-05-16T09:53:31 K558LLA8.T70W Long 0.3588 0.3613 0.993 0.2 0
178 48c8be72-64d9-4da3-95b5-bbec2c5e1dbd BE9558 2026-05-16T09:58:49 K558LLA9.210W Long 0.3582 0.3662 0.978 0.2 0
179 0da20919-7ce9-4feb-8ae9-12d9bb40c2b5 BE9558 2026-05-16T10:04:07 K558LLA9.AV0W Long 0.3506 0.3516 0.997 0.2 0
180 c2f7e9bc-8b93-42c3-96d3-e3af217dde35 BE9558 2026-05-16T10:09:25 K558LLA9.JP0W Long 0.3506 0.3516 0.997 0.2 0
181 522a0e42-d443-4447-bc71-af1832c6604e BE9558 2026-05-16T10:14:43 K558LLA9.SJ0W Long 0.3624 0.3662 0.990 0.2 0
182 67f7e732-3c0b-439f-87c5-3c478a381418 BE9558 2026-05-16T10:20:01 K558LLAA.1D0W Long 0.3494 0.3516 0.994 0.2 0
183 251767e8-56f7-4091-a001-364d8e75c15c BE9558 2026-05-16T10:25:19 K558LLAA.A70W Long 0.3463 0.3516 0.985 0.2 0
184 9457239d-a4ca-4476-b385-5e01fc8f6420 BE9558 2026-05-16T10:30:37 K558LLAA.J10W Long 0.3436 0.3467 0.991 0.2 0
185 43718d7c-9353-49e1-89b6-0841aeb1b276 BE9558 2026-05-16T10:35:55 K558LLAA.RV0W Long 0.3452 0.3516 0.982 0.2 0
186 f54ba557-ddfe-41d3-8f4c-8bbec9a3783c BE9558 2026-05-16T10:41:13 K558LLAB.0P0W Long 0.3419 0.3467 0.986 0.2 0
187 dc26c758-ad99-49c1-b518-931368cdf8cf BE9558 2026-05-16T10:46:31 K558LLAB.9J0W Long 0.3463 0.3516 0.985 0.2 0
188 10917eb2-d151-461c-a8cb-e9660da5a5b0 BE9558 2026-05-16T10:51:49 K558LLAB.ID0W Long 0.3520 0.3564 0.987 0.2 0
189 4938a5e6-d53b-40ee-be2b-06ec0e60398c BE9558 2026-05-16T10:57:07 K558LLAB.R70W Long 0.3541 0.3564 0.993 0.2 0
190 0711b51d-55bd-48be-b51e-2aad67107a60 BE9558 2026-05-16T11:13:01 K558LLAC.HP0W Long 0.3661 0.3711 0.986 0.2 0
191 065564b6-aa49-40e7-9ea6-c75defdc60fe BE9558 2026-05-16T11:18:19 K558LLAC.QJ0W Long 0.3622 0.3662 0.989 0.2 0
192 ffb6b230-1d70-4e0e-ba30-e945339a122a BE9558 2026-05-16T11:23:37 K558LLAC.ZD0W Long 0.3711 0.3760 0.987 0.2 0
193 52b4da82-c1e0-4a8a-8365-51b090787005 BE9558 2026-05-16T11:28:55 K558LLAD.870W Long 0.3644 0.3662 0.995 0.2 0
194 cdbff3d8-fbfe-4bea-8bd6-c898800e81ba BE9558 2026-05-16T11:39:31 K558LLAD.PV0W Long 0.3609 0.3662 0.986 0.2 0
195 3fb0bc30-1463-4cfc-9e7f-386c0eb2a34a BE9558 2026-05-16T11:44:49 K558LLAD.YP0W Long 0.3553 0.3564 0.997 0.2 0
196 ba1f5ec8-aef7-4a9e-ac1f-276cf016e285 BE9558 2026-05-16T11:50:07 K558LLAE.7J0W Long 0.3479 0.3516 0.990 0.2 0
197 b1dd4df7-34a9-4512-a903-f8242b236fd2 BE9558 2026-05-16T11:55:25 K558LLAE.GD0W Long 0.3427 0.3467 0.988 0.2 0
198 1f23aa28-c026-4bc7-b3d1-7c78fd76a673 BE9558 2026-05-16T12:00:43 K558LLAE.P70W Long 0.3454 0.3467 0.996 0.2 0
199 0d91f54d-b20d-4a50-b7dd-d071c39a0690 BE9558 2026-05-16T12:06:01 K558LLAE.Y10W Long 0.3431 0.3467 0.990 0.2 0
200 12ccdecd-5fd9-4465-9813-3d6006ec32f3 BE9558 2026-05-16T12:11:19 K558LLAF.6V0W Long 0.3433 0.3467 0.990 0.2 0
201 a7024f1a-f071-48ab-820f-99bdf87366b5 BE9558 2026-05-16T12:16:37 K558LLAF.FP0W Long 0.3361 0.3369 0.998 0.2 0
202 de0fa439-30b8-4607-a3c3-7e17191e4624 BE9558 2026-05-16T12:21:55 K558LLAF.OJ0W Long 0.3274 0.3320 0.986 0.2 0
203 f9374ec3-05e5-477f-8e1a-0c862fed2a50 BE9558 2026-05-16T12:27:13 K558LLAF.XD0W Long 0.3449 0.3467 0.995 0.2 0
204 424cb275-3743-4174-95f0-0ca1205b374c BE9558 2026-05-16T12:32:31 K558LLAG.670W Long 0.3370 0.3418 0.986 0.2 0
205 9accde13-cefa-41b8-bd0a-cef2ffed59b0 BE9558 2026-05-16T12:37:49 K558LLAG.F10W Long 0.3465 0.3467 0.999 0.2 0
206 4665be38-1956-4b14-b931-068ba9af5c5e BE9558 2026-05-16T12:48:25 K558LLAG.WP0W Long 0.3453 0.3516 0.982 0.2 0
207 1aedf624-1a99-43e1-a8f2-f9d358b97f61 BE9558 2026-05-16T12:53:43 K558LLAH.5J0W Long 0.3366 0.3418 0.985 0.2 0
208 c15e1799-91d7-425e-ad17-2ba3d170d81e BE9558 2026-05-16T13:04:19 K558LLAH.N70W Long 0.3348 0.3369 0.994 0.2 0
209 72d4c4ea-19ca-4cc6-9b04-7a2b70122c67 BE9558 2026-05-16T13:09:37 K558LLAH.W10W Long 0.3272 0.3320 0.986 0.2 0
210 b4ebf2c9-1f6d-4594-9810-40479e87c0a5 BE9558 2026-05-16T13:14:55 K558LLAI.4V0W Long 0.3297 0.3320 0.993 0.2 0
211 bb297e9e-548f-4dae-8b1a-0f161af2e766 BE9558 2026-05-16T13:20:13 K558LLAI.DP0W Long 0.3272 0.3320 0.986 0.2 0
212 87562c24-63db-48bd-9962-72a20a40f2ff BE9558 2026-05-16T13:36:07 K558LLAJ.470W Long 0.3174 0.3223 0.985 0.2 0
213 01e9cc58-3bea-4f38-8499-a2c20e5f8550 BE9558 2026-05-16T13:46:52 K558LLAJ.M40W Long 0.2880 0.2930 0.983 0.2 0
214 5ae7503d-ae17-4063-9208-6a420699e1ab BE9558 2026-05-16T14:00:35 K558LLAK.8Z0W Long 0.2879 0.2930 0.983 0.2 0
215 e009ea3c-1534-4154-8623-e180ed4db9fb BE9558 2026-05-16T14:06:19 K558LLAK.IJ0W Long 0.2882 0.2930 0.984 0.2 0
216 cd4e21f5-512b-4b2b-8054-bec01aa06400 BE9558 2026-05-16T14:12:03 K558LLAK.S30W Long 0.2857 0.2930 0.975 0.2 0
217 ae5b780f-2038-4ccf-8bfc-b15b87be139e BE9558 2026-05-16T14:17:22 K558LLAL.0Y0W Long 0.2899 0.2930 0.989 0.2 0
218 d8c3fb81-8c66-4ebc-b33a-0559bc03334b BE9558 2026-05-16T14:22:40 K558LLAL.9S0W Long 0.3009 0.3027 0.994 0.2 0
219 990a4c7a-3c51-4d4a-8ab7-416ccb97d29c BE9558 2026-05-16T14:27:58 K558LLAL.IM0W Long 0.3057 0.3076 0.994 0.2 0
220 68d7a2c3-d899-4e75-96fb-3bf16ae6ea6f BE9558 2026-05-16T14:33:16 K558LLAL.RG0W Long 0.3110 0.3125 0.995 0.2 0
221 73505b8c-f912-4116-b903-a8a4c75524d3 BE9558 2026-05-16T14:38:34 K558LLAM.0A0W Long 0.3172 0.3223 0.984 0.2 0
222 8d3c9602-7efa-488a-801b-3228bd85ab14 BE9558 2026-05-16T14:43:51 K558LLAM.930W Long 0.3136 0.3174 0.988 0.2 0
223 243e16ee-860a-4960-bc15-b797ad7e9735 BE9558 2026-05-16T14:49:08 K558LLAM.HW0W Long 0.3135 0.3174 0.988 0.2 0
224 e90c8d90-6d41-4788-9ee6-a29e4bfcc16b BE9558 2026-05-16T15:19:35 K558LLAN.WN0W Long 0.3132 0.3174 0.987 0.2 0
225 4182b0e7-7811-46b8-87d1-a4dd0c152f3b BE9558 2026-05-16T15:28:45 K558LLAO.BX0W Long 0.3023 0.3076 0.983 0.2 0
226 28a790da-0e48-4fe4-b8ba-2c82cc6bfa79 BE9558 2026-05-16T15:34:02 K558LLAO.KQ0W Long 0.3176 0.3223 0.985 0.2 0
227 093d2fa3-7a4b-4f0f-abda-71155ebe2dfb BE9558 2026-05-16T15:39:19 K558LLAO.TJ0W Long 0.3223 0.3271 0.985 0.2 0
228 68dc9560-4082-49b6-af04-9244773ffbc1 BE9558 2026-05-16T15:44:36 K558LLAP.2C0W Long 0.3227 0.3271 0.986 0.2 0
229 ad6b268a-165d-4b1d-b0b3-f58db7c9b0e4 BE9558 2026-05-16T15:49:53 K558LLAP.B50W Long 0.3177 0.3223 0.986 0.2 0
230 046c5cb4-56b3-48c0-83c2-bf1f30837940 BE9558 2026-05-16T15:55:10 K558LLAP.JY0W Long 0.3174 0.3223 0.985 0.2 0
231 1b76edf4-3b1c-4bcb-a73c-27334981c350 BE9558 2026-05-16T16:00:27 K558LLAP.SR0W Long 0.3127 0.3174 0.985 0.2 0
232 a0264171-a682-4396-ad8a-cda3b2964533 BE9558 2026-05-16T16:06:55 K558LLAQ.3J0W Long 0.2885 0.2930 0.985 0.2 0
233 707da1f6-ee81-4e57-abd5-98295c14651b BE9558 2026-05-16T16:12:30 K558LLAQ.CU0W Long 0.2880 0.2930 0.983 0.2 0
234 b8115b64-8739-42c8-b541-713ab6b68bcd BE9558 2026-05-16T16:17:53 K558LLAQ.LT0W Long 0.2881 0.2930 0.983 0.2 0
235 fb179c36-fef1-4df6-b0a0-2bd7792ea910 BE9558 2026-05-16T16:23:11 K558LLAQ.UN0W Long 0.2933 0.2979 0.985 0.2 0
236 0cec8793-c3c1-486b-a33a-4dbf9cb069b0 BE9558 2026-05-16T16:33:46 K558LLAR.CA0W Long 0.3017 0.3027 0.997 0.2 0
237 c531b052-ee04-4c66-888b-21e97445a615 BE9558 2026-05-16T16:49:37 K558LLAS.2P0W Long 0.2922 0.2979 0.981 0.2 0
238 0dc402f9-cab6-4c4a-8317-b8fc3c4b1ced BE9558 2026-05-16T16:55:08 K558LLAS.BW0W Long 0.2898 0.2930 0.989 0.2 0
239 fd73733e-b42d-4a51-81d0-4acad6edfbd4 BE9558 2026-05-16T17:16:17 K558LLAT.B50W Long 0.3115 0.3125 0.997 0.2 0
240 6a254daa-ae27-4ac1-b334-58f776a6b276 BE9558 2026-05-16T17:26:51 K558LLAT.SR0W Long 0.3174 0.3223 0.985 0.2 0
241 0cc8e82f-5270-4508-beae-0d3af56095ca BE9558 2026-05-16T17:37:27 K558LLAU.AF0W Long 0.2899 0.2930 0.989 0.2 0
242 00557a73-8dc3-4cd2-b880-c7820dc8b171 BE9558 2026-05-16T17:43:17 K558LLAU.K50W Long 0.2881 0.2930 0.983 0.2 0
243 8e5518d9-ff0a-4c09-9cf9-a681c84c0b6e BE9558 2026-05-16T17:53:53 K558LLAV.1T0W Long 0.2898 0.2930 0.989 0.2 0
244 91dbd7e9-7344-400b-82b1-379f2ac4b49a BE9558 2026-05-16T17:59:11 K558LLAV.AN0W Long 0.2925 0.2930 0.998 0.2 0
245 fa256408-d480-4376-95b5-d1a549c483ea BE9558 2026-05-16T18:04:29 K558LLAV.JH0W Long 0.2977 0.3027 0.983 0.2 0
246 4ab6e66a-8364-49b6-82f1-86e86199e676 BE9558 2026-05-16T18:09:46 K558LLAV.SA0W Long 0.2944 0.2979 0.988 0.2 0
247 0a65fb7c-96e1-4ba0-85de-4620d88658c1 BE9558 2026-05-16T18:15:03 K558LLAW.130W Long 0.2965 0.2979 0.995 0.2 0
248 92b1ef3e-1696-4123-8662-163947737c83 BE9558 2026-05-16T18:20:20 K558LLAW.9W0W Long 0.2976 0.3027 0.983 0.2 0
249 9e3cb24c-4426-4220-9a73-389d0a96c94f BE9558 2026-05-16T18:25:37 K558LLAW.IP0W Long 0.2983 0.3027 0.985 0.2 0
250 a3473215-4c46-45ab-9aa7-1720486ec4a8 BE9558 2026-05-16T18:30:54 K558LLAW.RI0W Long 0.2956 0.2979 0.993 0.2 0
251 449665b1-47c8-4bd2-984c-8f45b627e6d8 BE9558 2026-05-16T18:36:11 K558LLAX.0B0W Long 0.2989 0.3027 0.987 0.2 0
252 600cfabc-cffd-42e1-800c-70e75f312316 BE9558 2026-05-16T20:00:12 K558LLB0.WC0W Long 0.3077 0.3125 0.985 0.2 0
253 12bf5944-0194-4f5b-b486-a7acd7141c7f BE9558 2026-05-16T20:04:28 K558LLB1.3G0W Long 0.2888 0.2930 0.986 0.2 0
254 f1fc913a-91bc-4240-a595-7dfe3091f9a2 BE9558 2026-05-16T20:07:29 K558LLB1.8H0W Long 0.2977 0.3027 0.983 0.2 0
255 e74f7ec3-20bb-4177-beb2-e802e5f801fd BE9558 2026-05-16T20:10:26 K558LLB1.DE0W Long 0.2978 0.3027 0.984 0.2 0
256 27491c3a-b631-4643-818a-714523911178 BE9558 2026-05-16T20:16:21 K558LLB1.N90W Long 0.2921 0.2930 0.997 0.2 0
257 9d9196ce-11e2-4f28-b01c-3dcc60e60d42 BE9558 2026-05-16T20:22:28 K558LLB1.XG0W Long 0.2881 0.2930 0.983 0.2 0
258 a592d7c8-b643-4b25-9186-3d611ae22709 BE9558 2026-05-16T20:25:37 K558LLB2.2P0W Long 0.2893 0.2930 0.987 0.2 0
259 f709a3d5-27cd-4bb1-b91c-669e8ea11d77 BE9558 2026-05-16T20:28:57 K558LLB2.890W Long 0.2880 0.2930 0.983 0.2 0
260 cc9cad87-b87f-4b67-854a-ffb21e876a92 BE9558 2026-05-16T20:32:45 K558LLB2.EL0W Long 0.2873 0.2930 0.980 0.2 0
261 10732d26-6b49-4b14-a474-6c75e259d278 BE9558 2026-05-16T20:49:32 K558LLB3.6K0W Long 0.2881 0.2930 0.983 0.2 0
262 aa63957a-fdb2-4f17-af52-a63bb015119d BE9558 2026-05-16T21:21:45 K558LLB4.O90W Long 0.2880 0.2930 0.983 0.2 0
263 8350440f-019d-45a4-b9f9-23058628e6f0 BE9558 2026-05-16T21:32:43 K558LLB5.6J0W Long 0.2925 0.2930 0.999 0.2 0
264 edfc10b2-dbe1-4527-a061-b0d670b5e5d2 BE9558 2026-05-16T21:35:37 K558LLB5.BD0W Long 0.2891 0.2930 0.987 0.2 0
265 f98001a3-88b2-4830-8112-b7c5164e99c3 BE9558 2026-05-16T21:38:40 K558LLB5.GG0W Long 0.2877 0.2930 0.982 0.2 0
266 f1e53e7b-b124-4fc5-82c2-504fb0c8b80d BE9558 2026-05-16T21:41:46 K558LLB5.LM0W Long 0.2881 0.2930 0.983 0.2 0
267 7890637f-142e-4775-b48c-fd4f3b8ada77 BE9558 2026-05-16T21:45:14 K558LLB5.RE0W Long 0.2880 0.2930 0.983 0.2 0
268 7c97c10f-b413-467c-9b56-c18e423cdcfa BE9558 2026-05-16T21:48:26 K558LLB5.WQ0W Long 0.2886 0.2930 0.985 0.2 0
269 8178cf22-8428-4f85-8199-0a43f7334a8f BE9558 2026-05-16T21:51:47 K558LLB6.2B0W Long 0.2881 0.2930 0.983 0.2 0
270 eceb2997-deb4-403a-802f-50e93d23d423 BE9558 2026-05-16T21:57:18 K558LLB6.BI0W Long 0.2881 0.2930 0.984 0.2 0
271 9c26690c-1983-4b21-b8af-7c7967c014c3 BE9558 2026-05-16T22:12:21 K558LLB7.0L0W Long 0.2876 0.2930 0.982 0.2 0
272 78f67fc3-08b7-4317-96ba-ee5544e0b95b BE9558 2026-05-16T22:19:34 K558LLB7.CM0W Long 0.2880 0.2930 0.983 0.2 0
273 7f9dad14-4f1b-492d-aa26-845a908ea894 BE9558 2026-05-16T22:27:40 K558LLB7.Q40W Long 0.2881 0.2930 0.983 0.2 0
274 f75c52b4-21b9-4065-baeb-5cfbd27d130a BE9558 2026-05-16T22:33:50 K558LLB8.0E0W Long 0.2881 0.2930 0.984 0.2 0
275 10f7496d-fa76-40a7-8bef-dc14e8a41869 BE9558 2026-05-16T22:40:48 K558LLB8.C00W Long 0.2878 0.2930 0.982 0.2 0
-98
View File
@@ -1,98 +0,0 @@
#!/usr/bin/env python3
"""Backfill events.*_zc_freq / *_zc_above_range from .sfm.json sidecars.
Idempotent. Reads each event's sidecar bw_report and writes the per-channel
ZC frequency into the DB columns via a direct UPDATE. Events with no sidecar
(or no bw_report freq) are left untouched. Mirrors scripts/backfill_record_type.py.
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
log = logging.getLogger("backfill_event_zc_freq")
def _freqs_from_sidecar(sidecar: dict) -> dict | None:
bw = (sidecar or {}).get("bw_report") or {}
peaks = bw.get("peaks") or {}
mic = bw.get("mic") or {}
out = {}
for axis in ("tran", "vert", "long"):
chd = peaks.get(axis) or {}
out[f"{axis}_zc_freq"] = chd.get("zc_freq_hz")
out[f"{axis}_zc_above_range"] = 1 if chd.get("zc_freq_above_range") else 0
out["mic_zc_freq"] = mic.get("zc_freq_hz")
out["mic_zc_above_range"] = 1 if mic.get("zc_freq_above_range") else 0
# None if there's literally no frequency anywhere.
if all(out[f"{a}_zc_freq"] is None for a in ("tran", "vert", "long", "mic")):
return None
return out
def backfill_zc_freq(db: SeismoDb, store, *, dry_run: bool = False) -> dict:
counts = {"updated": 0, "skipped_no_sidecar": 0, "skipped_no_freq": 0}
# Pull every event (paginate generously; adjust if a store has >100k events).
rows = db.query_events(limit=1_000_000)
for row in rows:
serial = row.get("serial")
filename = row.get("blastware_filename")
if not serial or not filename:
counts["skipped_no_sidecar"] += 1
continue
sidecar = store.load_sidecar(serial, filename)
if sidecar is None:
counts["skipped_no_sidecar"] += 1
continue
freqs = _freqs_from_sidecar(sidecar)
if freqs is None:
counts["skipped_no_freq"] += 1
continue
if dry_run:
counts["updated"] += 1
continue
with db._connect() as conn:
conn.execute(
"""UPDATE events SET
tran_zc_freq=?, vert_zc_freq=?, long_zc_freq=?, mic_zc_freq=?,
tran_zc_above_range=?, vert_zc_above_range=?,
long_zc_above_range=?, mic_zc_above_range=?
WHERE id=?""",
(freqs["tran_zc_freq"], freqs["vert_zc_freq"], freqs["long_zc_freq"],
freqs["mic_zc_freq"], freqs["tran_zc_above_range"],
freqs["vert_zc_above_range"], freqs["long_zc_above_range"],
freqs["mic_zc_above_range"], row["id"]),
)
counts["updated"] += 1
return counts
def main(argv=None) -> int:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--db-path", default=str(
Path(__file__).resolve().parent.parent / "bridges" / "captures" / "seismo_relay.db"))
p.add_argument("--store-root", default=None)
p.add_argument("--dry-run", action="store_true")
p.add_argument("-v", "--verbose", action="store_true")
args = p.parse_args(argv)
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
db_path = Path(args.db_path).expanduser().resolve()
store_root = (
Path(args.store_root).expanduser().resolve()
if args.store_root else db_path.parent / "waveforms"
)
db = SeismoDb(db_path)
store = WaveformStore(store_root)
counts = backfill_zc_freq(db, store, dry_run=args.dry_run)
log.info("backfill_zc_freq: %s", counts)
return 0
if __name__ == "__main__":
raise SystemExit(main())
-150
View File
@@ -1,150 +0,0 @@
"""
scripts/backfill_record_type.py — fix `record_type` on legacy event
rows whose value was hardcoded to "Waveform" regardless of actual type.
Why this is needed
──────────────────
Pre-v0.16.1 the BW file importer (`event_file_io.read_blastware_file`)
hardcoded `ev.record_type = "Waveform"` for every imported event. Fixed
in commit aac1c8e — new ingests now derive the type from the Blastware
filename's extension last character (H=Histogram, W=Waveform, M=Manual,
E=Event, C=Combo) per the V10.72+ MiniMate Plus AB0T filename scheme.
Effect on a server that imported events under the old code: every
events row has `record_type = "Waveform"`, even for histograms,
manuals, etc. Visible in terra-view's event-detail modal under the
"Record Type" field. Terra-view also has a client-side workaround
that derives the type from the filename for display purposes, so
operators see the correct type in the UI even before this backfill.
This script makes the DB column match what the UI is already showing,
which matters for reporting and any downstream consumer that reads
events.record_type directly.
This script
───────────
Walks the `events` table and updates each row's `record_type` to the
derived value from its `blastware_filename`. Old S338 firmware files
(3-char extensions ending in `0`) and any unrecognized suffix get
left at the existing value (defaults to "Waveform").
Idempotent: re-running after a successful backfill finds zero rows
needing updates and exits cleanly (it always re-derives but only
writes when the value would change).
Usage
─────
# Dry-run (default): print what would change, don't touch the DB
python -m scripts.backfill_record_type --db bridges/captures/seismo_relay.db
# Apply the backfill
python -m scripts.backfill_record_type --db bridges/captures/seismo_relay.db --apply
"""
from __future__ import annotations
import argparse
import sqlite3
import sys
from collections import Counter
from pathlib import Path
# Must stay in sync with minimateplus.event_file_io._RECORD_TYPE_BY_EXT_SUFFIX.
_TYPE_FROM_SUFFIX = {
"H": "Histogram",
"W": "Waveform",
"M": "Manual",
"E": "Event",
"C": "Combo",
}
def derive_record_type(filename: str | None, default: str = "Waveform") -> str:
"""Mirror of minimateplus.event_file_io.derive_record_type_from_filename.
Vendored here so this script runs without needing the seismo-relay
package on the Python path (useful on prod where you might be
running it via `docker exec` against a container's DB volume).
"""
if not filename:
return default
name = Path(filename).name
if "." not in name:
return default
ext = name.rsplit(".", 1)[1]
if not ext:
return default
return _TYPE_FROM_SUFFIX.get(ext[-1].upper(), default)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--db", required=True, help="Path to seismo_relay.db")
ap.add_argument("--apply", action="store_true",
help="Actually write changes (default is dry-run).")
ap.add_argument("--default", default="Waveform",
help="Fallback record_type when filename doesn't encode one. "
"Default: Waveform (matches the pre-fix bug's behavior).")
args = ap.parse_args()
db_path = Path(args.db)
if not db_path.exists():
print(f"ERROR: database not found at {db_path}", file=sys.stderr)
return 1
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("""
SELECT id, blastware_filename, record_type
FROM events
WHERE blastware_filename IS NOT NULL
AND blastware_filename != ''
""")
rows = cur.fetchall()
total = len(rows)
print(f"Scanning {total:,} event rows…")
print()
# Tally proposed changes.
transitions: Counter[tuple[str, str]] = Counter()
update_ids: list[tuple[str, str]] = []
unrecognized = 0
for row in rows:
derived = derive_record_type(row["blastware_filename"], default=args.default)
current = row["record_type"] or ""
if derived == current:
continue
transitions[(current, derived)] += 1
update_ids.append((row["id"], derived))
if not update_ids:
print("Nothing to update — all rows already match.")
conn.close()
return 0
print(f"{len(update_ids):,} row(s) need updating:")
for (old, new), count in sorted(transitions.items(), key=lambda x: -x[1]):
print(f" {count:>6,} {old!r:14s} → {new!r}")
print()
if not args.apply:
print("(dry-run — re-run with --apply to write changes)")
conn.close()
return 0
print("Applying changes…")
cur.executemany(
"UPDATE events SET record_type = ? WHERE id = ?",
[(new, eid) for eid, new in update_ids],
)
conn.commit()
print(f"Done. Updated {cur.rowcount:,} row(s).")
conn.close()
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -2
View File
@@ -428,8 +428,7 @@ def main(argv=None) -> int:
try:
event_hdf5.write_event_hdf5(
hdf5_path, ev,
serial=serial,
geo_range="normal",
serial=serial, # range: the event's own, from its setup
source_kind=source_kind,
)
hdf5_filename = hdf5_path.name
+4 -1
View File
@@ -287,7 +287,7 @@ def main(argv=None) -> int:
if is_histogram and idf_intervals:
# 1 sample per interval per channel — same
# synthesis save_imported_idf uses. The h5
# writer's count×geo_fs/32768 conversion turns
# writer's count×_GEO_LSB_IPS conversion turns
# each peak-ADC-count into the bar's physical
# value.
ev.raw_samples = {
@@ -311,12 +311,15 @@ def main(argv=None) -> int:
from micromate.sensor_check import decode_idf_sensor_check
ev.sensor_check = decode_idf_sensor_check(binary_bytes) or None
# Thor counts, not MiniMate counts (issue #42).
from micromate.idf_file import _GEO_LSB_IPS
event_hdf5.write_event_hdf5(
hdf5_path, ev,
serial=serial,
geo_range="normal",
source_kind="idf-import",
tool_version=event_file_io.TOOL_VERSION,
geo_ips_per_count=_GEO_LSB_IPS,
)
h5_written += 1
log.debug("%s/%s — .h5 written (%s)",
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Import every Blastware .MLG under a directory into SFM's DB and waveform store.
import_mlg_dir.py <dir> --db-path P --store-root S [--dry-run] [--not-call-in]
For a copy of an ACH folder (DL2 holds ~86,000). Idempotent: a file already
stored (same name, same bytes) counts as a duplicate. Files with records go
first, then the empty ones, so every unit's serial is known before its empty
files arrive whatever the folder order. Each file's modified time is stored
as its call-in time: copy with robocopy, not a Windows zip, whose dates read
an hour early from March to October.
Operational consequence: writes rows to mlg_files / mlg_records and copies each
original into <store>/<serial>/mlg/. The dry run writes nothing.
"""
from __future__ import annotations
import argparse
import datetime
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.mlg_file import MLG_PREFIX, MlgFormatError, parse_mlg
from sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg
from sfm.waveform_store import WaveformStore
log = logging.getLogger("import_mlg_dir")
_COUNTS = ("files", "ok", "duplicate", "error", "empty", "unresolved", "inserted", "skipped")
def _mlg_files(root: Path) -> list[Path]:
"""Files with records first, then empty ones; each group oldest first."""
found = [p for p in root.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"]
key = lambda p: (p.stat().st_size <= len(MLG_PREFIX), p.stat().st_mtime, p.name)
return sorted(found, key=key)
def import_dir(root: Path, db_path: str, store_root: str, *, dry_run: bool = False,
call_in: bool = True) -> dict:
counts = dict.fromkeys(_COUNTS, 0)
db = store = None
if not dry_run:
db, store = SeismoDb(db_path), WaveformStore(store_root)
for path in _mlg_files(root):
counts["files"] += 1
data = path.read_bytes()
if dry_run:
try:
mlg = parse_mlg(data)
except MlgFormatError as exc:
counts["error"] += 1
log.warning("%s: %s", path, exc)
continue
counts["error" if mlg.crc_failures else "ok"] += 1
counts["empty"] += mlg.empty
continue
mtime = datetime.datetime.fromtimestamp(path.stat().st_mtime, datetime.timezone.utc)
res = ingest_mlg(db, store, path.name, data, file_mtime=mtime, call_in=call_in)
counts[res["status"]] += 1
if res["status"] == "error":
log.warning("%s: %s", path, res["detail"])
continue
counts["empty"] += res["empty"]
counts["unresolved"] += res["serial_unresolved"]
counts["inserted"] += res["inserted"]
counts["skipped"] += res["skipped"]
return counts
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("dir")
ap.add_argument("--db-path", required=True)
ap.add_argument("--store-root", required=True)
ap.add_argument("--dry-run", action="store_true", help="parse and check only; write nothing")
ap.add_argument("--not-call-in", action="store_true",
help="these are cable / direct downloads, not call-ins")
a = ap.parse_args(argv)
logging.basicConfig(level=logging.WARNING)
counts = import_dir(Path(a.dir), a.db_path, a.store_root, dry_run=a.dry_run,
call_in=not a.not_call_in)
for key in _COUNTS:
print(f"{key} {counts[key]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+5 -4
View File
@@ -73,7 +73,7 @@ def main(argv: list[str] | None = None) -> int:
conn.row_factory = sqlite3.Row
rows = list(conn.execute(
"SELECT id, serial, timestamp, blastware_filename "
"SELECT id, serial, timestamp, record_type, blastware_filename "
" FROM events "
" WHERE serial = 'UNKNOWN' "
" ORDER BY timestamp",
@@ -98,10 +98,11 @@ def main(argv: list[str] | None = None) -> int:
unresolved += 1
continue
# Check for an existing row at the target (serial, timestamp).
# Check for an existing row at the target key (serial, timestamp,
# record_type -- #51).
existing = conn.execute(
"SELECT id FROM events WHERE serial = ? AND timestamp = ?",
(new_serial, ts),
"SELECT id FROM events WHERE serial = ? AND timestamp = ? AND record_type IS ?",
(new_serial, ts, row["record_type"]),
).fetchone()
action: str
if existing is None:
-91
View File
@@ -1,91 +0,0 @@
"""Re-ingest a prod IDFW + IDFH via the patched save_imported_idf and
render both PDFs to confirm charts have data."""
from __future__ import annotations
import sys
import json
import datetime
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from sfm.waveform_store import WaveformStore
from sfm import report_pdf
import h5py
class FakeDb:
def __init__(self, event):
self.event = event
def get_event(self, _id):
return self.event
def to_ts_iso(ts):
if ts is None:
return None
try:
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second).isoformat()
except Exception:
return None
def render_case(idf_path: Path, serial: str, out_pdf: Path, h5_summary: bool = True):
with tempfile.TemporaryDirectory() as td:
store = WaveformStore(Path(td))
ev, rec = store.save_imported_idf(
idf_path.read_bytes(),
idf_path,
idf_report_text=None, # production worst case: no .txt
)
print(f"=== {idf_path.name} ===")
print(f" h5: {rec['hdf5_filename']}, sidecar: {rec['sidecar_filename']}")
h5p = Path(td) / serial / f"{idf_path.name}.h5"
if h5p.exists() and h5_summary:
with h5py.File(h5p) as h:
for ch in ("Tran", "Vert", "Long", "MicL"):
ds = h.get(f"samples/{ch}")
if ds is not None:
n = ds.shape[0]
mx = float(abs(ds[...]).max()) if n else 0
print(f" samples/{ch}: n={n} max_abs={mx:.5f}")
record_type = "Histogram" if idf_path.suffix.upper() == ".IDFH" else "Waveform"
fake_row = {
"serial": serial,
"blastware_filename": rec["filename"],
"record_type": record_type,
"timestamp": to_ts_iso(ev.timestamp),
"sample_rate": ev.sample_rate,
"project": ev.project_info.project if ev.project_info else None,
"client": ev.project_info.client if ev.project_info else None,
"operator": ev.project_info.operator if ev.project_info else None,
"sensor_location": ev.project_info.sensor_location if ev.project_info else None,
"created_at": None,
}
rd = report_pdf.gather_report_data(FakeDb(fake_row), store, event_id="test-1")
print(f" ReportData: channels={ {k: len(v) for k,v in rd.channels.items()} }")
if rd.is_histogram:
print(f" histogram n_intervals={rd.histogram_n_intervals} interval_size={rd.histogram_interval_size}")
pdf = report_pdf.render_event_report_pdf(rd)
out_pdf.write_bytes(pdf)
print(f" PDF: {out_pdf} ({len(pdf)} bytes)")
def main():
out_dir = Path("/tmp/thor_render_test"); out_dir.mkdir(exist_ok=True)
cases = [
# IDFW that decoded to preamble-only under the old codec
("/home/serversdown/seismo-relay-prod-snap/waveforms/UM6047/UM6047_20250804154137.IDFW", "UM6047"),
# IDFW that worked under the old codec (validates no regression)
("/home/serversdown/seismo-relay-prod-snap/waveforms/UM6047/UM6047_20250804104450.IDFW", "UM6047"),
# IDFH histogram
("/home/serversdown/seismo-relay-prod-snap/waveforms/UM6047/UM6047_20250804190047.IDFH", "UM6047"),
]
for path, serial in cases:
render_case(Path(path), serial, out_dir / f"{Path(path).name}.pdf")
if __name__ == "__main__":
main()
+2882 -2882
View File
File diff suppressed because it is too large. Load diff
+343 -9
View File
@@ -1,11 +1,15 @@
"""
sfm/database.py — SQLite persistence layer for seismo-relay.
Three tables, all keyed by unit serial number:
Tables, all keyed by unit serial number:
ach_sessions — one row per inbound ACH call-home
events — one row per triggered waveform event (deduped by serial+timestamp)
monitor_log — one row per monitoring interval (deduped by serial+start_time)
monitor_log — one row per monitoring interval (deduped by serial+start_time);
live 0x0A reads by bridges/ach_server.py only
mlg_files — one row per Blastware .MLG received (deduped by file name+sha256)
mlg_records — one row per .MLG log record (deduped by serial, start, stop,
flag word, trigger source — never the text, which Blastware writes)
The DB file lives at:
<output_dir>/seismo_relay.db (default: bridges/captures/seismo_relay.db)
@@ -36,12 +40,14 @@ from __future__ import annotations
import datetime
import json
import logging
import re
import sqlite3
import uuid
from pathlib import Path
from typing import Optional
from minimateplus.models import Event, MonitorLogEntry
from minimateplus.blastware_file import blastware_filename_time
from minimateplus.models import Event, MlgRecord, MonitorLogEntry
log = logging.getLogger("sfm.database")
@@ -106,7 +112,7 @@ CREATE TABLE IF NOT EXISTS events (
shape_offset_pre REAL, -- pre-trigger baseline median (in/s)
shape_offset_spread REAL, -- max(pre,mid,end) - min(...) in in/s; small = constant/DC
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
UNIQUE(serial, timestamp)
UNIQUE(serial, timestamp, record_type) -- unit + time + type (#51); see Migration 3
);
CREATE INDEX IF NOT EXISTS idx_events_serial ON events(serial);
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
@@ -148,6 +154,43 @@ CREATE TABLE IF NOT EXISTS device_commands (
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
-- Blastware monitor logs (.MLG): spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
-- Record times are the unit's own local clock (naive ISO); file_mtime is UTC (+00:00).
CREATE TABLE IF NOT EXISTS mlg_files (
id TEXT PRIMARY KEY,
serial TEXT, -- NULL: an empty file whose unit is not known yet
file_name TEXT NOT NULL,
sha256 TEXT NOT NULL,
size INTEGER NOT NULL,
record_count INTEGER NOT NULL, -- log records in the file (header excluded)
empty INTEGER NOT NULL, -- 1: the 18-byte prefix alone
call_in INTEGER NOT NULL DEFAULT 1, -- 0: a cable / direct download
file_mtime TEXT, -- the file's modified time, when the sender gave it
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%S+00:00', 'now')),
stored_path TEXT, -- the original file, relative to the waveform store
last_stop TEXT, -- the stop of the file's last record: the call that sent it
no_file_stops TEXT, -- JSON: earlier Modem Exit stops in it, calls that left no file
UNIQUE(file_name, sha256)
);
CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial);
CREATE TABLE IF NOT EXISTS mlg_records (
id TEXT PRIMARY KEY,
serial TEXT NOT NULL,
start_time TEXT NOT NULL,
stop_time TEXT, -- NULL: "monitoring started", no stop yet
flags INTEGER NOT NULL, -- monitor-log flag word; 65535 = started
trigger_source INTEGER NOT NULL, -- 1-8 a channel, 1024 a histogram, 0 none
text TEXT,
trigger_level TEXT,
event_time TEXT,
file_id TEXT NOT NULL REFERENCES mlg_files(id), -- the file it first came in
seq INTEGER NOT NULL -- its position in that file (1 = first log record)
);
-- NULL stops are distinct to a UNIQUE constraint, so the identity uses COALESCE.
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
"""
@@ -193,7 +236,7 @@ class SeismoDb:
row = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
).fetchone()
if row and "UNIQUE(serial, timestamp)" not in row[0]:
if row and "UNIQUE(serial, timestamp" not in row[0]: # neither key form yet
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp)")
conn.executescript("""
ALTER TABLE events RENAME TO events_old;
@@ -347,6 +390,33 @@ class SeismoDb:
""")
log.info("_migrate: monitor_log table rebuilt OK")
# Migration 3 (#51, 2026-11-03): events UNIQUE (serial, timestamp) ->
# (serial, timestamp, record_type). A unit records a waveform and a
# histogram in the same second legitimately -- 209 times in prod's
# 2026-09-30 store once histograms carry Blastware's start -- and the old
# key could hold only one. The table is rebuilt from its own current
# definition with only the key swapped, so every column added by the
# migrations above, every row and every id is kept (Terra-View reads
# rows by id); its indexes are recreated. One transaction.
row = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
).fetchone()
if row and "UNIQUE(serial, timestamp)" in row[0]:
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp, record_type)")
indexes = [r[0] for r in conn.execute(
"SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='events' "
"AND sql IS NOT NULL")]
table = re.sub(r'^CREATE TABLE\s+("?)events\1', "CREATE TABLE events_rekeyed",
row[0].replace("UNIQUE(serial, timestamp)",
"UNIQUE(serial, timestamp, record_type)", 1))
conn.executescript("BEGIN;\n" + table + ";\n"
"INSERT INTO events_rekeyed SELECT * FROM events;\n"
"DROP TABLE events;\n"
"ALTER TABLE events_rekeyed RENAME TO events;\n"
+ "".join(sql + ";\n" for sql in indexes)
+ "COMMIT;")
log.info("_migrate: events table re-keyed OK (%d indexes recreated)", len(indexes))
@staticmethod
def _iso(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.isoformat() if dt is not None else None
@@ -506,7 +576,8 @@ class SeismoDb:
device_family: Optional[str] = None,
) -> tuple[int, int]:
"""
Insert triggered events. Silently skips duplicates (serial+timestamp).
Insert triggered events. Silently skips duplicates (serial + timestamp +
record_type: a waveform and a histogram may share a second, #51).
Returns (inserted, skipped).
``waveform_records`` (optional): dict keyed by event waveform_key (hex)
@@ -514,11 +585,17 @@ class SeismoDb:
{"filename": str, "filesize": int, "a5_pickle_filename": str}
For events whose key is in this dict, the matching columns are
populated. If a row with the same (serial, timestamp) already exists
populated. If a row with the same (serial, timestamp, record_type) already exists
(dedup hit), the matching waveform record is upserted onto the
existing row so a re-download via the live endpoint refreshes the
file metadata.
An event whose stored file already has a row under a different time is
the same event re-stored with a corrected time (the waveform event-time
fix moved Series-3 waveforms from the session start to the trigger):
that row is moved to the new time in place, keeping its id and review,
rather than duplicated. See ``_restamp_by_file``.
``device_family`` (optional): "series3" (MiniMate Plus / Blastware) or
"series4" (Micromate / Thor). Drives per-family UI rendering — most
importantly the mic-unit convention (psi vs dB(L)). Set on every
@@ -547,7 +624,31 @@ class SeismoDb:
pi = ev.project_info
rec = wave_recs.get(key) or {}
if getattr(ev, "timestamp_source", None) == "estimate":
# No validated event record: the time may be a second off,
# so it is never allowed to move, merge into or duplicate
# a row (_estimate_guard). The file is already stored.
why = self._estimate_guard(conn, serial, rec.get("filename"), ts,
ev.record_type)
if why:
log.warning("insert_events: %s %s: %s", serial,
rec.get("filename") or key, why)
skipped += 1
continue
elif rec.get("filename") and ts and \
self._restamp_by_file(conn, serial, rec["filename"], ts,
ev.record_type) is False:
skipped += 1
continue
try:
if ev.record_type is None and conn.execute(
"SELECT 1 FROM events WHERE serial = ? AND timestamp = ? "
"AND record_type IS NULL", (serial, ts)).fetchone():
# A UNIQUE key treats NULLs as distinct, so an untyped
# event would never collide: it still refreshes the
# untyped row at its second, as under the old key.
raise sqlite3.IntegrityError("untyped event already stored")
conn.execute(
"""
INSERT INTO events
@@ -607,7 +708,7 @@ class SeismoDb:
inserted += 1
except sqlite3.IntegrityError:
skipped += 1
# UPSERT path: a row for this (serial, timestamp) already
# UPSERT path: a row for this (serial, timestamp, record_type) already
# exists. Refresh every device-authoritative field from
# the new data so that a re-import with better data (e.g.
# a watcher re-forward where the previous attempt missed
@@ -660,7 +761,7 @@ class SeismoDb:
shape_offset_axis = COALESCE(?, shape_offset_axis),
shape_offset_pre = COALESCE(?, shape_offset_pre),
shape_offset_spread = COALESCE(?, shape_offset_spread)
WHERE serial = ? AND timestamp = ?
WHERE serial = ? AND timestamp = ? AND record_type IS ?
""",
(
pv.tran if pv else None,
@@ -697,6 +798,7 @@ class SeismoDb:
rec.get("shape_offset_spread") if rec else None,
serial,
ts,
ev.record_type,
),
)
@@ -704,6 +806,87 @@ class SeismoDb:
serial, inserted, skipped)
return inserted, skipped
@staticmethod
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
ts: Optional[str], record_type: Optional[str] = None) -> Optional[str]:
"""Why an event whose time is only an estimate must not be written, or None.
An estimate (the decoder found no validated event record) may be a
second off, and (serial, timestamp, record_type) is the table's key. So it never
moves a row, never lands on another event's row, and never adds a second
row for an event already stored -- each refusal is logged by the caller,
and the event's file and sidecar are already in the store. Its own
row at the same second is refreshed as before; a free second is stored.
"""
named = filename if filename and blastware_filename_time(filename) is not None else None
if named:
own = [r[0] for r in conn.execute(
"SELECT timestamp FROM events WHERE serial = ? AND blastware_filename = ?",
(serial, named))]
if own and ts not in own:
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
f"time {ts} does not move or duplicate it")
holder = conn.execute(
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
"AND record_type IS ?", (serial, ts, record_type)).fetchone()
if holder is not None and (named is None or holder[0] != named):
return (f"its estimated time {ts} is held by {holder[0] or 'another event'}; "
"not merged into it")
return None
@staticmethod
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
ts: str, record_type: Optional[str] = None) -> Optional[bool]:
"""Move this file's row to `ts` (and `record_type`) when it sits under
another time or type.
The events table is unique on (serial, timestamp), so an event re-stored
with a corrected time -- every Series-3 waveform after the event-time fix,
through the release backfill or a watcher re-forward -- matched nothing
and was inserted a second time (measured 2026-10-26). The same stored
file is the same event: a Blastware name encodes the serial and the time
to the second. Any other name says nothing -- every unnamed upload is
stored as "imported.bw" -- so only a Blastware name is matched. Of
several rows for one file, a reviewed one with a time moves first.
The type moves the same way: before v0.33.0 a row's type came from the
filename, and with the type in the key (#51) a re-import under the file's
own type would otherwise add a second row.
Returns True when the row was moved; None when there was nothing to move
(no row for this file elsewhere, or this file's own row already holds
`ts`), so the caller goes on as before; False when a different stored
file holds `ts` -- moving would collide, and the old upsert would write
this event over that one -- so the caller must store nothing.
"""
if blastware_filename_time(filename) is None:
return None
mine = conn.execute(
"SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? "
"AND (timestamp IS NULL OR timestamp != ? OR record_type IS NOT ?) "
"ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
(serial, filename, ts, record_type),
).fetchone()
if mine is None:
return None
holder = conn.execute(
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
"AND record_type IS ?",
(serial, ts, record_type),
).fetchone()
if holder is None:
conn.execute("UPDATE events SET timestamp = ?, record_type = ? WHERE id = ?",
(ts, record_type, mine[0]))
log.info("insert_events: %s %s moved from %s to %s (corrected event time)",
serial, filename, mine[1], ts)
return True
if holder[1] in (None, filename):
return None
log.warning("insert_events: %s %s decodes to %s, which %s already holds -- "
"row %s left at %s, nothing stored", serial, filename, ts, holder[1],
mine[0], mine[1])
return False
def get_event(self, event_id: str) -> Optional[dict]:
"""Return one event row by id, or None."""
with self._connect() as conn:
@@ -712,6 +895,42 @@ class SeismoDb:
).fetchone()
return dict(row) if row else None
def find_event_by_blastware_name(self, serial: str, filename: str,
record_type: Optional[str] = None) -> Optional[dict]:
"""The row stored under `filename`'s Blastware name, or None.
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. Blastware's direct download is
`<stem>.<AB>0`, its call-in copy and SFM's own files `<stem>.<AB>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.
`record_type`: only a row of that type -- or an untyped one, which may be
this event -- matches (#51: a same-second waveform / histogram twin shares
the letterless name). Compared ignoring case.
"""
if blastware_filename_time(filename) is None:
return None
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:
typed, args = "", (serial, *forms)
if record_type is not None:
typed = " AND (record_type IS NULL OR UPPER(record_type) = UPPER(?))"
args = (*args, record_type)
row = conn.execute(
f"SELECT * FROM events WHERE serial = ? AND UPPER(blastware_filename) IN "
f"({', '.join('?' * len(forms))}){typed} ORDER BY rowid LIMIT 1",
args,
).fetchone()
return dict(row) if row else None
def query_events(
self,
serial: Optional[str] = None,
@@ -1081,6 +1300,121 @@ class SeismoDb:
).fetchall()
return [dict(r) for r in rows]
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────
def mlg_file_exists(self, file_name: str, sha256: str) -> bool:
with self._connect() as conn:
row = conn.execute(
"SELECT 1 FROM mlg_files WHERE file_name = ? AND sha256 = ?",
(file_name, sha256),
).fetchone()
return row is not None
def insert_mlg(
self,
*,
serial: Optional[str],
file_name: str,
sha256: str,
size: int,
empty: bool,
call_in: bool,
file_mtime: Optional[datetime.datetime],
stored_path: Optional[str],
records: list[MlgRecord],
last_stop: Optional[datetime.datetime] = None,
no_file_stops: Optional[list[datetime.datetime]] = None,
) -> tuple[Optional[str], int, int]:
"""Store one .MLG file and its log records, in one transaction.
Returns (file_id, inserted, skipped); (None, 0, 0) when this file name
with these bytes is already stored. A record already stored (from an
earlier file) is skipped and keeps pointing at that file; the file's own
call summary (last_stop, no_file_stops) is kept on its row either way."""
file_id = self._new_id()
inserted = skipped = 0
no_file_json = json.dumps([self._iso(t) for t in (no_file_stops or [])])
with self._connect() as conn:
try:
conn.execute(
"""
INSERT INTO mlg_files
(id, serial, file_name, sha256, size, record_count, empty,
call_in, file_mtime, stored_path, last_stop, no_file_stops)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(file_id, serial, file_name, sha256, size, len(records), int(empty),
int(call_in), self._iso(file_mtime), stored_path, self._iso(last_stop),
no_file_json),
)
except sqlite3.IntegrityError:
return None, 0, 0
for r in records:
cur = conn.execute(
"""
INSERT OR IGNORE INTO mlg_records
(id, serial, start_time, stop_time, flags, trigger_source,
text, trigger_level, event_time, file_id, seq)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(self._new_id(), serial, self._iso(r.start), self._iso(r.stop), r.flags,
r.trigger_source, r.text, r.trigger_level, self._iso(r.event_time),
file_id, r.index),
)
if cur.rowcount:
inserted += 1
else:
skipped += 1
log.debug("insert_mlg %s inserted=%d skipped=%d", file_name, inserted, skipped)
return file_id, inserted, skipped
def query_mlg_records(
self,
serial: str,
from_dt: Optional[datetime.datetime] = None,
to_dt: Optional[datetime.datetime] = None,
) -> list[dict]:
"""A unit's .MLG records, oldest first (start time, then position in file)."""
clauses, params = ["serial = ?"], [serial]
if from_dt:
clauses.append("start_time >= ?")
params.append(from_dt.isoformat())
if to_dt:
clauses.append("start_time <= ?")
params.append(to_dt.isoformat())
with self._connect() as conn:
rows = conn.execute(
f"SELECT * FROM mlg_records WHERE {' AND '.join(clauses)} "
f"ORDER BY start_time, seq",
params,
).fetchall()
return [dict(r) for r in rows]
def query_mlg_files(self, serial: str) -> list[dict]:
"""A unit's received .MLG files, oldest file time first."""
with self._connect() as conn:
rows = conn.execute(
"SELECT * FROM mlg_files WHERE serial = ? "
"ORDER BY COALESCE(file_mtime, received_at), file_name",
(serial,),
).fetchall()
return [dict(r) for r in rows]
def get_mlg_file(self, file_id: str) -> Optional[dict]:
with self._connect() as conn:
row = conn.execute("SELECT * FROM mlg_files WHERE id = ?", (file_id,)).fetchone()
return dict(row) if row else None
def known_serials(self) -> set[str]:
"""Every serial SFM holds data for: events, .MLG files and records."""
with self._connect() as conn:
rows = conn.execute(
"SELECT serial FROM events WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_files WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_records"
).fetchall()
return {r["serial"] for r in rows if r["serial"]}
# ── Fleet overview ────────────────────────────────────────────────────────
def query_units(self) -> list[dict]:
+67 -4
View File
@@ -9,19 +9,29 @@ 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 ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo,
UnitSettings, UnitStatus)
from .s3 import Series3Adapter, default_s3_client_factory
from .s4 import (
Series4Session, default_s4_client_factory, s4_change_monitoring, s4_download_event, s4_identify, s4_list_events,
s4_settings, s4_status,
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
log = logging.getLogger("sfm.device_access")
# A config write is read back at once, not after a sensor check: up to three
# 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:
def __init__(
@@ -109,6 +119,59 @@ class DeviceAccess:
lambda c, s: s4_change_monitoring(c, s, address=address, **kw),
change=True)
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
return self._dispatch(address, serial,
lambda a, s: self._s3.call_home_state(a, s),
lambda c, s: s4_call_home_state(c, s))
def set_call_home(self, address: UnitAddress, serial: str, *, enabled: bool,
dry_run: bool = False, even_if_already: bool = False,
caller: str = "api") -> ChangeResult:
"""Turn the unit's automatic call-home on or off (spec row 9): audited,
identity-checked, never retried, read back."""
serial = normalise_serial(serial)
series_for_serial(serial) # BadRequest (422) before the audit check
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(enabled=enabled, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, caller=caller, sleep=self._sleep,
verify_timeout_s=_CALL_HOME_VERIFY_TIMEOUT_S,
verify_interval_s=_CALL_HOME_VERIFY_INTERVAL_S)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_call_home(a, s, **kw),
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:
+56 -9
View File
@@ -1,4 +1,6 @@
"""The series-independent core of a start/stop request.
"""The series-independent core of a change request: start/stop monitoring,
call-home on/off. A `ChangeKind` says what the change is called and which state
read back means it took.
Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once ->
read back -> audit). Each series supplies only its own pieces as callables:
@@ -20,6 +22,7 @@ never taken there.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, NoReturn, Optional
from .errors import (
@@ -41,7 +44,43 @@ def _never(exc: BaseException) -> bool:
return False
def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_already: bool,
@dataclass(frozen=True)
class ChangeKind:
"""What a change is called (the audit row's action, the messages' subject),
the state `read_state` returns once it took, and the past tense for messages."""
action: str
want: str
became: str
def monitoring_change(start: bool) -> ChangeKind:
return (ChangeKind("start monitoring", "monitoring", "started") if start
else ChangeKind("stop monitoring", "idle", "stopped"))
def call_home_change(enabled: bool) -> ChangeKind:
return (ChangeKind("enable call-home", "enabled", "enabled") if enabled
else ChangeKind("disable call-home", "disabled", "disabled"))
def settings_change() -> ChangeKind:
"""A settings change (phase 5): its "state" is a read-back verdict --
"as asked" (the unit holds what was written), "unchanged", or "differs"."""
return ChangeKind("change settings", "as asked", "applied")
def _take_snapshot(snapshot: Optional[Callable[[], Dict[str, Any]]]) -> Optional[Dict[str, Any]]:
"""The caller's record of what the unit holds after the change -- for the
result and the audit row only. It never decides the outcome."""
if snapshot is None:
return None
try:
return dict(snapshot())
except Exception as exc: # noqa: BLE001 -- a record, never a verdict
return {"error": str(exc)}
def run_change(*, kind: ChangeKind, serial: str, series: int, dry_run: bool, even_if_already: bool,
audit: Any, address: UnitAddress, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float, verify_interval_s: float,
read_serial: Callable[[], str],
@@ -50,10 +89,9 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
send: Callable[[], Dict[str, Any]],
is_refusal: Callable[[BaseException], bool] = _never,
is_ring: Callable[[BaseException], bool] = _never,
pre_send: Optional[Callable[[], None]] = None) -> ChangeResult:
action = "start monitoring" if start else "stop monitoring"
want = "monitoring" if start else "idle"
became = "started" if start else "stopped"
pre_send: Optional[Callable[[], None]] = None,
snapshot: Optional[Callable[[], Dict[str, Any]]] = None) -> ChangeResult:
action, want, became = kind.action, kind.want, kind.became
reported = normalise_serial(read_serial())
if reported != serial:
@@ -175,13 +213,18 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; the unit is now calling home",
states=states([before], after))
lost_detail: Dict[str, Any] = {"error": f"no clean ack: {exc}"}
lost_states = states([before], after)
snap = _take_snapshot(snapshot) # what the unit holds is what tells whether it landed
if snap is not None:
lost_detail["snapshot"] = lost_states["snapshot"] = snap
finish(f"{action} was sent but the acknowledgement was lost ({exc}); the unit "
f"now reads {after}",
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=states([before], after))
error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=lost_states)
return ChangeResult(dry_run=False, sent=True, outcome="failed",
verified="not_checked", state_after=after, audit_id=cid,
detail={"error": f"no clean ack: {exc}"}, **base)
detail=lost_detail, **base)
seen = [before]
@@ -229,9 +272,13 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
detail["note"] = note
if error is None:
error = note
row_states = states(seen, last_poll())
snap = _take_snapshot(snapshot)
if snap is not None:
detail["snapshot"] = row_states["snapshot"] = snap
finish(f"{action} was sent and verified" if ok else
f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}",
outcome=outcome, verified=verified, ack=ack, error=error,
sent=SENT_ACKNOWLEDGED, states=states(seen, last_poll()))
sent=SENT_ACKNOWLEDGED, states=row_states)
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
state_after=seen[-1], audit_id=cid, detail=detail, **base)
+12
View File
@@ -88,6 +88,18 @@ class EventNotFound(DeviceError):
http_status = 404
class SettingsChanged(DeviceError):
"""The unit's settings changed since the preview the request names (a keypad
edit, another program, or a preview of another unit). Nothing was sent."""
http_status = 409
class ChangeRefused(DeviceError):
"""A change SFM will not send to this unit, and why -- its factory setup, a
schedule that would undo it, a block SFM has not seen. Nothing was sent."""
http_status = 409
class StaleEvent(DeviceError):
"""The event at that key is not the one listed -- the unit was erased, or
its memory wrapped, since the list was read."""
+13
View File
@@ -69,6 +69,18 @@ class UnitSettings:
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class CallHomeState:
"""A unit's call-home switch, read by serial (phase 4). `enabled` is None when
the enable byte is not a value ever measured; `detail` keeps `byte5` and the
whole `block` (hex) as read."""
serial: str
series: int
enabled: Optional[bool]
dial_string: Optional[str]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventRef:
"""One stored event, as listed. `event_id` is opaque: pass it back to
@@ -126,6 +138,7 @@ class DownloadedEvent:
filename: str
verified: Optional[bool]
idf_bytes: Optional[bytes] = field(default=None, repr=False)
bw_bytes: Optional[bytes] = field(default=None, repr=False) # Series 3: the assembled Blastware file
event: Any = field(default=None, repr=False)
a5_frames: Optional[list] = field(default=None, repr=False)
compliance: Any = field(default=None, repr=False)
+281 -25
View File
@@ -8,16 +8,29 @@ import struct
from typing import Any, Callable, Optional
from minimateplus import MiniMateClient
from minimateplus.blastware_file import 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
from minimateplus.framing import build_bw_write_frame, unescape_reply
from micromate.setup_block import decode_setup
from micromate.setup_fields import (
SettingsValueError, changes_bytes, check_changes, editable_fields, encode_setup, field_rows,
field_values, settings_state,
)
from micromate.setup_fields import revision as settings_revision
from minimateplus.protocol import (
SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, SUB_COMPLIANCE_WRITE, SUB_EVENT_INDEX_WRITE,
SUB_START_MONITORING, SUB_STOP_MONITORING, SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE,
ImageRefused, call_home_enabled, call_home_image, is_call_home_block, is_compliance_content,
write_image,
)
from minimateplus.transport import TcpTransport
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate
from .change import run_change
from .errors import (BadRequest, ChangeRefused, DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported,
SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit, translate)
from .change import call_home_change, monitoring_change, run_change, settings_change
from .events import iso_of, make_event_id, stamp_of
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
UnitInfo, UnitSettings, UnitStatus)
log = logging.getLogger("sfm.device_access")
@@ -27,9 +40,42 @@ S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "H
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
# A MiniMate call-home write goes out only once SFM's 0x7E / 0x7F frames are
# reproduced from Blastware's own; shut, a live change is refused before any
# connection (a dry run still works). OPEN since 2026-11-02:
# tests/test_s3_call_home_bw_frames.py rebuilds Blastware's enable and disable
# writes (BE11529, 2026-04-20) byte for byte from the unit's own reads.
S3_CALL_HOME_FRAME_VERIFIED = True
# Measured 2026-11-03 (BE9441): while monitoring, a MiniMate answers the 0x2C read
# with its device-info block, as it answers 1A -- its call-home settings cannot be
# read, so they cannot be changed (SFM writes back only a block it just read).
S3_CALL_HOME_WHILE_MONITORING = ("did not return its call-home settings -- a MiniMate answers the "
"call-home read with its device-info block while monitoring; "
"stop monitoring first, then change call-home")
# The 0x1C flag byte (section[1]): the only values ever measured. 0x10 is
# BE11529 monitoring (2026-04-08); 0x0B is BE9441 recording a histogram,
# confirmed at the unit (2026-10-26). Anything else is refused for a change.
# Measured 2026-11-03 (BE9441's 10-26 recording, 5 / 5 reads): while monitoring, a
# MiniMate answers the 1A settings read with its device-info block.
S3_SETTINGS_WHILE_MONITORING = ("did not return its settings -- a MiniMate answers this way "
"while monitoring; stop monitoring first (a stop makes it call in "
"if call-home is on)")
# Blastware's settings write, in its order (push_config_raw): event index, the
# settings block in addressed chunks, trigger, waveform data, with their confirms.
_S3_SETTINGS_STEPS = ((0x68, "event index (as read)"), (0x73, "confirm B"),
(0x71, "settings block"), (0x72, "confirm A"),
(0x82, "trigger block (as read)"), (0x83, "trigger confirm"),
(0x69, "waveform data (as read)"), (0x74, "confirm C"), (0x72, "confirm A"))
_S3_TAIL_WARNING = ("the two bytes after the settings block go out as 00 00 (Blastware sends "
"its own constant; the unit took it at the bench 2026-11-04)")
# Measured at the bench 2026-11-04 (BE9441): a write sent while the setup menu was open
# was acknowledged and read back, then lost when the operator pressed Cancel or Save --
# the menu writes its own copy of the whole block back.
_S3_MENU_WARNING = ("if someone is in this unit's setup menu, this change is lost when they "
"leave it (Cancel or Save writes the menu's copy back)")
S3_RUN_STATES = {0x00: "idle", 0x10: "monitoring", 0x0B: "monitoring"}
@@ -227,13 +273,37 @@ class Series3Adapter:
settle.append(S3_SENSOR_CHECK_S) # the first read waits out the check
return {"subs": [f"0x{ack_sub:02X}"]}
reconnected: list = []
def read_state() -> str:
if settle:
sleep(settle.pop())
return _woken_state(client)
try:
return _woken_state(client)
except OSError as exc:
# The modem can drop the line while the unit sensor-checks
# after a start: BE9441's first wake hit "[Errno 32] Broken
# pipe" (2026-10-29), and a fresh connection read it as
# monitoring. Reconnect once, TCP only (opening a MiniMate's
# serial port reboots it), check it is still the same unit,
# and read. A read -- nothing is re-sent.
if reconnected or not address.host:
raise
reconnected.append(True)
log.warning("Series 3 at %s: the line dropped during the read-back (%s) -- "
"reconnecting to read the state; nothing is re-sent",
address.key, exc)
client.close()
client.open()
# Wake first: the identity read is a bare 0x15, which a unit that
# has just started ignores until SESSION_RESET + POLL (the order
# the status read and the legacy write routes use: poll, then read).
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
self._check(client.read_serial(), serial, address)
return s3_run_state(client.get_monitor_status())
return run_change(
serial=serial, series=3, start=start, dry_run=dry_run,
kind=monitoring_change(start), serial=serial, series=3, dry_run=dry_run,
even_if_already=even_if_already, audit=audit, address=address, caller=caller,
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=read_serial,
@@ -306,29 +376,207 @@ class Series3Adapter:
)
return self._run(address, op)
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
"""The unit's call-home switch and dial string (0x2C), after a wake. Like
status, it reads no serial: the one shown is the one requested."""
def op(client: Any) -> CallHomeState:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
raw = client.read_call_home_raw()
image = unescape_reply(raw)
detail = {"byte5": f"0x{image[5]:02X}" if len(image) > 5 else None,
"block": bytes(raw).hex(), "serial_verified": False}
if not is_call_home_block(raw):
detail["reason"] = f"the unit {S3_CALL_HOME_WHILE_MONITORING}"
return CallHomeState(serial=serial, series=3, enabled=None, dial_string=None, detail=detail)
dial = bytes(image[6:46]).split(b"\x00", 1)[0].decode("ascii", errors="replace") or None
return CallHomeState(serial=serial, series=3, enabled=call_home_enabled(raw),
dial_string=dial, detail=detail)
return self._run(address, op)
def change_call_home(self, address: UnitAddress, serial: str, *, enabled: bool, dry_run: bool,
even_if_already: bool, audit: Any, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-3 pieces for the shared core: read 0x2C, set byte 5 of the
unescaped image, send it (0x7E) and confirm (0x7F), re-read. One attempt,
never retried; refused live until the frame is verified against Blastware."""
if not dry_run and not S3_CALL_HOME_FRAME_VERIFIED:
raise NotSupported("a MiniMate call-home write waits until its frame has been "
"reproduced from a Blastware capture -- nothing sent")
what = "call-home " + ("enable" if enabled else "disable")
def op(client: Any) -> ChangeResult:
reads: list = []
images: list = []
def read_serial() -> str:
return client.connect().serial or "" # a fresh connection: the 0x15 read
def read_state() -> str:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
raw = client.read_call_home_raw()
if not is_call_home_block(raw):
raise UnitStateUnknown(f"{serial} {S3_CALL_HOME_WHILE_MONITORING} -- nothing sent")
reads.append(raw)
on = call_home_enabled(raw)
if on is None:
image = unescape_reply(raw)
return f"unknown(0x{image[5]:02X})" if len(image) > 5 else "unknown(short)"
return "enabled" if on else "disabled"
def describe_plan() -> dict:
try:
image = call_home_image(reads[-1], enabled)
except ValueError as exc:
images[:] = []
return {"action": what, "steps": [], "warnings": [f"{exc}; nothing would be sent"]}
images[:] = [image]
warnings = []
if image == write_image(SUB_CALL_HOME_WRITE, reads[-1]):
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
" -- this write changes nothing")
return {"action": what, "warnings": warnings, "steps": [
{"sub": f"0x{SUB_CALL_HOME_WRITE:02X}", "what": "call-home config write",
"data_len": len(image), "frame": build_bw_write_frame(SUB_CALL_HOME_WRITE, image).hex()},
{"sub": f"0x{SUB_CALL_HOME_CONFIRM:02X}", "what": "call-home config confirm",
"data_len": 0, "frame": build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"").hex()}]}
def send() -> dict:
client.write_call_home_image(images[0])
return {"subs": [f"0x{0xFF - SUB_CALL_HOME_WRITE:02X}", f"0x{0xFF - SUB_CALL_HOME_CONFIRM:02X}"]}
def snapshot() -> dict:
before = write_image(SUB_CALL_HOME_WRITE, reads[0])
after = write_image(SUB_CALL_HOME_WRITE, reads[-1])
return {"before": before.hex(), "after": after.hex(),
"changed_offsets": [i for i in range(min(len(before), len(after)))
if before[i] != after[i]]}
return run_change(
kind=call_home_change(enabled), serial=serial, series=3, dry_run=dry_run,
even_if_already=even_if_already, audit=audit, address=address, caller=caller,
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=read_serial, read_state=read_state,
describe_plan=describe_plan, send=send, snapshot=snapshot,
# raised before the frame goes out: audited as nothing sent
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def change_settings(self, address: UnitAddress, serial: str, *, changes: dict,
revision: Optional[str], dry_run: bool, audit: Any, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-3 pieces for the shared core (phase 5): read the four settings
blocks, patch the settings block's fields (micromate.setup_fields), send
Blastware's sequence through push_config_raw with the other three blocks
as read, re-read the settings. One attempt, never retried.
Refused before anything is sent: a monitoring unit (it answers 1A with its
device-info block); a value the unit does not allow (BadRequest); a live
call whose `revision` is not this read's (SettingsChanged)."""
def op(client: Any) -> ChangeResult:
st: dict = {}
reads: list = []
def read_serial() -> str:
return client.connect().serial or "" # a fresh connection: the 0x15 read
def read_state() -> str:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
if st:
now = client.read_compliance_content()
if not is_compliance_content(now):
raise MalformedReply("the read-back did not return the settings block")
reads.append(now)
return settings_state(st["setup"], st["image"], now, series=3)
blocks = client.read_settings_blocks()
setup = blocks["compliance"]
if not is_compliance_content(setup):
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")
try:
normal = check_changes(setup, 3, changes)
except SettingsValueError as exc:
raise BadRequest(f"{exc} -- nothing sent") from exc
# What the preview showed: the settings block and the changes. The other
# three blocks are re-read here and sent back as read (the trigger block's
# byte 5 "differs by unit and session", #46).
rev = settings_revision([setup, changes_bytes(normal)])
if not dry_run and revision != rev:
raise SettingsChanged(f"{serial}'s settings, or the changes asked for, are not "
"the ones previewed -- preview again; nothing sent")
image = encode_setup(setup, 3, normal)
blocked = []
for sub, block in ((SUB_EVENT_INDEX_WRITE, blocks["event_index"]),
(SUB_COMPLIANCE_WRITE, image),
(SUB_TRIGGER_CONFIG_WRITE, blocks["trigger"]),
(SUB_WAVEFORM_DATA_WRITE, blocks["waveform"])):
try:
write_image(sub, block, escaped=False) # push_config_raw's own check
except ValueError as exc:
blocked.append(f"this unit's {exc} -- SFM has not seen a block like it")
st.update(blocks=blocks, setup=setup, image=image, changes=normal, revision=rev,
blocked=blocked)
reads.append(setup)
return settings_state(setup, image, setup, series=3)
def describe_plan() -> dict:
b = st["blocks"]
lens = {0x68: len(b["event_index"]), 0x71: len(st["image"]) + 2,
0x82: len(b["trigger"]), 0x69: len(b["waveform"])}
if st["blocked"] and not dry_run:
raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent")
steps = [] if st["blocked"] else [
{"sub": f"0x{sub:02X}", "what": what, "data_len": lens.get(sub, 0)}
for sub, what in _S3_SETTINGS_STEPS]
return {"action": "settings write", "blocked": list(st["blocked"]), "steps": steps,
"fields": field_rows(st["setup"], st["image"], 3, st["changes"]),
"revision": st["revision"], "warnings": [_S3_MENU_WARNING, _S3_TAIL_WARNING]}
def send() -> dict:
b = st["blocks"]
client.push_config_raw(b["event_index"], st["image"], b["trigger"], b["waveform"],
escaped=False) # every block read is logical
return {"subs": [f"0x{0xFF - sub:02X}" for sub, _ in _S3_SETTINGS_STEPS]}
def snapshot() -> dict:
before, after = st["setup"], reads[-1]
return {"fields": field_rows(before, st["image"], 3, st["changes"], now=after),
"before": before.hex(), "after": after.hex(),
"changed_offsets": [i for i in range(min(len(before), len(after)))
if before[i] != after[i]]}
return run_change(
kind=settings_change(), serial=serial, series=3, dry_run=dry_run,
even_if_already=False, audit=audit, address=address, caller=caller, sleep=sleep,
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=read_serial, read_state=read_state, describe_plan=describe_plan,
send=send, snapshot=snapshot,
# raised before the first frame goes out: audited as nothing sent
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
"""The 1A read assembled into the logical block and decoded by the shared
settings codec (phase 5)."""
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
}
content = client.read_compliance_content()
if not is_compliance_content(content):
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING}")
v = field_values(content, 3)
name = decode_setup(content + bytes(2), verify=False).name # Series 3 reads no CRC
labels = {d["field"]: d["label"] for d in editable_fields(content, 3)}
notes = {labels[f]: v[f] for f in ("note_1", "note_2", "note_3", "note_4")}
code = content[5]
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,
serial=info.serial, series=3, setup_name=name or None,
record_mode=S3_MODES.get(code, f"unknown (0x{code:02x})"),
sample_rate=v["sample_rate"], record_time_s=v["record_time_s"],
histogram_interval_s=v["histogram_interval_s"], geo_trigger_ips=v["geo_trigger_ips"],
notes=notes,
detail={"record_mode_code": cc.recording_mode, "alarm_level_geo": cc.alarm_level_geo,
"geo_range": cc.geo_range},
detail={"record_mode_code": code, "alarm_level_geo": v["geo_alarm_ips"],
"geo_range": v["geo_range"], "editable": editable_fields(content, 3)},
)
return self._run(address, op)
@@ -378,9 +626,17 @@ class Series3Adapter:
if filename is None:
raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored")
verified, why = verify_s3_download(ev, info.compliance_config)
try:
bw_bytes = blastware_file_bytes(ev, ev._a5_frames)
except ValueError as exc:
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,
bw_bytes=bw_bytes,
compliance=info.compliance_config, timestamp=_s3_dt(ev),
detail={"a5_frames": len(ev._a5_frames), "check": why},
)
+221 -7
View File
@@ -19,16 +19,31 @@ from typing import Any, Callable, Optional, TypeVar
from micromate.client import MicromateClient
from micromate.opcodes import OpcodeRefused
from micromate.protocol import THOR_CHUNK_SIZE
from micromate.writes import plan_start_monitoring, plan_stop_monitoring
from micromate.protocol import ProtocolError as _MMProtocolError
from micromate.schedule import parse_schedule, schedule_conflicts
from micromate.setup_block import decode_setup
from micromate.setup_fields import (
SettingsValueError, changes_bytes, check_changes, editable_fields, encode_setup, field_rows,
settings_state,
)
from micromate.setup_fields import revision as settings_revision
from micromate.writes import (
is_call_home_content, plan_call_home_enabled, plan_setup_push, plan_start_monitoring,
plan_stop_monitoring,
)
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
from .errors import (
AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound,
MalformedReply, StaleEvent, WrongUnit, translate,
AuditIncomplete, BadRequest, CallHomeInProgress, ChangeRefused, ChangeUnconfirmed, DeviceError,
EventNotFound, MalformedReply, SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit,
translate,
)
from .change import (
CALL_HOME_MESSAGE, call_home_change, monitoring_change, run_change, settings_change,
)
from .change import CALL_HOME_MESSAGE, run_change
from .events import iso_of, make_event_id, stamp_of
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
UnitInfo, UnitSettings, UnitStatus)
from .series import normalise_serial
log = logging.getLogger("sfm.device_access")
@@ -265,7 +280,8 @@ def s4_status(client: Any, serial: str, run_state: bool = False) -> UnitStatus:
def s4_settings(client: Any, serial: str) -> UnitSettings:
s = client.get_setup()
content = client.get_setup_content()
s = decode_setup(content)
return UnitSettings(
serial=serial, series=4, setup_name=s.name, record_mode=s.record_mode_name,
sample_rate=s.sample_rate, record_time_s=s.record_time_s,
@@ -290,6 +306,7 @@ def s4_settings(client: Any, serial: str) -> UnitSettings:
"distance_ft": s.distance_ft,
"charge_weight_lb": s.charge_weight_lb,
"scaled_distance": s.scaled_distance,
"editable": editable_fields(content, 4),
},
)
@@ -357,7 +374,8 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
return run_change(
serial=serial, series=4, start=start, dry_run=dry_run, even_if_already=even_if_already,
kind=monitoring_change(start), serial=serial, series=4, dry_run=dry_run,
even_if_already=even_if_already,
audit=audit, address=address, caller=caller, sleep=sleep,
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=lambda: client.serial(refresh=True),
@@ -369,3 +387,199 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
# out. One transport read: RingWatchTransport over Tcp/SerialTransport,
# each with a 10 ms read timeout, so it returns at once on a quiet line.
pre_send=lambda: client.read_unsolicited())
def _dial_string(block: bytes) -> Optional[str]:
raw = bytes(block[6:46]).split(b"\x00", 1)[0]
return raw.decode("ascii", errors="replace") or None
def _changed_offsets(before: bytes, after: bytes) -> list:
return [i for i in range(max(len(before), len(after)))
if (before[i] if i < len(before) else None) != (after[i] if i < len(after) else None)]
# Measured 2026-11-03 (UM20147): monitoring, a Micromate returns its real call-home
# block and ACKS a write, but does not apply it -- its own menu: "Feature disabled
# while monitoring". So SFM refuses before sending one it would ignore.
S4_CALL_HOME_WHILE_MONITORING = ("is monitoring -- a Micromate ignores call-home changes while "
"monitoring (its own menu: 'Feature disabled while monitoring'); "
"stop monitoring first, then change call-home")
_NOT_CALL_HOME = "returned a block that is not its call-home block (header {}, not 007c)"
def s4_call_home_state(client: Any, serial: str) -> CallHomeState:
"""Bit 0 of content[5] is the enable (UM12947 reads 0x05 / 0x04, UM20147 0x01)."""
block = client.get_call_home_content()
detail = {"byte5": f"0x{block[5]:02X}" if len(block) > 5 else None, "block": block.hex()}
if not is_call_home_content(block):
detail["reason"] = "the unit " + _NOT_CALL_HOME.format(block[0:2].hex())
return CallHomeState(serial=serial, series=4, enabled=None, dial_string=None, detail=detail)
return CallHomeState(serial=serial, series=4, enabled=bool(block[5] & 0x01),
dial_string=_dial_string(block), detail=detail)
def s4_change_call_home(client: Any, serial: str, *, enabled: bool, dry_run: bool,
even_if_already: bool, audit: Any, address: UnitAddress,
caller: str, sleep: Callable[[float], None],
verify_timeout_s: float, verify_interval_s: float) -> ChangeResult:
"""Series-4 pieces for the shared core: read 0x2C, flip bit 0 of [5], send the
rest back byte for byte, re-read. The plan is built from the read run_change
made just before it (spec: build the plan on the same line, right before
sending), and that same plan is the one sent."""
reads: list = []
planned: list = []
def read_state() -> str:
run = client.read_run_state().name
if run == "calling_home" or run.startswith("unknown"):
return run # the core refuses both; a write waits for a known state
if run == "monitoring" and not reads:
raise UnitStateUnknown(f"{serial} {S4_CALL_HOME_WHILE_MONITORING} -- nothing sent")
block = client.get_call_home_content()
if not is_call_home_content(block):
raise UnitStateUnknown(f"{serial} " + _NOT_CALL_HOME.format(block[0:2].hex())
+ " -- nothing sent")
reads.append(block)
return "enabled" if block[5] & 0x01 else "disabled"
def describe_plan() -> dict:
planned[:] = [plan_call_home_enabled(reads[-1], enabled)]
return planned[0].describe()
def send() -> dict:
acks = client.protocol.execute(planned[0])
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
def snapshot() -> dict:
before, after = reads[0], reads[-1]
return {"before": before.hex(), "after": after.hex(),
"changed_offsets": _changed_offsets(before, after)}
return run_change(
kind=call_home_change(enabled), serial=serial, series=4, dry_run=dry_run,
even_if_already=even_if_already, audit=audit, address=address, caller=caller, sleep=sleep,
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=lambda: client.serial(refresh=True),
read_state=read_state, describe_plan=describe_plan, send=send,
is_refusal=lambda e: isinstance(e, OpcodeRefused),
is_ring=lambda e: isinstance(e, RingDetected),
pre_send=lambda: client.read_unsolicited(),
snapshot=snapshot)
# ── Changing settings (phase 5) ──────────────────────────────────────────────
S4_SETTINGS_WHILE_MONITORING = ("is monitoring -- stop it first (a stop makes it call in if "
"call-home is on)")
_EDIT_BUFFER_WARNING = ("this reads the unit's keypad edit buffer: if someone is in its menu, "
"their unsaved edits are sent too")
_FACTORY = "factory.mmb"
def s4_change_settings(client: Any, serial: str, *, changes: dict, revision: Optional[str],
dry_run: bool, audit: Any, address: UnitAddress, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-4 pieces for the shared core: read the name, preferences, trigger
and setup blocks and the schedule; patch the setup's fields
(micromate.setup_fields); send THOR's setup push under the active setup's own
name; read the setup back. The plan is built from the read run_change made
just before it, and that same plan is the one sent.
Refused before anything is sent: a monitoring unit; values the unit does not
allow (BadRequest); a live call whose `revision` is not this read's
(SettingsChanged); the factory setup, a schedule that would load another
setup, an unreadable schedule, or a block SFM has not seen (ChangeRefused,
shown as `blocked` in a preview)."""
st: dict = {}
reads: list = []
def first_read() -> str:
name = client.get_active_setup_raw()
prefs = client.get_prefs_content()
trigger = client.get_trigger_content()
setup = client.get_setup_content()
try:
normal = check_changes(setup, 4, changes)
except SettingsValueError as exc:
raise BadRequest(f"{exc} -- nothing sent") from exc
# What the preview showed: the target name, the setup block, the changes. The
# preferences and trigger blocks are re-read here and sent back as read.
rev = settings_revision([name.encode("ascii", "replace"), setup, changes_bytes(normal)])
if not dry_run and revision != rev:
raise SettingsChanged(f"{serial}'s settings, or the changes asked for, are not the ones "
"previewed -- preview again; nothing sent")
image = encode_setup(setup, 4, normal)
blocked: list = []
warnings = [_EDIT_BUFFER_WARNING]
if name.strip().casefold() == _FACTORY:
blocked.append("this unit is running its factory setup; load any other setup on "
"its keypad, then try again")
try:
entries = parse_schedule(client.read_schedule())
except (_MMProtocolError, ValueError) as exc:
blocked.append(f"could not read this unit's schedule ({exc}) -- SFM will not change "
"a unit whose schedule it cannot check")
else:
conflicts = schedule_conflicts(entries, name)
for e in conflicts:
blocked.append(f"this unit's schedule loads {e.setup} at {e.time}, which would "
"replace this change")
for e in entries:
if "start_with_setup" in e.actions and e not in conflicts:
warnings.append(f"the unit's schedule loads this setup at {e.time}; the "
"change survives it")
plan = None
try:
plan = plan_setup_push(prefs, trigger, image, name)
except ValueError as exc:
blocked.append(f"this unit's {exc} -- SFM has not seen a block like it")
st.update(name=name, prefs=prefs, trigger=trigger, setup=setup, image=image,
changes=normal, revision=rev, blocked=blocked, warnings=warnings, plan=plan)
reads.append(setup)
return settings_state(setup, image, setup, series=4)
def read_state() -> str:
run = client.read_run_state().name
if run == "calling_home" or run.startswith("unknown"):
return run # the core refuses both; a write waits for a known state
if not st:
if run == "monitoring":
raise UnitStateUnknown(f"{serial} {S4_SETTINGS_WHILE_MONITORING} -- nothing sent")
return first_read()
now = client.get_setup_content()
reads.append(now)
return settings_state(st["setup"], st["image"], now, series=4)
def describe_plan() -> dict:
ok = st["plan"] is not None and not st["blocked"]
d = st["plan"].describe() if ok else {"action": "setup push", "steps": [], "warnings": []}
d["warnings"] = list(st["warnings"]) + list(d.get("warnings", []))
d.update(fields=field_rows(st["setup"], st["image"], 4, st["changes"]),
revision=st["revision"], blocked=list(st["blocked"]))
if st["blocked"] and not dry_run:
raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent")
return d
def send() -> dict:
acks = client.protocol.execute(st["plan"])
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
def snapshot() -> dict:
before, after = st["setup"], reads[-1]
return {"fields": field_rows(before, st["image"], 4, st["changes"], now=after),
"before": before.hex(), "after": after.hex(),
"changed_offsets": _changed_offsets(before, after),
"prefs": st["prefs"].hex(), "trigger": st["trigger"].hex()}
return run_change(
kind=settings_change(), serial=serial, series=4, dry_run=dry_run, even_if_already=False,
audit=audit, address=address, caller=caller, sleep=sleep,
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=lambda: client.serial(refresh=True),
read_state=read_state, describe_plan=describe_plan, send=send,
is_refusal=lambda e: isinstance(e, OpcodeRefused),
is_ring=lambda e: isinstance(e, RingDetected),
pre_send=lambda: client.read_unsolicited(),
snapshot=snapshot)
+69 -4
View File
@@ -32,6 +32,16 @@ Layout written to `<filename>.h5`:
client str
operator str
sensor_location str
job_number int (only when read; kept while not shown)
job_number_enabled bool (Blastware prints the job number)
battery_volts, triggered_by, trigger_sources, trigger_level_geo_ips,
trigger_level_mic_psi, firmware_version, dsp_version, model,
calibration_date (ISO), calibrated_by
(each only when read from the event file)
histogram_interval_sec int (histograms)
/intervals (histograms, when read)
half_period/<ch> uint16 samples per interval; Hz = (sample rate / 2) / it
pvs_ips float32 each interval's vector sum, in/s
peak_tran_ips float (from 0C; authoritative)
peak_vert_ips float
peak_long_ips float
@@ -139,17 +149,23 @@ def _ts_iso(ts) -> str:
def _samples_to_float(
samples_int16: list[int],
full_scale: float,
*,
ips_per_count: Optional[float] = None,
) -> np.ndarray:
"""Convert int16 ADC counts → float32 physical units.
Uses _GEO_INT16_FS=32000 (see the constant's rationale): one decoder
unit (16 ADC counts) is exactly 0.005 in/s, so full scale is 32000
counts, not 32768.
counts, not 32768. That is the MiniMate body codec's count; a source
with a different count scale passes ``ips_per_count`` instead (Thor:
``micromate.idf_file._GEO_LSB_IPS``).
"""
if not samples_int16:
return np.array([], dtype=np.float32)
if ips_per_count is None:
ips_per_count = full_scale / _GEO_INT16_FS
arr = np.asarray(samples_int16, dtype=np.int32) # int32 to avoid overflow during scale
return (arr.astype(np.float32) * (full_scale / _GEO_INT16_FS)).astype(np.float32)
return (arr.astype(np.float32) * ips_per_count).astype(np.float32)
def _mic_scale_factor(
@@ -174,15 +190,23 @@ def write_event_hdf5(
event: Event,
*,
serial: str,
geo_range = "normal",
geo_range = None,
source_kind: str = "sfm-live",
tool_version: Optional[str] = None,
captured_at: Optional[datetime.datetime] = None,
include_int16: bool = True,
geo_ips_per_count: Optional[float] = None,
) -> dict:
"""
Persist a decoded Event as an HDF5 file with samples in physical units.
``geo_range`` left as None takes the event's own (``event.geo_range``,
which a Blastware file's decode reads from its setup block), else Normal.
``geo_ips_per_count`` overrides the range-derived MiniMate count scale
for sources whose counts differ — Thor IDF imports pass
``micromate.idf_file._GEO_LSB_IPS`` (issue #42).
Returns a small summary dict suitable for logging:
{"path": Path, "n_samples": int, "geo_full_scale_ips": float}
"""
@@ -191,6 +215,8 @@ def write_event_hdf5(
pv = event.peak_values
pi = event.project_info
if geo_range is None:
geo_range = event.geo_range if getattr(event, "geo_range", None) is not None else "normal"
geo_fs = _resolve_geo_full_scale(geo_range)
geo_range_str = _normalise_range(geo_range)
captured_at = captured_at or datetime.datetime.utcnow()
@@ -199,7 +225,9 @@ def write_event_hdf5(
# Per-channel float32 arrays in physical units.
geo_arrays = {}
for ch in ("Tran", "Vert", "Long"):
geo_arrays[ch] = _samples_to_float(raw.get(ch, []), geo_fs)
geo_arrays[ch] = _samples_to_float(
raw.get(ch, []), geo_fs, ips_per_count=geo_ips_per_count,
)
# Mic channel — the per-count factor is resolved from the device-reported
# peak when available so the plot peaks the BW value exactly.
@@ -239,6 +267,27 @@ def write_event_hdf5(
attrs["client"] = (pi.client if pi else "") or ""
attrs["operator"] = (pi.operator if pi else "") or ""
attrs["sensor_location"] = (pi.sensor_location if pi else "") or ""
if pi is not None and getattr(pi, "job_number", None) is not None:
attrs["job_number"] = int(pi.job_number)
attrs["job_number_enabled"] = bool(pi.job_number_enabled)
# Read from a Blastware file's identity and setup blocks; absent when not read.
for attr, value in (
("battery_volts", getattr(event, "battery_volts", None)),
("triggered_by", getattr(event, "triggered_by", None)),
("trigger_sources", getattr(event, "trigger_sources", None)),
("trigger_level_geo_ips", getattr(event, "trigger_level_geo", None)),
("trigger_level_mic_psi", getattr(event, "trigger_level_mic_psi", None)),
("histogram_interval_sec", getattr(event, "histogram_interval_sec", None)),
):
if value is not None:
attrs[attr] = value
di = getattr(event, "device_info", None)
if di is not None:
for attr in ("firmware_version", "dsp_version", "model", "calibrated_by"):
if getattr(di, attr, None):
attrs[attr] = getattr(di, attr)
if getattr(di, "calibration_date", None) is not None:
attrs["calibration_date"] = di.calibration_date.isoformat()
attrs["peak_tran_ips"] = float(pv.tran if pv and pv.tran is not None else 0.0)
attrs["peak_vert_ips"] = float(pv.vert if pv and pv.vert is not None else 0.0)
attrs["peak_long_ips"] = float(pv.long if pv and pv.long is not None else 0.0)
@@ -260,6 +309,22 @@ def write_event_hdf5(
compression="gzip", compression_opts=4, shuffle=True,
)
# /intervals — a histogram's per-interval detail as the file holds it:
# each channel's half-period in samples (frequency = (sample rate / 2)
# / half-period; 0 is Blastware's "N/A") and each interval's vector sum.
half_periods = getattr(event, "interval_half_periods", None)
interval_pvs = getattr(event, "interval_pvs", None)
if half_periods or interval_pvs:
igrp_iv = f.create_group("intervals")
if half_periods:
hgrp = igrp_iv.create_group("half_period")
for ch, hps in half_periods.items():
hgrp.create_dataset(ch, data=np.asarray(hps, dtype="uint16"),
compression="gzip", compression_opts=4, shuffle=True)
if interval_pvs:
igrp_iv.create_dataset("pvs_ips", data=np.asarray(interval_pvs, dtype="float32"),
compression="gzip", compression_opts=4, shuffle=True)
# /samples_int16 — optional raw ADC counts (preserved for analysis
# tools that want pre-conversion data). Cheap to include.
if include_int16:
+98 -10
View File
@@ -66,6 +66,51 @@ def _already_stored(dl: DownloadedEvent, row: dict) -> EventDownload:
)
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.
@@ -89,13 +134,45 @@ def _overlay_s4_record(ev: Any, record: dict) -> None:
ev.project_info.sensor_location = location
def _download_record_type(dl: DownloadedEvent) -> Optional[str]:
"""The download's own record type -- "Waveform" / "Histogram", as every stored
row has it -- from its file: a Series-3 file's STRT[18], a Series-4 name's
IDFW / IDFH. None when it does not read (then any row at its second counts)."""
if dl.series == 4:
ext = dl.filename.rsplit(".", 1)[-1].upper()
return {"IDFW": "Waveform", "IDFH": "Histogram"}.get(ext)
if not dl.bw_bytes:
return None
try:
from minimateplus.event_file_io import decode_blastware_bytes
return decode_blastware_bytes(dl.bw_bytes).record_type
except Exception: # noqa: BLE001 -- a check, not a decode
return None
def _same_type(row_type: Optional[str], mine: Optional[str]) -> bool:
"""An untyped row, or a download whose type does not read, matches
conservatively: it may be this event."""
return row_type is None or mine is None or row_type.casefold() == mine.casefold()
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.
# Never merge: a row for (serial, timestamp, record type) means the event is
# stored, and whoever stored it first keeps it. No store call, no insert, no
# sidecar. The type matters since #51: a waveform and a histogram recorded in
# the same second (Histogram + Continuous) are two events.
kind = _download_record_type(dl)
if dl.timestamp is not None:
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1)
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=10)
rows = [r for r in rows if _same_type(r.get("record_type"), kind)]
if rows:
return _already_stored(dl, rows[0])
# The Blastware name encodes the event's second (a second guard; before #51 a
# histogram's row sat a second off the unit's time). Both twins share the
# letterless name, so it too is held to the type.
row = db.find_event_by_blastware_name(dl.serial, dl.filename, record_type=kind)
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)
@@ -103,13 +180,24 @@ def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownlo
_overlay_s4_record(ev, dl.record)
family = "series4"
else:
ev = dl.event
if ev is None:
raise IngestError(f"{dl.filename}: the download carried no event; nothing was stored")
backfill_series3_event(ev, dl.compliance)
geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None
rec = store.save(ev, serial=dl.serial, a5_frames=dl.a5_frames,
geo_range=geo_range if geo_range is not None else "normal")
# 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")
+130
View File
@@ -0,0 +1,130 @@
"""
sfm/mlg_ingest.py — take in one Blastware .MLG: verify it, work out its unit,
keep the original, store its records once.
Shared by POST /db/import/mlg_file and scripts/import_mlg_dir.py. Spec:
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3, §5, §6.
"""
from __future__ import annotations
import datetime
import hashlib
import logging
import re
from pathlib import Path
from typing import Optional
from minimateplus.mlg_file import MlgFormatError, parse_mlg
log = logging.getLogger("sfm.mlg_ingest")
_MODEM_EXIT = 0x0020
# A serial becomes a directory in the waveform store, and a header serial comes
# from the file's own bytes: only plain serials (BE6907, UM20147) are used.
_SERIAL_RE = re.compile(r"[A-Za-z0-9]{1,16}")
def usable_serial(serial: Optional[str]) -> bool:
return bool(serial) and _SERIAL_RE.fullmatch(serial) is not None
def resolve_serial(
file_name: str,
header_serial: Optional[str],
hint: Optional[str],
known: set[str],
) -> Optional[str]:
"""The unit a .MLG belongs to.
The serial inside the file wins; then the caller's hint. An empty file
carries none, and its name is <serial><counter> with nothing between, so
take the longest serial SFM already knows that the name starts with,
followed only by digits (or nothing: DL2's first file was BE8081.MLG).
None when nothing fits."""
if header_serial:
return header_serial
if hint:
return hint
stem = Path(file_name).name
if stem.upper().endswith(".MLG"):
stem = stem[:-4]
def fits(serial: str) -> bool:
counter = stem[len(serial):]
return stem.upper().startswith(serial.upper()) and (counter == "" or counter.isdigit())
candidates = [s for s in known if fits(s)]
return max(candidates, key=len) if candidates else None
def ingest_mlg(
db,
store,
file_name: str,
data: bytes,
*,
serial_hint: Optional[str] = None,
file_mtime: Optional[datetime.datetime] = None,
call_in: bool = True,
) -> dict:
"""Ingest one .MLG. Never raises for a bad file: the result says what happened.
status "error": not a whole .MLG, or any record fails its checksum — nothing
of it is stored. status "duplicate": this name with these bytes is already
stored. status "ok": the original is kept and its new records stored."""
result = {
"filename": file_name, "status": "error", "detail": None, "serial": None,
"serial_unresolved": False, "empty": False, "records": 0,
"inserted": 0, "skipped": 0, "file_id": None,
}
try:
mlg = parse_mlg(data)
except MlgFormatError as exc:
result["detail"] = str(exc)
return result
result["records"] = len(mlg.records)
result["empty"] = mlg.empty
if mlg.crc_failures:
result["detail"] = ", ".join(f"record {i}" for i in mlg.crc_failures) + " fails its checksum"
return result
header = mlg.serial or None
for label, value in (("the file's serial", header), ("the serial hint", serial_hint)):
if value is not None and not usable_serial(value):
result["detail"] = f"{label} {value!r} is not a plain serial"
return result
known = db.known_serials() if not (header or serial_hint) else set()
serial = resolve_serial(file_name, header, serial_hint, known)
if mlg.records and serial is None:
result["detail"] = "no serial: the file's header carries none and no hint was given"
return result
result["serial"] = serial
result["serial_unresolved"] = serial is None
# What this file says about calls, kept per file: a record stored once may
# have arrived first in another file (a cable download). The file was sent
# by the call that ended its last record; every earlier Modem Exit in it was
# a call that left no file.
last_stop = mlg.records[-1].stop if mlg.records else None
no_file_stops = [r.stop for r in mlg.records[:-1]
if not r.is_start and r.flags & _MODEM_EXIT and r.stop]
sha256 = hashlib.sha256(data).hexdigest()
if db.mlg_file_exists(file_name, sha256):
result["status"] = "duplicate"
result["detail"] = "this file is already stored"
return result
stored_path = store.save_mlg(serial, file_name, data)
file_id, inserted, skipped = db.insert_mlg(
serial=serial, file_name=file_name, sha256=sha256, size=len(data), empty=mlg.empty,
call_in=call_in, file_mtime=file_mtime, stored_path=stored_path, records=mlg.records,
last_stop=last_stop, no_file_stops=no_file_stops,
)
if file_id is None: # stored between the check and the insert
result["status"] = "duplicate"
result["detail"] = "this file is already stored"
return result
result.update(status="ok", file_id=file_id, inserted=inserted, skipped=skipped)
log.info("mlg %s serial=%s inserted=%d skipped=%d", file_name, serial, inserted, skipped)
return result
+359
View File
@@ -0,0 +1,359 @@
"""
sfm/mlg_timeline.py — a unit's monitoring timeline from its .MLG records.
Pure: takes the rows SeismoDb.query_mlg_records / query_mlg_files return and
gives back plain dicts (times as ISO strings). Spec §4,
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
How sessions appear in a .MLG (measured on BE6907, BE12844, BE8081):
* a session with no events is one closed record: start, stop and why it stopped
* a session with events is a "monitoring started" record (flags 0xFFFF, no
stop), then the events, in the same file; the unit calls in after each
event and monitoring resumes as a new session, so the first session's end
is not written anywhere -- it lies between its last event's stop and the
next start
* a histogram session is a "monitoring started" record at T, then a histogram
record from T+1 s to the stop, carrying the stop reason
Times are the unit's own clock. When it steps back an hour after daylight
saving ends, a session starts before the previous one stopped: that is a clock
step, never a negative gap. Sessions are built in start order, but an event
always joins the "monitoring started" record of its own file, so a call-in on
the step day cannot move an event into the wrong session.
Every session and call-in names the records and files it rests on, so a shot
report can attach the original .MLG (GET /db/mlg_files/{id}).
"""
from __future__ import annotations
import datetime
import json
from dataclasses import dataclass
from typing import Optional
from minimateplus.event_file_io import monitor_log_description
_STARTED = 0xFFFF
_RECORDED = 0x0001
_HISTOGRAM_SOURCE = 0x0400
_JOIN_SECONDS = 2 # a histogram record starts 1 s after its "started" record
_GAP_MEANING = {
"Modem Exit": "call-in",
"Timer Stop": "scheduled off",
"Battery Low Exit": "lost power",
"Keyboard Exit": "stopped by a person",
"Remote Exit": "stopped by a person",
"Memory Full Exit": "memory full",
}
# A call-in takes minutes (BE12844 2, BE8081 5, measured). A longer gap after a
# Modem Exit, with no call-in file missing, is a unit that did not restart (BE6907
# for 14 days from 2026-10-07; BE8081 over Labor Day 2019).
_LONG_CALL_IN_MINUTES = 60
NO_RESTART = "no restart after a call-in"
# Each call-in file holds everything since the previous one and is numbered
# <serial><counter>. Records can be missing only where a number is: then the
# gap cannot say the unit was not monitoring.
RECORDS_MISSING = "records missing"
_MISSING_LISTED = 20
@dataclass
class _Rec:
id: str
file_id: str
start: datetime.datetime
stop: Optional[datetime.datetime]
flags: int
source: int
trigger_level: Optional[str]
seq: int
def _dt(value: Optional[str]) -> Optional[datetime.datetime]:
if not value:
return None
if value.endswith("Z"): # Python 3.10's fromisoformat rejects "Z"
value = value[:-1] + "+00:00"
return datetime.datetime.fromisoformat(value)
def _iso(value: Optional[datetime.datetime]) -> Optional[str]:
return value.isoformat() if value else None
def _ended_by(flags: int) -> Optional[str]:
return monitor_log_description(flags & ~_RECORDED & 0xFFFF).strip() or None
def _kind(r: _Rec) -> str:
if r.flags == _STARTED or r.stop is None:
return "start" # no stop: monitoring began here, its end is not known
if r.flags & _RECORDED:
return "histogram" if r.source == _HISTOGRAM_SOURCE else "event"
return "closed"
def _session(start, *, stop=None, ended_by=None, kind="monitoring", trigger_level=None) -> dict:
return {"start": start, "stop": stop, "end_after": None, "end_before": None,
"ended_by": ended_by, "kind": kind, "trigger_level": trigger_level,
"running_at_last_report": False, "events": [], "record_ids": [], "file_ids": []}
def _note(s: dict, r: _Rec) -> None:
s["record_ids"].append(r.id)
if r.file_id not in s["file_ids"]:
s["file_ids"].append(r.file_id)
def _event(r: _Rec) -> dict:
return {"start": r.start, "stop": r.stop, "trigger_source": r.source,
"trigger_level": r.trigger_level, "record_id": r.id,
"description": monitor_log_description(r.flags).strip()}
def _last_running_point(s: dict) -> datetime.datetime:
if s["events"]:
return s["events"][-1]["stop"] or s["events"][-1]["start"]
return s["start"]
def _sessions(recs: list[_Rec]) -> list[dict]:
sessions: list[dict] = []
pending: Optional[dict] = None # a session whose stop is not known yet
started_in_file: dict[str, dict] = {} # file id -> the session its latest start record opened
def close_pending(before: datetime.datetime) -> None:
nonlocal pending
if pending is not None:
pending["end_after"] = _last_running_point(pending)
pending["end_before"] = before
pending = None
def own_file_session(r: _Rec) -> Optional[dict]:
s = started_in_file.get(r.file_id)
if s is None or r.start < s["start"]:
return None
if s["stop"] is not None and r.start > s["stop"]:
return None
return s
for r in recs:
kind = _kind(r)
if kind == "start":
close_pending(r.start)
pending = _session(r.start, trigger_level=r.trigger_level)
_note(pending, r)
started_in_file[r.file_id] = pending
sessions.append(pending)
elif kind == "histogram":
if pending is not None and (r.start - pending["start"]).total_seconds() <= _JOIN_SECONDS:
pending.update(stop=r.stop, kind="histogram", ended_by=_ended_by(r.flags))
pending["trigger_level"] = pending["trigger_level"] or r.trigger_level
_note(pending, r)
pending = None
else:
close_pending(r.start)
s = _session(r.start, stop=r.stop, kind="histogram",
ended_by=_ended_by(r.flags), trigger_level=r.trigger_level)
_note(s, r)
sessions.append(s)
elif kind == "event":
own = own_file_session(r)
last = sessions[-1] if sessions else None
if own is not None:
own["events"].append(_event(r))
_note(own, r)
if own is pending:
if _ended_by(r.flags):
own.update(stop=r.stop, ended_by=_ended_by(r.flags))
pending = None
elif own["stop"] is None:
# A later session (another file) closed its window first: the
# unit's clock stepped back at the call-in after this event.
own["end_after"] = _last_running_point(own)
if own["end_before"] is not None and own["end_after"] > own["end_before"]:
own["end_before"] = None
elif last is not None and last["stop"] is not None and last["start"] <= r.start <= last["stop"]:
last["events"].append(_event(r))
_note(last, r)
elif pending is not None:
pending["events"].append(_event(r))
_note(pending, r)
if _ended_by(r.flags):
pending.update(stop=r.stop, ended_by=_ended_by(r.flags))
pending = None
else:
s = _session(r.start, trigger_level=r.trigger_level)
s["events"].append(_event(r))
_note(s, r)
if _ended_by(r.flags):
s.update(stop=r.stop, ended_by=_ended_by(r.flags))
else:
pending = s
sessions.append(s)
else:
close_pending(r.start)
s = _session(r.start, stop=r.stop, ended_by=_ended_by(r.flags),
trigger_level=r.trigger_level)
_note(s, r)
sessions.append(s)
if pending is not None:
pending["running_at_last_report"] = True
pending["end_after"] = _last_running_point(pending)
return sessions
def _counter(file_name: str, serial: Optional[str]) -> Optional[int]:
"""The call-in number in <serial><counter>.MLG; a bare <serial>.MLG is 0."""
stem = file_name[:-4] if file_name.upper().endswith(".MLG") else file_name
if not serial or not stem.upper().startswith(serial.upper()):
return None
rest = stem[len(serial):]
if rest == "":
return 0
return int(rest) if rest.isdigit() else None
def _missing_between(a: Optional[int], b: Optional[int], received: set[int]) -> list[int]:
if a is None or b is None or b <= a + 1:
return []
return [c for c in range(a + 1, b) if c not in received][:_MISSING_LISTED]
def _gaps_and_steps(sessions: list[dict], counter_of: dict[str, Optional[int]],
received: set[int]) -> tuple[list[dict], list[dict]]:
gaps, steps = [], []
for prev, nxt in zip(sessions, sessions[1:]):
end = prev["stop"] or prev["end_after"]
minutes = (nxt["start"] - end).total_seconds() / 60
if nxt["start"] < end:
steps.append({"previous_stop": end, "next_start": nxt["start"], "minutes": minutes})
continue
missing = _missing_between(counter_of.get(prev["file_ids"][-1]),
counter_of.get(nxt["file_ids"][0]), received)
meaning = _GAP_MEANING.get(prev["ended_by"], "unknown")
if missing:
meaning = RECORDS_MISSING
elif meaning == "call-in" and minutes > _LONG_CALL_IN_MINUTES:
meaning = NO_RESTART
gaps.append({"start": end, "stop": nxt["start"], "minutes": minutes, "meaning": meaning,
"missing_files": missing})
return gaps, steps
def _call_ins(files: list[dict]) -> list[dict]:
"""From each file's own call summary, written when it arrived (a record
stored once may have come first in another file)."""
out = []
for f in files:
if not f["call_in"]:
continue
base = {"file_name": f["file_name"], "file_id": f["id"]}
file_time = _iso(_dt(f["file_mtime"] or f["received_at"]))
if not f["record_count"]:
out.append({"kind": "nothing_new", "unit_time": None, "file_time": file_time, **base})
continue
for stop in json.loads(f["no_file_stops"] or "[]"):
out.append({"kind": "no_file", "unit_time": stop, "file_time": None, **base})
out.append({"kind": "delivered", "unit_time": f["last_stop"], "file_time": file_time, **base})
return out
def build_timeline(records: list[dict], files: list[dict]) -> dict:
"""Sessions, gaps (with what each means), clock steps and call-ins."""
recs = sorted(
(_Rec(r["id"], r["file_id"], _dt(r["start_time"]), _dt(r["stop_time"]), r["flags"],
r["trigger_source"], r["trigger_level"], r["seq"]) for r in records),
key=lambda r: (r.start, 0 if r.flags == _STARTED else 1, r.seq),
)
sessions = _sessions(recs)
counter_of = {f["id"]: _counter(f["file_name"], f["serial"]) for f in files if f["call_in"]}
received = {c for c in counter_of.values() if c is not None}
gaps, steps = _gaps_and_steps(sessions, counter_of, received)
for s in sessions:
for key in ("start", "stop", "end_after", "end_before"):
s[key] = _iso(s[key])
for e in s["events"]:
e["start"], e["stop"] = _iso(e["start"]), _iso(e["stop"])
for g in gaps:
g["start"], g["stop"] = _iso(g["start"]), _iso(g["stop"])
for c in steps:
c["previous_stop"], c["next_start"] = _iso(c["previous_stop"]), _iso(c["next_start"])
return {"sessions": sessions, "gaps": gaps, "clock_steps": steps, "call_ins": _call_ins(files)}
def window(timeline: dict, from_dt: Optional[datetime.datetime],
to_dt: Optional[datetime.datetime]) -> dict:
"""The parts of a timeline that overlap [from_dt, to_dt] (the unit's clock).
Sessions, gaps and clock steps are on the unit's clock and filter exactly.
A call-in with a unit time filters by it. A nothing_new call-in has only
the PC's file time (UTC); it is kept when within a day of the window, since
the unit's local clock and UTC differ by hours and cannot be compared
exactly."""
lo = from_dt or datetime.datetime.min
hi = to_dt or datetime.datetime.max
def overlaps(start: Optional[str], end: Optional[str]) -> bool:
s = _dt(start) or datetime.datetime.min
e = _dt(end) or datetime.datetime.max
return s <= hi and e >= lo
def call_in_kept(c: dict) -> bool:
if c["unit_time"]:
return lo <= _dt(c["unit_time"]) <= hi
if not c["file_time"]:
return True
t = _dt(c["file_time"]).replace(tzinfo=None)
day = datetime.timedelta(days=1)
return (lo == datetime.datetime.min or t >= lo - day) and (hi == datetime.datetime.max or t <= hi + day)
return {
"sessions": [s for s in timeline["sessions"]
if overlaps(s["start"], None if s["running_at_last_report"]
else s["stop"] or s["end_before"])],
"gaps": [g for g in timeline["gaps"] if overlaps(g["start"], g["stop"])],
"clock_steps": [c for c in timeline["clock_steps"] if overlaps(c["next_start"], c["previous_stop"])],
"call_ins": [c for c in timeline["call_ins"] if call_in_kept(c)],
}
def monitoring_at(timeline: dict, at: datetime.datetime) -> dict:
"""Was the unit monitoring at `at` (its own clock)?
monitoring: inside a session (boundaries included); two sessions matching
(the repeated hour after a clock step back) set ambiguous. unknown: inside
a session's unrecorded end, after its last report, where a call-in file is
missing (records missing), or where no record reaches.
not_monitoring: inside a gap, with what the gap means."""
result = {"status": "unknown", "ambiguous": False, "sessions": [], "gap": None,
"trigger_level": None, "reason": "no record covers this time"}
matches = []
for s in timeline["sessions"]:
start, end = _dt(s["start"]), _dt(s["stop"]) or _dt(s["end_after"])
if start <= at <= end:
matches.append(s)
if matches:
result.update(status="monitoring", ambiguous=len(matches) > 1, sessions=matches,
trigger_level=matches[0]["trigger_level"], reason="inside a monitoring session")
return result
for s in timeline["sessions"]:
if s["stop"] is not None or _dt(s["end_after"]) >= at:
continue
if s["running_at_last_report"]:
result.update(sessions=[s], reason="after the unit's last report")
return result
if s["end_before"] is not None and at < _dt(s["end_before"]):
result.update(sessions=[s], reason="the session's end was not recorded")
return result
for g in timeline["gaps"]:
if _dt(g["start"]) < at < _dt(g["stop"]):
if g["meaning"] == RECORDS_MISSING:
result.update(gap=g, reason="call-in file(s) not received: "
+ ", ".join(f"#{c}" for c in g["missing_files"]))
else:
result.update(status="not_monitoring", gap=g, reason=g["meaning"])
return result
return result
+259 -141
View File
@@ -43,6 +43,7 @@ or:
from __future__ import annotations
import datetime
import json
import logging
import socket
import sys
@@ -50,13 +51,14 @@ 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:
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
from fastapi import Body, FastAPI, File, Form, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import uvicorn
except ImportError:
@@ -71,7 +73,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
@@ -83,9 +85,11 @@ from sfm.live_cache import LiveCache as _LiveCache
from sfm.waveform_store import WaveformStore
from sfm import db_snapshot
from sfm.event_ingest import backfill_series3_event, persist_download
from sfm.mlg_ingest import ingest_mlg
from sfm.mlg_timeline import build_timeline, monitoring_at as mlg_monitoring_at, window as mlg_window
import dataclasses
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
from sfm.device_access.errors import BadRequest
from sfm.device_access.errors import BadRequest, ChangeUnconfirmed
from sfm.device_access.series import normalise_serial, series_for_serial
from sfm.audit import DbAudit
@@ -118,6 +122,20 @@ app.add_middleware(
)
class _PageScripts(StaticFiles):
"""sfm/static/: the web page's JavaScript (no inline JS -- a stack-wide rule,
2026-11-02). `no-cache` makes the browser revalidate on every load, a cheap
304, so a page served by a new SFM never runs an old SFM's cached script."""
async def get_response(self, path, scope):
response = await super().get_response(path, scope)
response.headers["Cache-Control"] = "no-cache"
return response
app.mount("/static", _PageScripts(directory=str(Path(__file__).parent / "static")), name="static")
# ── DB ────────────────────────────────────────────────────────────────────────
# Shared SeismoDb instance. Path can be overridden by --db-path at startup,
# or defaults to bridges/captures/seismo_relay.db relative to the repo root.
@@ -385,9 +403,20 @@ def _via_device_access(fn) -> dict:
def _change_response(fn) -> JSONResponse:
"""Run a start/stop; the ChangeResult is the body, its outcome picks the status.
DeviceError mapping is _via_device_access's -- not repeated here.
DeviceError mapping is _via_device_access's -- not repeated here. A change
that went out, or may have (ChangeUnconfirmed), keeps that status and message
and adds `sent` ("acknowledged" / "unknown") and `audit_id`, so a client can
tell it from a failure that sent nothing without matching the wording
(bench finding #10, 2026-11-02).
"""
body = _via_device_access(fn)
try:
body = _via_device_access(fn)
except HTTPException as exc:
cause = exc.__cause__
if not isinstance(cause, ChangeUnconfirmed):
raise
return JSONResponse(status_code=exc.status_code,
content={"detail": exc.detail, "sent": cause.sent, "audit_id": cause.audit_id})
# An allow-list: only a dry run, a skip, or a change read back as made is a 200.
ok = (body["outcome"] in ("dry_run", "skipped")
or (body["outcome"] == "sent" and body["verified"] == "ok"))
@@ -399,6 +428,8 @@ _SERIAL_AWARE_PATHS = frozenset({
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
"/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",
})
@@ -1025,8 +1056,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 +1073,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,
@@ -1083,145 +1116,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 ───────────────────────────────────────────────────────
@@ -2027,6 +1976,64 @@ def device_monitor_stop(
# ── Call home config endpoints ───────────────────────────────────────────────
@app.get("/device/call_home/state")
def device_call_home_state(
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})"),
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
) -> dict:
"""The unit's call-home switch and dial string, by serial, both series (phase 4).
`enabled` is null when the enable byte is not a value ever measured;
`detail` keeps `byte5` and the whole block as read."""
return _via_device_access(lambda: _device_access().call_home_state(
_unit_address(port, baud, host, tcp_port), serial))
def _set_call_home(enabled: bool, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller):
return _change_response(lambda: _device_access().set_call_home(
_unit_address(port, baud, host, tcp_port), serial, enabled=enabled, dry_run=dry_run,
even_if_already=even_if_already, caller=caller or "api"))
@app.post("/device/call_home/enable")
def device_call_home_enable(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
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: str = Query(..., description=_SERIAL_DOC),
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
even_if_already: bool = Query(False, description="Send even if call-home is already on"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
"""Turn the unit's automatic call-home ON (spec row 9), by serial, both series.
The same audited change as /device/monitor/start: identity read first (a
different unit is a 409, nothing sent), the 0x2C block read, one write that
changes only the enable byte (0x7E + 0x7F), never retried, then read back.
Statuses as /device/monitor/start; a change that went out but was not
confirmed carries `sent` and `audit_id`."""
return _set_call_home(True, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller)
@app.post("/device/call_home/disable")
def device_call_home_disable(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
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: str = Query(..., description=_SERIAL_DOC),
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
even_if_already: bool = Query(False, description="Send even if call-home is already off"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
"""Turn the unit's automatic call-home OFF -- as /device/call_home/enable."""
return _set_call_home(False, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller)
@app.get("/device/call_home")
def device_call_home_get(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
@@ -3063,6 +3070,117 @@ async def db_import_idf_file(
return {"count": len(results), "results": results}
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────────
# Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §5.
# Record and timeline times are the unit's own local clock; file times are UTC.
def _parse_unit_time(value: Optional[str], name: str, *, required: bool = False) -> Optional[datetime.datetime]:
"""A time on the unit's own clock: ISO-8601 with no UTC offset. 400 otherwise."""
if not value:
if required:
raise HTTPException(400, f"{name} is required (ISO-8601, the unit's clock)")
return None
try:
parsed = datetime.datetime.fromisoformat(value)
except ValueError:
raise HTTPException(400, f"{name} is not an ISO-8601 time: {value!r}")
if parsed.tzinfo is not None:
raise HTTPException(400, f"{name} is on the unit's own clock and carries no UTC offset: {value!r}")
return parsed
def _mlg_timeline(serial: str) -> dict:
db = _get_db()
return build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
@app.post("/db/import/mlg_file")
async def db_import_mlg_file(
files: list[UploadFile] = File(...),
serial: Optional[str] = Query(None, description="Serial hint, used only for a file with no serial inside (an empty one)"),
call_in: bool = Query(True, description="False for a cable / direct download: its records are kept, but it is not a call-in"),
mtimes: Optional[str] = Form(None, description='Each file\'s modified time: JSON {"<file name>": <unix seconds, UTC>}'),
) -> dict:
"""
Multipart upload of one or more Blastware .MLG monitor logs.
Each file gets its own status ("ok" / "duplicate" / "error"); good files
are stored even when another in the same request is not. A file that is
not whole, or any of whose records fails its checksum, stores nothing.
The original is kept byte for byte in the waveform store.
"""
try: # all of it checked before any file is stored
raw_times = json.loads(mtimes) if mtimes else {}
if not isinstance(raw_times, dict):
raise ValueError("not an object")
file_times = {name: datetime.datetime.fromtimestamp(float(stamp), datetime.timezone.utc)
for name, stamp in raw_times.items()}
except (ValueError, TypeError, OverflowError, OSError) as exc:
raise HTTPException(400, f"mtimes must be a JSON object of file name -> unix seconds: {exc}")
db, store = _get_db(), _get_store()
results: list[dict] = []
for upload in files:
name = upload.filename or "unnamed.MLG"
try:
data = await upload.read()
except Exception as exc:
results.append({"filename": name, "status": "error", "detail": f"read failed: {exc}"})
continue
results.append(ingest_mlg(db, store, name, data, serial_hint=serial,
file_mtime=file_times.get(name), call_in=call_in))
return {"count": len(results), "results": results}
@app.get("/db/units/{serial}/timeline")
def db_unit_timeline(
serial: str,
from_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
to_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
) -> dict:
"""A unit's monitoring timeline from its .MLGs: sessions (how each ended,
its events, its trigger level), gaps and what each means, clock steps, and
call-ins (delivered / no_file / nothing_new)."""
lo, hi = _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt")
timeline = _mlg_timeline(serial)
if lo or hi:
timeline = mlg_window(timeline, lo, hi)
return {"serial": serial, **timeline}
@app.get("/db/units/{serial}/monitoring_at")
def db_unit_monitoring_at(
serial: str,
at: str = Query(..., description="ISO-8601, the unit's clock"),
) -> dict:
"""Was the unit monitoring at `at`? monitoring / not_monitoring / unknown,
with the session or gap that says so and the trigger level as logged."""
when = _parse_unit_time(at, "at", required=True)
return {"serial": serial, "at": at, **mlg_monitoring_at(_mlg_timeline(serial), when)}
@app.get("/db/mlg_records")
def db_mlg_records(
serial: str = Query(..., description="Unit serial"),
from_dt: Optional[str] = Query(None, description="ISO-8601 start (record start, inclusive)"),
to_dt: Optional[str] = Query(None, description="ISO-8601 end (record start, inclusive)"),
) -> dict:
"""A unit's raw .MLG records, oldest first."""
rows = _get_db().query_mlg_records(
serial, _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt"))
return {"count": len(rows), "records": rows}
@app.get("/db/mlg_files/{file_id}")
def db_mlg_file(file_id: str):
"""The original .MLG, byte for byte, for printing or opening in Blastware."""
row = _get_db().get_mlg_file(file_id)
path = _get_store().root / row["stored_path"] if row and row["stored_path"] else None
if path is None or not path.is_file():
raise HTTPException(404, f"no stored .MLG with id {file_id}")
return FileResponse(path, filename=row["file_name"], media_type="application/octet-stream")
@app.get("/db/units/{serial}/waveforms.zip")
def db_unit_waveforms_zip(
serial: str,
+32 -2442
View File
File diff suppressed because it is too large. Load diff
+271
View File
@@ -0,0 +1,271 @@
/* <device-routing> */
// Every rule that decides where a /device/ request goes, or whether a
// series-specific control is live. Pure functions -- no DOM, no fetch -- so
// tests/test_webapp_device_routing.py runs them in Node (phase 1c, 2026-10-29).
// A control follows the unit's own /device/info answer, never a typed serial
// alone: 0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate.
const SERIES_BY_PREFIX = [['UM', 4], ['BE', 3], ['BA', 3]]; // sfm/device_access/series.py
function normSerial(serial) { return String(serial || '').trim().toUpperCase(); }
function seriesFromSerial(serial) {
const s = normSerial(serial);
for (const [prefix, series] of SERIES_BY_PREFIX) {
if (s.startsWith(prefix) && s.length > prefix.length) return series;
}
return null;
}
function unitQuery(unit) {
const parts = [];
const s = normSerial(unit.serial);
if (s) parts.push(`serial=${encodeURIComponent(s)}`);
parts.push(`host=${encodeURIComponent(unit.host || '')}`);
parts.push(`tcp_port=${encodeURIComponent(unit.tcpPort)}`);
return parts.join('&');
}
// action -> [method, path, needs a serial (no legacy equivalent)]
const DEVICE_ROUTES = {
info: ['GET', '/device/info', false],
status: ['GET', '/device/monitor/status', false],
settings: ['GET', '/device/settings', true],
events: ['GET', '/device/events', false],
download: ['POST', '/device/events/download', true],
start: ['POST', '/device/monitor/start', false],
stop: ['POST', '/device/monitor/stop', false],
hangup: ['POST', '/device/hangup', true],
storage_range: ['GET', '/device/events/storage_range', false],
index: ['GET', '/device/events/index', false],
erase: ['POST', '/device/events/erase', false],
rescue: ['POST', '/device/rescue', false],
blind_stop: ['POST', '/device/stop_monitoring_blind', false],
slow_drip: ['POST', '/device/stop_monitoring_slow_drip', false],
call_home_read: ['GET', '/device/call_home', false],
call_home_write: ['POST', '/device/call_home', false],
call_home_state: ['GET', '/device/call_home/state', true],
call_home_on: ['POST', '/device/call_home/enable', true],
call_home_off: ['POST', '/device/call_home/disable', true],
settings_change: ['POST', '/device/settings/change', true],
event_waveform: ['GET', '/device/event/{index}/waveform', false],
event_file: ['GET', '/device/event/{index}/blastware_file', false],
};
function deviceUrl(action, unit, params = {}) {
const route = DEVICE_ROUTES[action];
if (!route) throw new Error(`unknown device action: ${action}`);
const [method, template, needsSerial] = route;
if (needsSerial && !normSerial(unit.serial)) return null;
const rest = { ...params };
let path = template;
if (path.includes('{index}')) { // the legacy per-event routes
if (rest.index === undefined) throw new Error(`${action} needs params.index`);
path = path.replace('{index}', encodeURIComponent(rest.index));
delete rest.index;
}
// Hang-up releases whatever line is held at the address: no serial.
let query = action === 'hangup' ? unitQuery({ ...unit, serial: '' }) : unitQuery(unit);
for (const [k, v] of Object.entries(rest)) query += `&${k}=${encodeURIComponent(v)}`;
return { method, path: `${path}?${query}` };
}
function confirmedSeries(unit) {
const c = unit.confirmed;
if (!c) return null;
const typed = normSerial(unit.serial);
if (!typed) return c.series; // a legacy identify, no serial typed
return typed === normSerial(c.serial) ? c.series : null;
}
function controlsFor(unit) {
const series = confirmedSeries(unit);
const serialMode = Boolean(normSerial(unit.serial));
return {
startStop: serialMode && (series === 3 || series === 4),
hangup: series === 4,
diagnostics: series === 3,
// by host, the legacy read is Series 3's; by serial, both series (phase 4)
callHomeRead: series === 3 || (serialMode && series === 4),
callHomeChange: serialMode && (series === 3 || series === 4),
configWrite: serialMode && (series === 3 || series === 4),
callHomeWrite: false,
reasons: { configWrite: 'By serial only: Preview, then Send (audited).',
callHomeWrite: 'By serial: use Call-home On / Off (audited). Other call-home fields wait for the THOR round.' },
};
}
function changeSummary(body) {
const id8 = String(body.audit_id || '').slice(0, 8);
if (body.outcome === 'dry_run') {
const subs = ((body.plan || {}).steps || []).map(s => s.sub).join(', ');
return `${body.action}: dry run — would send ${subs}`;
}
if (body.action === 'change settings') { // phase 5: the state is a read-back verdict
if (body.outcome === 'skipped') return 'change settings: the unit already holds these — nothing sent';
if (body.outcome === 'sent' && body.verified === 'ok') {
return `change settings: confirmed — the unit holds what was sent (audit ${id8})`;
}
if (body.verified === 'mismatch') {
return `change settings: sent, but the unit reads ${body.state_after} — see what it holds (audit ${id8})`;
}
}
if (body.outcome === 'skipped') return `${body.action}: already ${body.state_before} — nothing sent`;
if (body.outcome === 'sent' && body.verified === 'ok') {
return `${body.action}: confirmed — ${body.state_before} → ${body.state_after} (audit ${id8})`;
}
return `${body.action}: ${body.outcome}, ${body.verified} (audit ${id8})`;
}
// What a chip and the peaks bar show for an event, from either shape: the
// shared EventRef (serial mode) or the legacy event (host/port mode).
function eventView(ev) {
const label = typeof ev.timestamp === 'string' ? ev.timestamp.replace('T', ' ')
: (ev.timestamp && ev.timestamp.display) || `Event ${ev.index}`;
let peaks = null;
if (ev.peaks_ips || ev.peak_vector_sum_ips != null) {
const p = ev.peaks_ips || {};
peaks = { tran: p.tran ?? null, vert: p.vert ?? null, long: p.long ?? null,
pvs: ev.peak_vector_sum_ips ?? null, micPsi: null };
} else if (ev.peak_values) {
const pv = ev.peak_values;
peaks = { tran: pv.tran_in_s ?? null, vert: pv.vert_in_s ?? null, long: pv.long_in_s ?? null,
pvs: pv.peak_vector_sum ?? null, micPsi: pv.micl_psi ?? null };
}
return { label, title: ev.record_type || '', peaks };
}
// What the Config tab's serial-mode Read shows for a UnitSettings reply.
function settingsRows(st) {
const dash = v => (v == null || v === '' ? '—' : v);
const hi = st.histogram_interval_s;
const rows = [
['Setup Name', dash(st.setup_name)],
['Record Mode', dash(st.record_mode)],
['Sample Rate', st.sample_rate != null ? `${st.sample_rate} sps` : '—'],
['Record Time', st.record_time_s != null ? `${st.record_time_s.toFixed(2)} s` : '—'],
['Histogram Interval', hi == null ? '—' : hi < 60 ? `${hi} s` : `${hi / 60} min`],
['Geo Trigger', st.geo_trigger_ips != null ? `${st.geo_trigger_ips.toFixed(4)} in/s` : '—'],
];
const notes = Object.entries(st.notes || {});
if (!notes.length) rows.push(['Notes', '—']);
for (const [k, v] of notes) rows.push([`Note: ${k}`, dash(v)]);
return rows;
}
// The legacy per-index routes (Load / Save / Download, prev/next, the arrow
// keys) address events by position on the MiniMate path: live only for a list
// loaded without a serial that has events.
function perIndexLive({ bySerial, count }) { return !bySerial && count > 0; }
// A unit's own string (setup name, project, an error naming a serial) placed
// into markup must stay text.
function escapeHtml(v) {
return String(v ?? '').replace(/[&<>"']/g,
c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function downloadSummary(body) {
if (body.inserted === false) return `already stored — ${body.stored_filename}`;
return `stored ${body.stored_filename}, ${body.filesize} bytes, check: ${(body.detail || {}).check}`;
}
// A Micromate's version string lives in 0x01, undecoded; which firmware line it
// runs comes free with every reply (bench finding #12).
const FIRMWARE_LINES = { thor: 'Thor line (version not read)', blastware: 'Blastware line (version not read)' };
function firmwareLabel(info) {
const i = info || {};
return i.firmware_version || i.firmware || FIRMWARE_LINES[(i.detail || {}).firmware_line] || '—';
}
// A failed device request's message. A 504 is a unit that took the connection
// but never answered: while THOR polls a Micromate, SFM's connection is accepted
// and gets 0 bytes (measured 2026-10-29, bench finding #16). The hint is left
// off once a change was sent -- its own message says what happened.
const NO_REPLY_HINT = 'the connection opened, so the modem is reachable — another program (THOR or '
+ "Blastware) may be holding this unit's line, or the unit is busy (e.g. its sensor check)";
function errorDetail(body, statusText) {
const b = body || {}, d = b.detail;
return b.outcome ? changeSummary(b) : typeof d === 'string' ? d : d ? (d.message || JSON.stringify(d)) : statusText;
}
function deviceErrorText(status, body, unit, statusText) {
const text = errorDetail(body, statusText);
return status === 504 && !(body || {}).sent && unit && unit.host ? `${text} — ${NO_REPLY_HINT}` : text;
}
// A change that went out (or may have) is not "failed": its body carries `sent`
// (ChangeUnconfirmed, bench finding #10), and its message says what the unit
// did and names the audit record. `label` is the whole name: "Start monitoring",
// "Enable call-home".
function changeErrorText(label, status, body, unit, statusText) {
if ((body || {}).sent) return `${label} not confirmed: ${errorDetail(body, statusText)}`;
return `${label} failed: ${deviceErrorText(status, body, unit, statusText)}`;
}
// By serial, settings are read-only until phase 5: no empty legacy edit form or
// legacy tables, and the settings box shows from the start (#6, #12).
function serialPanes(bySerial, settingsRead) {
return { configForm: !bySerial, settingsBox: bySerial, settingsPlaceholder: bySerial && !settingsRead,
legacyDeviceTables: !bySerial, callHomeForm: !bySerial, callHomeBox: bySerial };
}
// A unit's call-home switch, read by serial (phase 4). `enabled` null is an
// enable byte never measured -- shown with the byte, never as On or Off.
function callHomeRows(state) {
const s = state || {};
const d = s.detail || {};
const sw = s.enabled === true ? 'On' : s.enabled === false ? 'Off'
: d.reason || `Unknown (byte 5 = ${d.byte5 ?? '?'})`;
return [['Call-home', sw], ['Dial string', s.dial_string || '—'], ['Series', s.series]];
}
// ── The Config tab's edit form, by serial (phase 5) ──────────────────────────
// The fields the server says this unit can change, in its order, with their
// limits (UnitSettings.detail.editable).
function settingsFormFields(st) {
return (((st || {}).detail || {}).editable || []).map(f => ({ ...f }));
}
// Only what the operator changed, typed as the server expects. Numbers compare
// as numbers (0.30 is 0.3); a number that does not parse is left out (the
// preview shows exactly what would change); read-only fields never count.
function settingsChanges(fields, edited) {
const out = {};
const e = edited || {};
for (const f of fields || []) {
if (f.readonly || !(f.field in e)) continue;
let v = e[f.field];
if (f.kind === 'number' || (f.kind === 'choice' && typeof f.value === 'number')) {
if (v === '' || v == null) continue;
v = Number(v);
if (!Number.isFinite(v) || v === Number(f.value)) continue;
} else if (f.kind === 'bool') {
v = Boolean(v);
if (v === Boolean(f.value)) continue;
} else {
v = String(v);
if (v === String(f.value == null ? '' : f.value)) continue;
}
out[f.field] = v;
}
return out;
}
const _dash = v => (v == null || v === '' ? '—' : v);
// A preview (dry run): one row per field, [label, the unit holds, it would get].
function settingsPreviewRows(body) {
return Object.values(((body || {}).plan || {}).fields || {}).map(r => [r.label, _dash(r.old), _dash(r.new)]);
}
// Why a preview would not be sent ('' when nothing blocks it).
function settingsBlockedText(body) {
return (((body || {}).plan || {}).blocked || []).join('; ');
}
// After a send: [label, the unit held, SFM sent, the unit now holds].
function settingsResultRows(body) {
const fields = ((((body || {}).detail || {}).snapshot || {}).fields) || {};
return Object.values(fields).map(r => [r.label, _dash(r.old), _dash(r.new), _dash(r.now)]);
}
/* </device-routing> */
File diff suppressed because it is too large. Load diff
+78 -47
View File
@@ -30,6 +30,7 @@ Roles:
from __future__ import annotations
import datetime
import hashlib
import logging
import pickle
import re
@@ -38,7 +39,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
@@ -46,7 +47,19 @@ from sfm.shape_metrics import shape_from_h5, offset_from_h5
log = logging.getLogger("sfm.waveform_store")
A5_PICKLE_VERSION = 1
# 2 (2026-11-06, #58): frames as the parser gives them since an escaped checksum
# stopped leaving its 0x10 in `data`. A version-1 frame with a checksum of 02, 03
# or 04 still ends in that 0x10; load_a5 drops it (_frame_from_v1).
A5_PICKLE_VERSION = 2
def _frame_from_v1(f: S3Frame) -> S3Frame:
"""A frame pickled before #58, as the parser reads its reply now. Its 02/03/04
checksum arrived as `10 X` (every recorded one did), and the 10 ended `data`."""
if f.chk_byte in (0x02, 0x03, 0x04) and f.data[-1:] == b"\x10":
return S3Frame(sub=f.sub, page_hi=f.page_hi, page_lo=f.page_lo, data=f.data[:-1],
checksum_valid=f.checksum_valid, chk_byte=f.chk_byte)
return f
def _frame_to_dict(f: S3Frame) -> dict:
@@ -75,7 +88,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.
@@ -93,6 +106,25 @@ class WaveformStore:
d.mkdir(parents=True, exist_ok=True)
return d
def save_mlg(self, serial: Optional[str], file_name: str, data: bytes) -> str:
"""Keep an original .MLG byte for byte, at <serial or _unresolved>/mlg/<file_name>.
Blastware reuses some names (a cable download is always <serial>.MLG), so
a name already holding different bytes gets the hash in its name instead.
Returns the path relative to the store root. Raises ValueError for a
serial that is not plain letters and digits (it becomes a directory)."""
if serial is not None and not re.fullmatch(r"[A-Za-z0-9]{1,16}", serial):
raise ValueError(f"not a plain serial: {serial!r}")
d = self.root / (serial or "_unresolved") / "mlg"
d.mkdir(parents=True, exist_ok=True)
path = d / Path(file_name).name
if path.exists() and path.read_bytes() != data:
digest = hashlib.sha256(data).hexdigest()[:8]
path = d / f"{path.stem}.{digest}{path.suffix}"
if not path.exists():
path.write_bytes(data)
return path.relative_to(self.root).as_posix()
def paths_for(self, serial: str, filename: str) -> tuple[Path, Path]:
"""Return (blastware_path, a5_pickle_path) for a given serial+filename.
@@ -184,7 +216,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 +228,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)
@@ -296,6 +329,8 @@ class WaveformStore:
*,
serial_hint: Optional[str] = None,
bw_report_text: Optional[Union[str, bytes]] = None,
source_kind: str = "bw-import",
geo_range: Optional[Union[str, int]] = None,
) -> tuple[Event, dict]:
"""
Ingest a Blastware event file produced by an external tool
@@ -315,7 +350,8 @@ class WaveformStore:
3. Resolve serial from BW filename (`<P><serial3>...`) or use
serial_hint. Falls back to "UNKNOWN".
4. Copy the BW bytes verbatim into <root>/<serial>/<filename>.
5. Write the .sfm.json sidecar with source.kind = "bw-import"
5. Write the .sfm.json sidecar with source.kind = `source_kind`
("bw-import"; "sfm-live" for SFM's own downloads)
and a5_pickle_filename = None. Does NOT write a .a5.pkl
(no A5 source available; byte-for-byte regeneration not
possible — the on-disk BW file IS the byte-for-byte source).
@@ -323,29 +359,9 @@ class WaveformStore:
Returns (event, record_dict) so callers can both insert into
SeismoDb and surface the parsed Event.
"""
# Stash the bytes to a temp path so read_blastware_file (path-based)
# can parse without us duplicating its logic.
import tempfile
with tempfile.NamedTemporaryFile(suffix=".bw", delete=False) as tmp:
tmp.write(bw_bytes)
tmp_path = Path(tmp.name)
try:
ev = event_file_io.read_blastware_file(tmp_path)
finally:
try:
tmp_path.unlink()
except FileNotFoundError:
pass
# read_blastware_file derives record_type from its path arg, but
# that arg is the tmp file (suffix ".bw") — so override with the
# original filename's encoded type (H/W/M/E/C in the BW AB0T
# scheme). Without this override every BW-imported event lands
# in the DB with record_type="Waveform" regardless of the actual
# type (Histogram, Manual, etc.).
ev.record_type = event_file_io.derive_record_type_from_filename(
source_path.name
)
# Decode the bytes directly; the name only labels the record type and
# cross-checks the decoded time (event_file_io.decode_blastware_bytes).
ev = event_file_io.decode_blastware_bytes(bw_bytes, name=source_path.name)
# Parse the BW ASCII report if one was supplied. Failures here
# are non-fatal: we still write the binary + sidecar without the
@@ -361,14 +377,15 @@ class WaveformStore:
exc,
)
# If we have a report, overlay its device-authoritative fields
# (peaks, project, sample_rate, record_time) onto the Event
# BEFORE handing it to db.insert_events(). Without this overlay
# the DB row gets `peak_values` from _peaks_from_samples(), which
# runs the still-undecoded waveform codec on the BW body and
# produces ±10 in/s saturation values on every channel for every
# event. The sidecar JSON had the correct values via
# event_to_sidecar_dict(bw_report=...) but the DB columns didn't.
# If we have a report, overlay its fields (peaks, project,
# sample_rate, record_time) onto the Event BEFORE handing it to
# db.insert_events(). The file decode reads these itself now (the
# decode checker compares it with Blastware's XML reports, DL2's
# 70,042 events); the overlay stays because production keeps a
# paired Blastware report as the record until the file-only decode
# has no blanks. The sidecar's `bw_report` block keeps the report's
# own values either way. (The old reason -- an undecoded codec
# giving ±10 in/s -- has not held since the 2026-08 codec fixes.)
if bw_report is not None:
try:
event_file_io.apply_report_to_event(ev, bw_report)
@@ -433,7 +450,10 @@ class WaveformStore:
event_hdf5.write_event_hdf5(
hdf5_path, ev,
serial=serial,
geo_range="normal", # BW file doesn't carry the range; assume Normal
# None (an import): the event's own range, read from the file's
# setup (ev.geo_range), else Normal. An explicit value -- a live
# download's (event_ingest) -- wins.
geo_range=geo_range,
source_kind="bw-import",
)
hdf5_filename = hdf5_path.name
@@ -458,7 +478,7 @@ class WaveformStore:
blastware_filename=filename,
blastware_filesize=filesize,
blastware_sha256=sha256,
source_kind="bw-import",
source_kind=source_kind, # "sfm-live" for SFM's own downloads (event_ingest)
a5_pickle_filename=None,
txt_filename=txt_filename,
review=existing_review,
@@ -587,6 +607,13 @@ class WaveformStore:
report_dict["sample_rate"] = binary_md.sample_rate
if binary_md.record_time_sec and not report_dict.get("record_time_sec"):
report_dict["record_time_sec"] = binary_md.record_time_sec
# The pre-trigger and notes, from the file's own settings record
# and note block (#44, #45; 2,027 / 2,027 against Thor's reports).
if binary_md.pre_trigger_sec is not None and report_dict.get("pre_trigger_sec") is None:
report_dict["pre_trigger_sec"] = binary_md.pre_trigger_sec
for key in ("project", "client", "operator", "notes"):
if getattr(binary_md, key) and not report_dict.get(key):
report_dict[key] = getattr(binary_md, key)
# Calibration date (binary) vs calibration text (.txt) cohabit
# under different keys; no overwrite needed.
if binary_md.event_datetime and not report_dict.get("event_type"):
@@ -653,11 +680,9 @@ class WaveformStore:
# caveats of this bridge (mic units, missing fields → sidecar).
ev = idf_event.to_minimateplus_event(waveform_key)
# Attach the decoded sample arrays. Thor's decoder counts use
# LSB = 0.0003 in/s for geo (vs BW's 16-count units at 0.005 in/s)
# — the .h5 writer's geo_range="normal" yields LSB = 10/32768
# ≈ 0.000305 in/s, so plotted samples come out ~1.7% high.
# Acceptable known offset; refine with a Thor-aware h5 path later.
# Attach the decoded sample arrays. These are raw Thor counts at
# _GEO_LSB_IPS = 0.000310308 in/s, not the MiniMate's 10/32000;
# the .h5 write below passes that scale explicitly (issue #42).
if idf_samples is not None:
ev.raw_samples = idf_samples
n_samples = max((len(idf_samples.get(ch, [])) for ch in ("Tran", "Vert", "Long", "MicL")), default=0)
@@ -673,7 +698,7 @@ class WaveformStore:
# a 1-sample-per-interval array so the existing h5+renderer pipeline
# (which groups samples down to ``n_intervals`` bars via max-per-group)
# produces a non-blank histogram chart. Each "sample" is the peak ADC
# count for that interval, so the h5 writer's ``count × geo_fs/32768``
# count for that interval, so the h5 writer's ``count × _GEO_LSB_IPS``
# conversion yields the right physical value for the bar height.
if is_histogram and idf_intervals:
hist_samples = {
@@ -692,11 +717,13 @@ class WaveformStore:
if ev.raw_samples:
hdf5_path = self.hdf5_path_for(serial, filename)
try:
from micromate.idf_file import _GEO_LSB_IPS
event_hdf5.write_event_hdf5(
hdf5_path, ev,
serial=serial,
geo_range="normal", # Thor's geo full scale is also 10 in/s (Normal)
source_kind="idf-import",
geo_ips_per_count=_GEO_LSB_IPS,
)
hdf5_filename = hdf5_path.name
except Exception as exc:
@@ -813,7 +840,8 @@ class WaveformStore:
def load_a5(self, serial: str, filename: str) -> Optional[list[S3Frame]]:
"""
Re-hydrate the pickled A5 frame stream for a stored event.
Re-hydrate the pickled A5 frame stream for a stored event, as the parser
reads it now (a version-1 pickle's frames are converted).
Returns None if the sidecar is missing.
"""
_, a5_path = self.paths_for(serial, filename)
@@ -824,7 +852,10 @@ class WaveformStore:
if not isinstance(payload, dict) or "frames" not in payload:
log.warning("WaveformStore.load_a5: malformed sidecar at %s", a5_path)
return None
return [_dict_to_frame(d) for d in payload["frames"]]
frames = [_dict_to_frame(d) for d in payload["frames"]]
if payload.get("version", 1) < 2:
frames = [_frame_from_v1(f) for f in frames]
return frames
# ── modern .sfm.json sidecar accessors ──────────────────────────────────────
+187 -6
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import copy
import datetime
import json
from pathlib import Path
from micromate.models import MicromateDeviceInfo, MicromateEventRef, MicromateState
@@ -16,6 +17,79 @@ from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStat
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
PUSH_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-writes" / "setup-push-overwrite-test1.json"
def s4_push_reads() -> dict:
"""UM12947's reads (content, by SUB) just before THOR's setup push: 0x08 prefs,
0x2E trigger, 0x1A setup, 0x41 active name."""
import json
ex = json.loads(PUSH_FIXTURE.read_text())["exchanges"]
start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA)
return {e["sub"]: bytes.fromhex(e["response_data"])[11:] for e in ex[:start]}
_S3_BLOCKS = None
def s3_settings_blocks() -> dict:
"""BE9441's four settings blocks on 2026-10-26, as SFM's reads return them:
the 1A read Blastware took right after its second write (assembled, 2,090 B),
and the event index / trigger / waveform blocks that write sent back (each a
write is the read plus two bytes)."""
global _S3_BLOCKS
if _S3_BLOCKS is None:
from minimateplus.framing import S3FrameParser
from minimateplus.protocol import assemble_compliance_content
from test_minimate_write_frames import WRITES, _payload
fix = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
reads, cur = [], None
for f in S3FrameParser().feed((fix / "unit_replies.bin").read_bytes()):
if f.sub != 0xE5:
continue
if len(f.data) == 11:
cur = []
reads.append(cur)
else:
cur.append(bytes(f.data))
sent = {_payload(f)[2]: _payload(f)[16:] for f in WRITES[13:26]}
_S3_BLOCKS = {"event_index": sent[0x68][:-2], "compliance": assemble_compliance_content(reads[2]),
"trigger": sent[0x82][:-2], "waveform": sent[0x69][:-2]}
return dict(_S3_BLOCKS)
def s3_device_info_answer(serial: bytes = b"BE9441") -> bytes:
"""What a MONITORING MiniMate returns for a 1A read, assembled: its device-info
block (BE9441 10-26: reads 3-7 start 0e 'BE9441'), 2,090 bytes."""
return (b"\x0e" + serial).ljust(2090, b"\x00")
def schedule_record(time_slot: int, action: int, setup: str = "") -> bytes:
"""One 260-byte schedule.dat record (micromate.schedule's layout)."""
rec = bytearray(260)
rec[4], rec[5], rec[6], rec[7] = time_slot, 3, action, len(setup)
rec[8:8 + len(setup)] = setup.encode("ascii")
return bytes(rec)
THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
def s3_call_home_raw(byte5: int = 0x01) -> bytes:
"""A MiniMate's 0x2C reply payload as S3FrameParser returns it (125 B, the
num_retries 3 kept as 10 03), laid out as the 4-20-26 captures measured
(BE11529): header 00 7C DC, [5] the enable, [6:46] the dial string."""
raw = b"\x00\x7c\xdc\x00\x00" + bytes([byte5]) + b"RADIO RING".ljust(40, b"\x00")
raw += bytes(117 - len(raw)) + b"\x10\x03"
return raw + bytes(125 - len(raw))
def um12947_call_home(enabled: bool = True) -> bytes:
"""UM12947's own 126-byte call-home content, as THOR read it (0x05 on, 0x04 off)."""
ex = json.loads((THOR_WRITES / "call-home-enable-disable.json").read_text())["exchanges"]
reads = [bytes.fromhex(e["response_data"])[11:] for e in ex if e["sub"] == 0x2C]
return next(r for r in reads if r[5] == (0x05 if enabled else 0x04))
from minimateplus.protocol import TimeoutError as mmp_TimeoutError # noqa: E402
class _Base:
@@ -75,9 +149,23 @@ def default_s3_events():
class FakeMiniMateClient(_Base):
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
monitor_states=None, write_error=None, **kw):
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None,
bare_requests_ignored=False, call_home_raw=None, settings_blocks=None,
monitoring_settings=False, **kw):
super().__init__(**kw)
self.serial = serial
self.settings_blocks = s3_settings_blocks() if settings_blocks is None else dict(settings_blocks)
self.monitoring_settings = monitoring_settings
self.pushed = None
# As a monitoring MiniMate (measured 2026-04-08): on a fresh connection a
# read before SESSION_RESET + POLL goes unanswered. Off unless a test asks.
self.bare_requests_ignored = bare_requests_ignored
self._woken = False
self.call_home_raw = s3_call_home_raw() if call_home_raw is None else call_home_raw
# read_serial()'s answer (connect() keeps answering `serial`), and errors
# raised by wake() once a write has gone out -- the read-back's wakes.
self.serial_reported = serial if serial_reported is None else serial_reported
self.wake_errors = list(wake_errors or [])
self.monitoring = monitoring
self.monitor_states = list(monitor_states) if monitor_states else [monitoring]
self.write_error = write_error
@@ -94,8 +182,18 @@ class FakeMiniMateClient(_Base):
self.download_requests: list = [] # (key4, expected_timestamp) per download
self.last_download = None
def open(self):
super().open()
self._woken = False
def _bare_read(self, name):
self._step(name)
if self.bare_requests_ignored and not self._woken:
raise mmp_TimeoutError(f"{name}: no reply (the unit was not woken)")
def connect(self) -> DeviceInfo:
self._step("connect")
self._woken = True # connect() starts with the startup handshake
return DeviceInfo(
serial=self.serial, firmware_minor=17, firmware_version="S338.17",
dsp_version="10.72", manufacturer="Instantel", model="MiniMate Plus",
@@ -104,12 +202,45 @@ class FakeMiniMateClient(_Base):
def poll(self) -> None:
self._step("poll")
self._woken = True
def wake(self, **kw) -> None:
self._step("wake")
if self.writes and self.wake_errors:
raise self.wake_errors.pop(0)
self._woken = True
def read_serial(self) -> str:
self._bare_read("read_serial")
return self.serial_reported
def read_call_home_raw(self) -> bytes:
self._bare_read("read_call_home_raw")
return self.call_home_raw
def write_call_home_image(self, image: bytes) -> None:
self._write("call_home")
self.call_home_raw = bytes(image) # read back as the unit would store it
def read_compliance_content(self) -> bytes:
self._bare_read("read_compliance_content")
return s3_device_info_answer() if self.monitoring_settings else self.settings_blocks["compliance"]
def read_settings_blocks(self) -> dict:
self._bare_read("read_settings_blocks")
blocks = dict(self.settings_blocks)
if self.monitoring_settings:
blocks["compliance"] = s3_device_info_answer()
return blocks
def push_config_raw(self, event_index, compliance, trigger, waveform, *, escaped=False) -> None:
self.pushed_escaped = escaped
self.pushed = (bytes(event_index), bytes(compliance), bytes(trigger), bytes(waveform))
self._write("push_config_raw")
self.settings_blocks["compliance"] = bytes(compliance)[:2090] # read back as the unit stores it
def get_monitor_status(self) -> MonitorStatus:
self._step("get_monitor_status")
self._bare_read("get_monitor_status")
state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0]
# A bool is a measured state; an int (or None: a short section) is the raw 0x1C flag byte.
flag = (0x10 if state else 0x00) if isinstance(state, bool) else state
@@ -151,8 +282,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
@@ -207,15 +338,39 @@ class _FakeProtocol:
self._owner.executed.append(plan)
if self._owner.execute_error is not None:
raise self._owner.execute_error
for st in plan.steps:
if st.sub == 0x7E: # the unit stores the block and moves [118:120] itself
old = self._owner.call_home
self._owner.call_home = bytes(st.data[:118]) + bytes(~b & 0xFF for b in old[118:120]) \
+ bytes(st.data[120:])
if st.sub == 0x71: # the unit stores the setup and computes its own CRC
from micromate.setup_block import with_crc
old = self._owner.setup
self._owner.setup = with_crc(old[:3] + bytes(st.data[3:2090]) + old[2090:2092])
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
def read_call_home_config(self):
self._owner._step("read_call_home_config")
return bytes(11) + self._owner.call_home
class FakeMicromateClient(_Base):
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
unsolicited=b"", event_refs=None, run_states=None,
serial_reported=None, execute_error=None, **kw):
serial_reported=None, execute_error=None, call_home=None, setup=None,
prefs=None, trigger=None, active_name=None, schedule_body=None,
schedule_error=None, **kw):
super().__init__(**kw)
self.unit_serial = serial # not `serial`: that is the client's method
self.call_home = um12947_call_home() if call_home is None else call_home
push = s4_push_reads()
self.setup = SETUP_FIXTURE.read_bytes()[11:] if setup is None else setup
self.prefs = push[0x08] if prefs is None else prefs
self.trigger = push[0x2E] if trigger is None else trigger
self.active_name = (push[0x41].split(b"\x00")[0].decode("ascii")
if active_name is None else active_name)
self.schedule_body = bytes(524) if schedule_body is None else schedule_body
self.schedule_error = schedule_error
self.run_states = list(run_states) if run_states else [0x00]
self.serial_reported = serial if serial_reported is None else serial_reported
self.execute_error = execute_error
@@ -242,6 +397,10 @@ class FakeMicromateClient(_Base):
self._step("serial")
return self.serial_reported if refresh else self.unit_serial
def get_call_home_content(self) -> bytes:
self._step("get_call_home_content")
return self.call_home
def read_run_state(self):
from micromate.models import MicromateRunState
self._step("read_run_state")
@@ -263,7 +422,29 @@ class FakeMicromateClient(_Base):
def get_setup(self):
self._step("get_setup")
return decode_setup(SETUP_FIXTURE.read_bytes()[11:])
return decode_setup(self.setup)
def get_setup_content(self) -> bytes:
self._step("get_setup_content")
return self.setup
def get_prefs_content(self) -> bytes:
self._step("get_prefs_content")
return self.prefs
def get_trigger_content(self) -> bytes:
self._step("get_trigger_content")
return self.trigger
def get_active_setup_raw(self) -> str:
self._step("get_active_setup_raw")
return self.active_name
def read_schedule(self) -> bytes:
self._step("read_schedule")
if self.schedule_error is not None:
raise self.schedule_error
return self.schedule_body
def read_unsolicited(self) -> bytes:
self._step("read_unsolicited")
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 348 files, more files were not shown because too many files have changed in this diff. Show more