29 Commits
Author SHA1 Message Date
serversdown e9c01ce8d4 Merge pull request 'Release v0.32.0 — event times you can trust, and Series 4 mapped' (#54) from dev into main
Reviewed-on: #54
2026-10-27 11:00:59 -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
serversdown d2258dad4e Merge pull request 'Release v0.31.0 — report parity + the inverted rescue (0.29.0 → 0.31.0)' (#40) from dev into main
Reviewed-on: #40
2026-09-18 16:46:41 -04:00
serversdown e050e602c2 Merge pull request 'Release v0.29.0 — offset detector + false_trigger_reason + BlastMate serials (0.27.0→0.29.0)' (#36) from dev into main
Reviewed-on: #36
2026-09-07 15:57:37 -04:00
serversdown fc1c7c7936 Merge pull request 'Docs/claude.md corrections' (#35) from dev into main
Reviewed-on: #35
2026-08-29 15:48:33 -04:00
serversdown 7d0d12079b Merge pull request 'v0.27.0 Decoder fixes, offset exploration and testing.' (#34) from dev into main
Reviewed-on: #34
2026-08-28 22:40:34 -04:00
serversdown 5203aab849 Merge pull request 'update to 0.26.0. Big chonking update including 0.23, 0.24, and 0.25 as well.' (#33) from dev into main
Reviewed-on: #33
2026-08-27 13:43:00 -04:00
serversdown 5b65718b72 Merge pull request 'v0.23.0 - ZC freq in events store' (#31) from dev into main
Reviewed-on: #31
2026-08-06 12:12:19 -04:00
serversdown 483762607e Merge pull request 'Update to v0.22.0' (#30) from dev into main
Reviewed-on: #30
2026-07-03 15:35:20 -04:00
serversdown d0b66368d5 Merge pull request 'update to v0.21.1, thor data import successful' (#29) from dev into main
Reviewed-on: #29
2026-06-01 16:54:23 -04:00
serversdown 2eb1d25028 Merge pull request 'v0.20.0 -- Full s3 event parse and PDF creation.' (#28) from dev into main
Reviewed-on: #28
2026-05-28 17:54:31 -04:00
claude cc821f9ee3 hotfix: fix dockerfile on main to fix import bug on prod 2026-05-21 20:42:15 +00:00
128 changed files with 2766 additions and 23370 deletions

No files matched your search

+169 -5
View File
@@ -4,7 +4,31 @@ All notable changes to seismo-relay are documented here.
---
## Unreleased
## v0.32.0 — 2026-10-27
**Event times you can trust, and Series 4 mapped end to end.** Two threads.
The first is correctness on stored data. Series-3 waveforms were stamped with
the monitoring-session start, hours off; they now carry the instrument's own
trigger time, read from the event record the unit sends inside its 5A stream,
which matches Blastware's reports on every one of 1,320 report-paired
waveforms -- no filename needed. Getting the correction into prod safely
needed three more fixes found on the way: re-storing an event at its corrected
time duplicated it, prod's ISO-dated reports were never read, and the binary's
own estimate is a second off often enough to land waveforms on their histogram
twins. Sub-minute histograms recorded with the mic off now decode, and mic-on
ones are read right (#47, #49). Micromate `.h5` samples are on Thor's own
scale (#42). The deploy was rehearsed on prod's own (snapshot) store before
release: every waveform on Blastware's exact time, every row id kept.
The second is Series IV. The Micromate live wire protocol is reverse-engineered
end to end (`docs/micromate_protocol_reference.md`), with a read-only live
client in `micromate/`, the call-home session captured, and a Micromate's setup
decoded. None of it is on a shipped code path yet -- SFM's Series-4 device
work lands with the parity branch. The SFM webapp gains a Diagnostics tab.
⚠ **This release owes prod a backfill, and moves stored event times** -- see
*Migration* below.
### Fixed
@@ -21,6 +45,11 @@ All notable changes to seismo-relay are documented here.
Histograms keep `ts1` (the ~24 h window start). A paired report's
`event_datetime` stays authoritative (unit-clock drift).
⚠ **Needs a re-decode backfill** to correct existing stored events' timestamps.
⚠ **As released, the time comes from the instrument's embedded event record**
(entry below):
`ts2 - record time` turned out a second off on 260 of prod's 1,394 waveforms,
and the backfill this needs duplicated every corrected event until the
restamp fix below. See *Migration*.
- **`scratch/mm_frame_parse.py` accepted either checksum rule, so it could not
@@ -78,6 +107,106 @@ All notable changes to seismo-relay are documented here.
- **`mm_client_check.py` carried two stale labels.** It still printed `0x06`
content[4:8] as "unexplained" (it is very likely the monitor-log count -- see
*Changed*) and announced UM20147 as "the FIRST 11.0BD unit this code has met".
- **Micromate `.h5` samples used the MiniMate's count scale (#42).** Every
idf-import `.h5` converted Thor's raw geo counts with `full_scale /
_GEO_INT16_FS`, the MiniMate body codec's count. A Thor count is
`_GEO_LSB_IPS` = 0.000310308 in/s, so the samples disagreed with the event's
own peak by a constant: **−1.65%** while that divisor was 32768 (before
2026-08-25) and **+0.71%** after it became 32000. v0.30.0's LSB fix corrected
the decoder's *peaks*, and those were right everywhere (DB, sidecar, h5
`peak_*_ips`, PDF numbers). It never reached the sample arrays, which go
through the shared writer. Off-scale: waveform and histogram charts, FFT
magnitudes, and the offset detector's 0.025 in/s floor. Crest factor and ZC
frequency are scale-free. `write_event_hdf5` now takes `geo_ips_per_count`.
`save_imported_idf` and `backfill_thor_events.py` pass Thor's LSB, and
MiniMate callers are unchanged. Measured: the 8 thor-idf fixtures (24
channels) go from max|sample| / peak = 1.00706 to 1.00000 through the real
ingest path.
⚠ **Existing Thor `.h5` files keep the wrong scale until regenerated.** Run
`scripts/backfill_thor_events.py` (bump `TOOL_VERSION` at release so it is
gated, or pass `--force`), then `backfill_event_shape.py`, because the offset
metrics read these samples. No schema change, no migration. **Series-3
`.h5` files are unaffected** and do not need `backfill_sidecars.py`. A
`TOOL_VERSION` bump would make that script regenerate them anyway (~2 h on
the NAS), so don't run it for this.
- **Sub-minute histograms recorded with the microphone off decoded to nothing
(#47), and mic-on ones were read one byte off (#49).** A multi-interval block
is a 5-byte header, then one record per interval of **big-endian**
peak/half-period pairs (20 bytes with the mic, 16 without), then a 7-byte
trailer; the last block is short and ends on `9c 06 00 42`. The old reader
took the records as little-endian from byte 6, which agrees while every high
byte is zero, and misread 2 intervals across the archive (a mic peak and a
Long half-period). Verified against every archived histogram with a
Blastware export: **13,089/13,089 exact** (was 13,087), and BE9441's mic-off
`K441LTOK.QZ0` 66/66 peaks and 66/66 frequencies. ⚠ Decoder change: needs
the `TOOL_VERSION` bump plus `backfill_sidecars.py` and
`backfill_event_shape.py` to regenerate stored histograms -- the same run
this release's other fixes need (~2 h on the NAS). No schema change.
It changes **none** of the 10,433 histograms in prod's store (2026-09-30
snapshot): the misread needs a half-period of 256 or more, below ~2 Hz at the
archive's and prod's 1,024 sps. At 4,096 sps it is common -- below ~8 Hz --
and on BE9441's 3,398-interval `K441LTON.900` the old reader got 87 intervals
wrong (~2.6%); the new one gets all 3,398.
- **Re-storing an event at a corrected time duplicated it.** The event-time
fix above moves a waveform's time, and `events` is unique on
`(serial, timestamp)`, so re-storing an old event -- the release backfill, a
watcher re-forward -- found no row at the new time and inserted a second one.
Measured by storing real files with v0.31.0 and running this release's
`backfill_sidecars.py --force`: `N844LQHB.ZT0W` came out at 06:00:13 **and**
10:33:29, its false-trigger mark on the wrong copy. `insert_events` now
matches a row by its Blastware filename first and moves it to the new time in
place -- same id, review kept. When a different stored file already holds
that second, nothing moves and nothing is written (the old upsert wrote this
event over that one). Only Blastware names are matched (every unnamed upload
is `imported.bw`); of several copies a reviewed one with a time moves first.
Follow-ups: #52. No schema change, no migration.
- **A paired report's event time was never read from prod's reports.**
`_parse_event_date` read only "August 14, 2026"; all 81 report-paired
waveforms in prod's store (2026-09-30 snapshot) write "2026-08-14" --
Blastware follows the PC's settings. It reads both now (81/81, was 0/81).
The sidecar's `bw_report` block also never stored the event time and the
backfill's overlay never applied it; both do now, and `--reparse-txt`
re-reads the saved `.TXT`s. Codec-library change.
- **A Series-3 waveform's time comes from the instrument's own event record.**
The unit sends a copy of its event record inside the 5A stream, so it is in
every Blastware file and every SFM download:
`00 28 05 00 ?? ?? fe 80 [trigger][stop]`, each time
`dd mm yyyy(BE) 00 hh mm ss`.
- **Measured on 7,935 waveforms.** Its trigger equals Blastware's report
1,320/1,320, the filename 7,935/7,935 and the unit's `0C` record 10/10.
- **Provenance.** It occurs once in the unit's own A5 replies for each of 8
recorded events, and in SFM-only downloads.
- **Why it mattered.** The footer's `ts2 - record time` is a second off on
260 of prod's 1,394 (199 late, 61 early). On BE9558 the 61 early ones landed
on their histogram twin's second, so a fresh import wrote each waveform over
its histogram's row (888 files -> 827 rows). The backfill would also have
moved 161 rows that v0.31.0 had right a second off.
- **Validation.** A record counts only if its lead bytes, marker, both times,
its relation to the footer and its length all check out, and exactly one
candidate does.
- **Fallbacks.** Without one the estimate stands, recorded in the event's new
`decode_problems` and the sidecar's `timestamp_source`. A filename is never a
time source, only a cross-check, logged when it disagrees. A paired report
fills in only when there is no record.
- **An estimate is kept, never trusted.** An event is never discarded for
want of an exact time. But an estimated time never moves a row, never adds a
second row for an event already stored, and never lands on another event's
row (`insert_events` writes nothing and logs a warning naming both). The
file and sidecar are kept either way.
- **API.** New `decode_blastware_bytes(raw, name=None)` needs no file (the
import no longer writes a temp file); `blastware_file.blastware_filename_time()`
decodes a name for cross-checks.
- **Histograms keep `ts1`.** It runs a second early against Blastware on 97%
of them, though their record (marker `fe f5`) holds the exact start. With
both on exact times, a waveform and its histogram share a second 209 times
in prod's store, which `(serial, timestamp)` cannot hold -- #51.
- **Open.** 3 archive files named as waveforms are not recognised by the
waveform codec and keep the footer start, as before (none in prod).
Series-III reference §7.8.9.
Codec-library change.
### Added
@@ -445,10 +574,45 @@ All notable changes to seismo-relay are documented here.
### Migration
**None.** No codec change, no waveform-store change, no DB or schema change,
and **no `TOOL_VERSION` bump** — so no `backfill_sidecars.py` /
`backfill_event_shape.py` run is owed. The webapp is served from the image, so
its changes appear after the next `sfm` rebuild.
⚠ **This release owes prod a backfill, and it moves stored event times.**
`TOOL_VERSION` is bumped to **0.32.0**, which gates the regeneration. **Back up
`seismo_relay.db` first.** Then, in the `sfm` container, in this order (the
scripts default to `bridges/captures/seismo_relay.db` and its `waveforms/`):
1. `python scripts/backfill_sidecars.py --force --reparse-txt` -- re-decodes
every Series-3 event: sidecars and `.h5` regenerate, **waveform times move
to Blastware's** (each DB row in place -- id and review kept), and
`--reparse-txt` re-reads the saved `.TXT` reports. ⚠ `--reparse-txt` is
required the first time: prod's sidecars were written by the old parser, and
a run without it leaves report-paired rows on the binary's estimate.
⚠ **~2 h on the NAS.**
2. `python scripts/backfill_thor_events.py` -- Series-4 `.h5` samples onto
Thor's own LSB (#42).
3. `python scripts/backfill_event_shape.py --db-path bridges/captures/seismo_relay.db
--store-root bridges/captures/waveforms` -- the shape/offset metrics read the
regenerated samples.
**Rehearsed** on prod's 2026-09-30 store snapshot (11,827 Series-3 files; stale
-- prod has more since): stored with v0.31.0 exactly as the watcher does, then
step 1 with this release. Waveforms on Blastware's exact time **1,016 → 1,394
of 1,394**: 373 had been hours off (up to 14.3 h) and 5 a second off. Every row
id kept, none lost or merged, no refusals, no errors. Histograms do not move
(#51). One known extra row: a histogram whose time does not decode
(BE18003 `T003LCYV.JD0H`) gains a duplicate on every backfill -- pre-existing,
#52. A log line "nothing stored" from `insert_events` names a file whose
corrected second another file already holds; expected zero. (The rehearsal
ran when waveform times came from the filename; the event record that replaced
it gives the identical time on all 1,394 of those waveforms, so it stands.) A
log line "no validated embedded event record" names a waveform kept on the
footer estimate; expected zero (every prod waveform has one).
**Terra-View** reads SFM's rows by id and needs no change, but its views show
the corrected times: waveforms move up to hours later in the day, so an event
can land in a different day, deployment window or summary, and waveform /
histogram twin matching can change. That is the correction, not a fault.
The webapp is served from the image, so its changes appear after the next
`sfm` rebuild.
The Series-4 live client adds **new** modules under `micromate/`
(`framing.py`, `protocol.py`, `client.py`) and appends three dataclasses to
+12 -245
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.32.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,7 +10,7 @@ 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-10-19)
Read this first when picking the project back up.
@@ -24,31 +24,9 @@ Read this first when picking the project back up.
by 47x). Read path, event chain, setups, scheduler, monitoring control and
per-event delete are all mapped — **and as of 2026-10-14 so is the inbound
call-home session.** There are no protocol unknowns left.
~~⚠ **No command has ever been originated against a unit by this project.**
⚠ **No command has ever been originated against a unit by this project.**
Every write was performed by THOR while we recorded. That line is worth
keeping.~~ **Retracted 2026-10-25:** the first commands this project
originated against a **Micromate** were `0x96` / `0x97` (start / stop
monitoring) to **UM20147 on 2026-10-25**, sent by SFM at the bench with
Brian's go for each send — 4 sends, each acked and read back, each audited.
(This line was always about Series 4: the `minimateplus` stack has sent
Series-III writes — start/stop, config push, erase, call-home config — since
April 2026.) Every *other* Micromate write (call-home, setup push, delete,
scheduler) is still THOR-only, never sent by us. Details:
`docs/micromate_protocol_reference.md` → *The first commands this project
originated against a Micromate*.
**Series-4 write path, phase 2 is done (2026-10-22):** the write encoder, a
send-side opcode gate and write *plans* for start/stop, call-home enable and
the setup rewrite, reproduced byte for byte against THOR's captured frames.
`bridges/mm_dry_run.py` prints a write's planned frames from a live unit's
reads (run on UM20147: sizes equal UM12947's). `MicromateProtocol._send`
refuses every write opcode except one start/stop plan at a time through
`execute()`, on a connection with a fresh Micromate reply, and refuses `0xA2`
always. The only transmit path for a write is `execute()`, reached only from
SFM's serial-named start/stop routes through `sfm/device_access` (identity,
state, audit, read-back, never retried); the Series-3 `minimateplus` stack
and raw-socket bench bridges are outside the gate. The reproduction's
breadth is one distinct input per block (the five pushes share the same name,
prefs and trigger block).
keeping.
- **✅ `micromate/` HAS a live client (2026-10-02).** `framing.py`,
`protocol.py`, `client.py` + models, **119 tests**, mirroring the
`minimateplus/` stack and reusing its `transport.py` unchanged. Connect over
@@ -119,104 +97,8 @@ Read this first when picking the project back up.
— `micromate/setup_block.py`, measured fields only, checksum-verified,
69 tests on 15 real fixtures (`tests/fixtures/micromate-setup/`, force-
added). `bridges/mm_client_check.py` prints it; Brian matched every line
against UM20147's screen.
✅ **SFM speaks Series 4 by serial (phase 1a, 2026-10-20):** `/device/info`,
`/device/monitor/status` and `/device/settings` take `serial` and return one
shared shape for both series through `sfm/device_access/`. Micromate lines
are held open (one call-up, keep-alive 60 s, idle hang-up 5 min, released on
RADIO RING); MiniMates still reconnect per request. Without `serial` the
legacy Series-3 path is unchanged.
✅ **Phase 1b (2026-10-21) lists and downloads events by serial for both
series** -- the MiniMate list comes from headers only (no 5A), and a download
is checked and stored in SFM's DB (`db_event_id`). Bench-checked on UM20147:
5 events, a waveform that verified, a histogram, one call-up for the whole
sequence. ~~⚠ The MiniMate header walk is **unproven on a unit; a MiniMate
bench check is owed before the branch merges.**~~ **2026-10-25, first
MiniMate bench run (BE9441, serial cable):** the header walk listed 20
events correctly, and the check found four bugs, all fixed and tested on its
logged bytes.
1. **Every non-first event SFM assembled was 2 bytes short.** The body
builder assumed the 0x1002/0x1004 metadata pages in every 5A stream; it
now reads each A5 reply's echoed address. This also affected legacy
`get_events` and `ach_server.py` files. Blastware's own files were not
affected.
2. **A reboot mid-download stored a partial event as a success.** A strict
5A stream now raises on any early end. The reboot itself was ours: the 5A
request had a bare `0x02` checksum, which the unit reads as STX. A 5A
checksum in {02, 03, 04, 10} is now DLE-escaped (re-run 2026-10-26).
3. **The unit boots when its port opens** and ignores a POLL sent before the
`Operating System` banner. Startup now waits for it.
4. **The 0x15 serial is a C string** (`"BE9441\x00?"`).
Series-3 downloads are now checked against the unit's own 0C peaks before
being stored. **Re-run 2026-10-26:** every event that does not cross a
64 KB page downloaded whole and verified (events 0, 1, 3, 4, 10). ~~The two
that cross one (events 2, 19) are refused by name.~~ **Later the same day the
page bug was fixed** (see the ✅ FIXED entry below): a fresh 8 events, 4 of them
crossing a page, all downloaded byte-identical to Blastware's own files. Stale
id gives 409, a repeat gives `already_stored`, also against Blastware's imported
copy. **Evening 2026-10-26 (measured):** a 71 KB histogram (139 requests, two
64 KB crossings) downloaded byte-identical to Blastware's, and SFM **stopped**
the unit through the new audited path (acked, read back idle). That needed
`d990466`: the 0x1C flag reads **0x0B** during a histogram run (only 0x10 had
been measured), and the status decode had to unescape before counting from the
end. **Start too (2026-10-27 00:12):** idle → monitoring, verified -- once a
start's read-back waited out the ~30 s sensor check and re-sent the wake
(`9886422`, `ca5c401`; a monitoring MiniMate answers nothing until woken, and
nothing during its sensor check). Still owed before merge: #47 from dev, and
`persist_download` aligned with dev's waveform-time restamp (spec).
- **Phase 1c: the SFM webapp by serial (2026-10-29), built; bench pass owed.**
`sfm/sfm_webapp.html` has a **Serial** field beside host/port. With one, the
Live tabs use the serial-based routes for both series: identify, status (now
with the unit's clock and event count), settings (read-only), the event list
with a Download per row (checked, stored, then opened from the store), and
audited start/stop (asks first, one send, shows the ChangeResult as it is).
Hang up appears for a Series 4. Every series-specific control follows the
unit's own `/device/info` answer, never the typed serial, and drops the
moment the serial, host or port is edited. Config and call-home **writes are
off for both series** (phases 5 and 4); Diagnostics is enabled only for a
confirmed Series 3. Without a serial every read behaves as before.
The page keeps every routing and button rule in one block of pure functions
between `/* <device-routing> */` markers, run through **Node** by
`tests/test_webapp_device_routing.py` (skipped when `node` is absent); a
static test fails if a `/device/` URL is built anywhere else.
**Server side:** the legacy Series-3 writes and erase -- `POST /device/config`
(and `/config/project`), `/events/erase`, `/rescue` (when it disables ACH or
erases), `POST /device/call_home` -- read the unit's serial (or reuse the one
`connect()` read) and refuse 409, nothing sent, unless it is Series 3 and,
when `serial=` was given, that unit. 0xA2 is CONFIRM ERASE on a MiniMate and
ends a call-home on a Micromate. The stop tools (legacy `monitor/start|stop`,
`stop_monitoring_blind`, `_slow_drip`, `_spam`) are exempt: 0x96/0x97 mean
the same on both series, and the blind tools must reach a unit too wedged to
answer.
**Bench pass done 2026-10-29** (both series, each on its own modem): 16
findings in the spec (*Left open by the 1c bench*) -- the S3 settings decode
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.
**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.
While THOR polls a unit, SFM gets no reply and does not disturb THOR.
✅ **Line hold decided (Brian, 2026-10-29): keep it as is for now; the
long-term fix is SFM handling auto call-ins itself.** The ring-path merge gate
is settled. THOR's log: `C:\THORDATA\Logs\`.
Next: a short fix plan for the findings, then phases 4 and 5.
- **✅ Phase 3: start / stop monitoring by serial (2026-10-23) — built,
reviewed, and bench-verified on UM20147 (2026-10-25).** Start acked in
0.46 s and read back as monitoring at the first 2 s poll (during the sensor
check); stop acked in 0.12 s, then `0x49` read a new value **`0x01` for ~18 s**
(inferred: the unit's call-home attempts after a stop — refused as unmeasured
until settled) before idle; a stop while idle is a harmless 10 ms no-op. The
Series-3 path is unproven on a unit (MiniMate bench check owed). Both
series go through one safety core, `sfm/device_access/change.py`: a fresh
identity read, the run state (calling home or never measured is refused),
`dry_run` (the exact frames, nothing sent), a row in the new
`device_commands` audit table (`GET /db/device_commands`; `sent` says whether
a frame went out, `states` keeps every read), one send never retried, then a
read-back. The HTTP status is an allow-list -- only a dry run, a skip or a
send read back as made is a 200 -- and a failure after the send says so and
names its audit record.
against UM20147's screen. Not yet in SFM — nothing there uses the
Micromate client.
- **🔑 ACH / call-home, captured end to end (2026-10-14).** A Micromate signals
`RADIO RING`; **two paths exist and timing decides which**: if anything
already holds the modem's single TCP session the ring rides that connection,
@@ -291,37 +173,7 @@ Read this first when picking the project back up.
4th-decimal tick and are Thor's own rounding — no single linear LSB can
reproduce every printed value (the constraints are infeasible by 7e-5
relative), so do NOT retune `_GEO_LSB_IPS`.
- **✅ FIXED 2026-10-26 (`887e75d`) — was: "KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB."**
Kept below as history. The fix came from a recording of Blastware downloading all 8 of
BE9441's events, 4 crossing a page (`tests/fixtures/minimate-bench-10-26-26-blastware/`):
- **Every MiniMate request DLE-escapes 02, 03, 04 and 10**, payload and checksum alike
(748/748 re-encode). `build_bw_frame` had escaped only 0x10.
- **A 5A request is an ordinary request carrying a LENGTH and a 4-byte linear ADDRESS.**
The walk: the event's start, +0x200 carrying into the page byte, then TERM at the
next boundary for the remainder.
- **The old model misread the same bytes.** The "offset 0x1002" is length 0x0200
escaped; the "metadata pages at 0x1002/0x1004" are event 0's chunks at 0x0200 and
0x0400; the 16-bit counter could not leave its page.
- **Verified on BE9441**, live: all 8 events, including 4 page crossings, downloaded
whole and matched the unit's own peaks.
⚠ Sections below that describe "partial DLE stuffing", "11-byte params", "offset_hi
0x10 raw" and "metadata pages 0x1002/0x1004" are that misreading. They are retracted
here, not deleted.
**Review follow-ups (2026-10-26):** the walk's chunk cap is now sized from STRT (a
caller's 128 cut every event past ~66 KB; 2,545 of 63,500 archived histograms are
bigger); a STRT claiming less than one chunk or more than 4 MiB is refused as a
misread; a TERM is sent only for a true tail. Still open, none measured: an event
ending exactly on a chunk step sends a zero-length TERM (as the old code did; 1 in
512, never seen); with no STRT the legacy walk still reads `max_chunks` blind.
🔶 **Inferred only, do not act on it without a capture:** `build_bw_write_frame`
("raw except BW_CMD", "DLE-aware checksum") carries the same fingerprints as the
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.
~~**⚠ KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB.**~~
- **⚠ 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
at `0x0112_1010` therefore reads `end_offset = 0x1010` — *behind* its own
@@ -339,19 +191,6 @@ Read this first when picking the project back up.
over) needs a BW capture of a spanning event first. Do not ship layer one
alone without a loud truncation warning — a silently short event is the
failure mode this codec has been bitten by repeatedly.
**Narrowed 2026-10-26 (BE9441, measured):**
- The one-event download now refuses a spanning event by name (502), before
any chunk.
- STRT carries the full 32-bit end key, so the page is there to use.
- A read-only test walk carrying the page byte got a proper reply for the
first chunk in the next page (`01 12 01 2c`). The second chunk, params
`… 01 12 03 2c`, got none: a raw `0x03` inside the params.
- Pages after `0x11` have counters with `02`/`03`/`04` bytes. Page `0x11`
has none, because event 1 skips `0x0000`–`0x05FF`.
- How Blastware encodes those bytes is the one unknown left. The capture to
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
inserts DB rows for store files that have none (one-time per store) and the
@@ -591,7 +430,7 @@ Full read pipeline + write pipeline + erase pipeline + monitor log + call home c
| Event header / first key | 1E | ✅ |
| Waveform header | 0A | ✅ |
| Waveform record (peaks, timestamp, project) | 0C | ✅ |
| **Bulk waveform stream (event-time metadata + full waveform)** | **5A** | ✅ **(2026-10-26: a LENGTH read at a 32-bit ADDRESS, every 02/03/04/10 escaped — the model in the rest of this cell is retracted, see "✅ FIXED 2026-10-26")** byte-perfect against BW captures (v0.14.3, 2026-05-05) — STRT-bounded chunk walk + correct event-N probe counter + DLE-stuffed `0x10` bytes in params + concatenate-only file body assembly. All 17 5A request frames in the 5-1-26 3-sec capture reproduce byte-for-byte. |
| **Bulk waveform stream (event-time metadata + full waveform)** | **5A** | ✅ **byte-perfect against BW captures (v0.14.3, 2026-05-05)** — STRT-bounded chunk walk + correct event-N probe counter + DLE-stuffed `0x10` bytes in params + concatenate-only file body assembly. All 17 5A request frames in the 5-1-26 3-sec capture reproduce byte-for-byte. |
| Event advance / next key | 1F | ✅ |
| **Write commands (push config to device)** | **68–83** | ✅ new v0.8.0 |
| **Erase all events** | **0xA3 → 0x1C → 0x06 → 0xA2** | ✅ new v0.9.0 |
@@ -920,14 +759,6 @@ S3→BW (response):
## Critical protocol gotchas (hard-won — do not re-derive)
### SUB 5A — bulk waveform stream — NON-STANDARD frame format
> ⚠ **RETRACTED 2026-10-26 (measured): it is a standard frame.** The payload is
> `[10 00 5A 00][length BE][address BE 4][zeros 6]` with a SUM8 checksum, and every
> 02/03/04/10 is DLE-escaped (`s3_stuff`, `build_5a_request`). "offset_hi 0x10 raw" was
> the length 0x0200 escaped (`10 02 00`). The "DLE-aware checksum" is SUM8 of the
> unescaped payload. The "partial stuffing" carve-outs were the escape rule seen half.
> All 540 of Blastware's 5A requests rebuild byte for byte
> (`tests/test_5a_blastware_walk.py`). The text below is history.
**Always use `build_5a_frame()` for SUB 5A. Never use `build_bw_frame()` for SUB 5A.**
@@ -968,9 +799,6 @@ the 1-2-26 BW TX capture (10 frames). Difference (3) confirmed against the 5-1-
"bwcap3sec" capture (17 frames, all match byte-for-byte after fix).
### SUB 5A — chunk counter formula (REWRITTEN 2026-05-01 — see 5-1-26 captures)
> ⚠ **SUPERSEDED 2026-10-26:** a chunk is addressed by a full 32-bit address, stepping
> +0x200 across page boundaries; no event-1 special case (see `read_bulk_waveform_stream`).
> ⚠️ **Everything that came before this rewrite was WRONG in important ways.** The previous
> formula `max(key4[2:4], 0x0400) + (chunk_num - 1) * 0x0400` happened to *work* for events
@@ -1055,11 +883,6 @@ several events should read 0x1002/0x1004 only once at the start.
`read_bulk_waveform_stream`.
### SUB 5A — STRT record encodes end_offset (NEW 2026-05-01)
> ⚠ **SUPERSEDED 2026-10-26:** the end is the FULL 32-bit `end_key`
> (`parse_strt_end_key`), read after removing the reply's escape bytes. The 16-bit
> `end_offset` below was the 64 KB page bug, and misread any end whose low bytes held
> an escaped 02/03/04.
The first A5 response (probe response, or the first chunk for event 2+) contains a STRT
record at byte offset 17 of the `data` field. Layout:
@@ -1089,11 +912,6 @@ Verified across 3 events:
| 5-1-26 "copy 2nd address" / DA event 2 | `011121F2` | `0111417E` | `0x417E` (event 2 span 0x1F8C = 8,076 B) |
### SUB 5A — TERM frame formula (FINALIZED 2026-05-01)
> ⚠ **SUPERSEDED 2026-10-26:** TERM is `build_5a_request(next_boundary, end -
> next_boundary)`: a read of the remainder at the next 32-bit boundary. "offset_word"
> is that length; "params[2:4]" are the address's low bytes. The tables below still
> hold as numbers.
The TERM frame fetches the partial last chunk *and* the file footer. It is **not** a simple
"goodbye" frame — its response payload contains the bytes between the last full 0x0200-aligned
@@ -1129,11 +947,6 @@ are wrong; the device's response under that path is a tiny 101-byte device-side
(arrived only after we walked the entire post-event buffer), not the proper file footer.
### SUB 5A — fixed metadata pages 0x1002 and 0x1004 (NEW 2026-05-01)
> ⚠ **RETRACTED 2026-10-26 (measured):** these are not fixed global pages. They are the
> first event's own chunks at addresses 0x0200 and 0x0400, which escape to `10 02 00` and
> `10 04 00` on the wire. A non-first event has no such reads because it does not start at
> 0x0000. Their strings are still read as described below.
Two chunk addresses are GLOBAL device/session metadata, not event-specific:
@@ -1158,18 +971,12 @@ locates the ASCII strings via label scans (`Project:`, `Client:`, `User Name:`,
dump the structural layout if more session-global fields need to be extracted.
### SUB 5A — params are 11 bytes for chunk frames, 10 for termination
> ⚠ **RETRACTED 2026-10-26:** every 5A request has the standard 10 params bytes (address +
> 6 zeros). The "11th byte" was the length's low byte, read as params.
`bulk_waveform_params()` returns 11 bytes (extra trailing `0x00`). The 11th byte was
confirmed from the BW wire capture. `bulk_waveform_term_params()` returns 10 bytes.
Do not swap them.
### SUB 5A — event-time metadata source (FINALIZED 2026-05-05)
> ⚠ **AMENDED 2026-10-26:** the strings come from the first event's chunks at 0x0200 and
> 0x0400, not from "global pages read once per session" (see the retraction above).
The metadata strings come from the two fixed metadata pages at counter `0x1002` and
`0x1004` (see "SUB 5A — fixed metadata pages 0x1002 and 0x1004" above). These pages
@@ -1211,11 +1018,6 @@ that's an old-walk artifact (the broken `0x0400`-step formula occasionally caugh
pages instead.
### SUB 5A — end-of-stream (FINALIZED 2026-05-01)
> ⚠ **AMENDED 2026-10-26:** a reply's `page_key` is not a page. It is the echoed
> length plus an escape byte the parser keeps: all 532 chunk replies read `0x0010` and
> the 8 TERMs `0x0000`/`0x0001`. The walk relies on it only for the mid-stream
> terminator check, and now sends TERM only for a tail (< 0x200).
Under the v0.14.0+ STRT-bounded walk the stream ends cleanly:
@@ -1381,7 +1183,6 @@ Confirmed from the 5-1-26 "Download All" capture:
1F → null sentinel
```
(⚠ 2026-10-26: the walk starts at the 0x46 key itself, as a plain 32-bit address.)
This is why event 2's first 5A chunk is at `start_key + 0x46` — that's the address of the
"real start" 0x46-record, distinct from the `0x2C`-record at the raw boundary. Use the
`0x46` keys as the input to `read_bulk_waveform_stream`, not the `0x2C` keys.
@@ -1600,32 +1401,12 @@ for 0x10 records).
GET /device/info?port=COM5 ← serial
GET /device/info?host=1.2.3.4&tcp_port=9034 ← cellular
GET /device/events?host=1.2.3.4&tcp_port=9034&baud=38400
GET /device/events?serial=UM20147&host=...&tcp_port=... ← list with event_id, either series (no 5A on a MiniMate)
POST /device/events/download?serial=UM20147&event_id=...&host=... ← download, check, store; returns db_event_id
GET /device/event?host=1.2.3.4&tcp_port=9034&index=0
GET /device/monitor/status?host=1.2.3.4&tcp_port=9034 ← battery, memory, mode
POST /device/monitor/start?host=1.2.3.4&tcp_port=9034 ← start recording
POST /device/monitor/stop?host=1.2.3.4&tcp_port=9034 ← stop recording
POST /device/monitor/start?serial=UM20147&host=...&tcp_port=...&dry_run=&even_if_already= ← audited start, either series
POST /device/monitor/stop?serial=UM20147&host=...&tcp_port=...&dry_run=&even_if_already= ← audited stop, either series
GET /device/settings?serial=UM20147&host=1.2.3.4&tcp_port=9034 ← shared-model settings, either series
POST /device/hangup?host=1.2.3.4&tcp_port=9034 ← release a held Series-4 line
```
`serial=` (UM = Series 4, BE/BA = Series 3) on `/device/info`, `/connect`,
`/monitor/status`, `/settings` returns the shared model, uncached; on `/events` and
`/events/download` it lists and downloads by `event_id`; on `/monitor/start` and
`/monitor/stop` it runs the audited change (`dry_run=true` returns the frames and sends
nothing; `even_if_already=true` sends even when the unit is already in that state). A
`UM` serial on any other `/device/*` route is 501; any request taking the legacy
Series-3 path at a held Series-4 address is 409.
The legacy Series-3 writes and erase (`POST /device/config`, `/config/project`,
`/events/erase`, `/rescue`, `POST /device/call_home`) take an optional `serial=` and
refuse 409, nothing sent, when the unit at the address does not answer as Series 3
or is not the named unit. The stop tools (`monitor/start|stop` without a serial,
`stop_monitoring_blind`, `_slow_drip`, `_spam`) are exempt by design.
SFM must run a single uvicorn worker (locks and held lines are per process).
Server retries once on `ProtocolError` for TCP connections (handles cold-boot timing).
### DB read endpoints (query seismo_relay.db written by ach_server.py)
@@ -1636,7 +1417,6 @@ GET /db/events?serial=BE11529&from_dt=&to_dt=&limit= ← triggered events, ne
GET /db/monitor_log?serial=BE11529&from_dt=&to_dt= ← monitoring intervals, newest first
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
```
DB file: `bridges/captures/seismo_relay.db` (default; override with `--db-path` at startup).
@@ -1648,30 +1428,17 @@ All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger`.
| Capture | Location | Contents |
|---|---|---|
| 1-2-26 | `bridges/captures/1-2-26/` | SUB 5A BW TX frames — confirmed 5A frame format, 11-byte params, DLE-aware checksum (⚠ that model retracted 2026-10-26: a standard frame, length + 32-bit address) |
| 1-2-26 | `bridges/captures/1-2-26/` | SUB 5A BW TX frames — confirmed 5A frame format, 11-byte params, DLE-aware checksum |
| 3-11-26 | `bridges/captures/3-11-26/` | Full compliance setup write, Aux Trigger capture |
| 3-31-26 | `bridges/captures/3-31-26/` | Complete event download cycle (148 BW / 147 S3 frames) — confirmed 1E/0A/0C/1F sequence; only 1 event stored so token=0xFE appeared to work |
| 4-3-26 | `bridges/captures/4-3-26/` | Browse-mode S3 capture with 2+ events — confirmed all-zero params for 1F, 1F response layout, null sentinel, 0A context requirement |
| 4-27-26 | `bridges/captures/4-27-26/` | BW "open 2sec waveform" + "copy event to disk" + paired SFM "seismo_dl" — first proof that SFM was over-reading 5× past event end. BW reads 14 chunks at 0x0200 increments + TERM at end_offset; SFM was reading 37 chunks at 0x0400 increments. STRT end_key field located. |
| 5-1-26 | `bridges/captures/5-1-26/comcheck/` | Three sub-captures: SFM 3-sec download (`seismo_dl_…`), BW comms-check + 3-sec download (`bwcap3sec/`), BW second-event download + "Download All" (`raw_*_170945`/`_171216`). Confirmed: TERM frame formula across 3 events; metadata pages 0x1002/0x1004 are global (read once per session) (⚠ retracted 2026-10-26: event 1's chunks at 0x0200/0x0400); event-1 vs event-N chunk-pattern split; WAVEHDR length 0x46 vs 0x2C disambiguates real events from boundaries. |
| 5-1-26 | `bridges/captures/5-1-26/comcheck/` | Three sub-captures: SFM 3-sec download (`seismo_dl_…`), BW comms-check + 3-sec download (`bwcap3sec/`), BW second-event download + "Download All" (`raw_*_170945`/`_171216`). Confirmed: TERM frame formula across 3 events; metadata pages 0x1002/0x1004 are global (read once per session); event-1 vs event-N chunk-pattern split; WAVEHDR length 0x46 vs 0x2C disambiguates real events from boundaries. |
---
## Write commands (SUBs 68–83) — confirmed 2026-04-07
> ⚠ **RETRACTED 2026-10-27 (#46, measured): write frames are ordinary requests.**
> Every 02/03/04/10 is escaped and the checksum is SUM8 of the payload, as in every
> request. The length field [4:6] is the data's length. A config block is its own
> length N + 2 bytes; the compliance image (2,092) goes in addressed chunks
> (params[2:4]; 512 B now, 1,024 B in March). This re-encodes all 3,869 Blastware
> requests from February to April, plus 26 write frames from 2026-10-26. The
> "raw except BW_CMD", "DLE-aware checksum", "offset = data[1] + 2" and "71×3 at
> 0x1004" below were the same frames read with their escape bytes in. The trigger
> block is READ (SUB 0x2E) -- its byte 5 differs by unit -- not a fixed blob.
> Code: `build_bw_write_frame`, `protocol.write_image`, `b5037b0`. The text below
> is history.
All confirmed from 3-11-26 BW TX capture (`raw_bw_20260311_170151.bin`, frames 102–112).
### Write frame format — CRITICAL: minimal DLE stuffing
@@ -2282,7 +2049,7 @@ body) because writing a dial string may require DLE escaping for embedded contro
| Folder / File | Contents |
|---|---|
| `1-2-26/` | First SUB 5A BW TX capture — established 5A frame format (raw offset_hi, DLE-aware checksum). 10 frames verified. (⚠ model retracted 2026-10-26) |
| `1-2-26/` | First SUB 5A BW TX capture — established 5A frame format (raw offset_hi, DLE-aware checksum). 10 frames verified. |
| `3-11-26/raw_bw_20260311_170151.bin` | Full compliance write + event download (SUBs 68→83 confirmed, frames 102–112) |
| `3-31-26/` | Single-event download (148 BW / 147 S3 frames) — 1E/0A/0C/1F sequence confirmed (single event so token=0xFE appeared to work in either branch) |
| `4-2-26/` | Download-mode BW TX capture — POLL×3 requirement confirmed (frames 68-73 between 1F and first 5A) |
@@ -2294,7 +2061,7 @@ body) because writing a dial string may require DLE escaping for embedded contro
| `4-20-26/geo sensitivity/` | Geo sensitivity changes: 1.25 in/s (Sensitive), 10 in/s (Normal) |
| `4-20-26/call home settings/` | Call home config read/write captures |
| `4-27-26/` | BW "open 2sec waveform" + "copy event to disk" + paired SFM "seismo_dl" — first proof of 5× SFM over-read. STRT end_key field located. |
| **`5-1-26/comcheck/`** | **Triplet of captures that nailed the v0.14.0 walk:** SFM 3-sec download (`seismo_dl_…`), BW comms-check + 3-sec download (`bwcap3sec/`), BW second-event download + "Download All" (`raw_*_170945` / `_171216`). Confirmed: TERM frame formula across 3 events, metadata pages 0x1002/0x1004 are global session metadata (⚠ retracted 2026-10-26: event 1's chunks at 0x0200/0x0400), event-1 vs event-N chunk pattern split, WAVEHDR off=0x46 vs 0x2C disambiguates real events from boundaries. |
| **`5-1-26/comcheck/`** | **Triplet of captures that nailed the v0.14.0 walk:** SFM 3-sec download (`seismo_dl_…`), BW comms-check + 3-sec download (`bwcap3sec/`), BW second-event download + "Download All" (`raw_*_170945` / `_171216`). Confirmed: TERM frame formula across 3 events, metadata pages 0x1002/0x1004 are global session metadata, event-1 vs event-N chunk pattern split, WAVEHDR off=0x46 vs 0x2C disambiguates real events from boundaries. |
| **`5-1-26/comcheck/bwcap3sec/`** | **The byte-perfect reference for v0.14.3.** All 17 BW 5A request frames (probe, 2 metadata, 13 samples, TERM) reproduce byte-for-byte from SFM's framing helpers — including the `10 10 00` DLE-stuffed counter for sample @ 0x1000 that was the long-standing failure mode. |
| `5-4-26/` | BW MITM captures of "copy 3sec / 2sec / Download All" + paired SFM session (`seismo_dl_20260504_145701`) showing the +0x46 event-N probe bug producing 110-chunk runaway walk. Cross-references against 5-1-26 confirmed device behavior is identical. |
+35 -19
View File
@@ -1,11 +1,11 @@
# seismo-relay `v0.31.0`
# seismo-relay `v0.32.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,21 @@ 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*.
> See [CHANGELOG.md](CHANGELOG.md) for full version history.
---
@@ -177,25 +192,10 @@ via a thread-safe `_LiveCache` (plain Python dict + `threading.Lock`):
| `POST` | `/device/monitor/start` | Sends SUB 0x96; immediately evicts status cache |
| `POST` | `/device/monitor/stop` | Sends SUB 0x97; immediately evicts status cache |
| `POST` | `/device/call_home` | Reads, patches specified fields, writes back to device |
| `GET` | `/device/settings` | Recording settings in the shared model, either series; serial required; never cached |
| `POST` | `/device/hangup` | Releases a held Series-4 line now; `{"hung_up": bool}` |
| `GET` | `/device/events?serial=` | Lists a unit's events, either series, each with an opaque `event_id` (`serial:key:timestamp`). A MiniMate list reads headers only (no bulk download), on the normal timeout, and gives `record_type: null` (its event record does not say waveform or histogram; not decoded yet). A lost walk reply fails the list rather than shortening it (a lost event-record reply still lists that event, without a timestamp) |
| `POST` | `/device/events/download?serial=&event_id=` | Downloads one event, checks it, and stores it in SFM's database; returns `db_event_id` (file at `GET /db/events/{db_event_id}/blastware_file`). A stale `event_id` (unit erased or wrapped since the list) gets **409** without downloading, for both series; an `event_id` from another unit gets **422**, before any I/O. An event already stored — by an earlier download, or by THOR's or Blastware's call-home watcher — returns its existing row and changes nothing (same `db_event_id`, `inserted: false`, `detail.already_stored: true`). The unit is busy for the whole download; other requests to it get 423 |
**Cache bypass** — All cached endpoints accept `?force=true` to skip the cache and
force a fresh read from the device.
**Serial-named requests (Series 3 and 4)** — `/device/info`, `/device/connect`,
`/device/monitor/status` and `/device/settings` accept `serial` (`UM...` = Series 4
Micromate, `BE...`/`BA...` = Series 3 MiniMate Plus) and return one shared model
for either series. Serial-named requests are **not cached** and ignore `force`.
Without `serial` the legacy Series-3 behaviour is unchanged. Any other `/device/*`
route given a `UM` serial answers **501** ("not supported for Series 4 yet"), and any
request that takes the legacy Series-3 path (no `serial`, or a `BE`/`BA` serial on a
route that does not take one) at an address holding a Series-4 line answers **409**
(use `POST /device/hangup` first). Series-4 lines are held open between requests, so
SFM must run a **single uvicorn worker**: locks and held lines are per process.
**Cache stats** — `GET /cache/stats` returns hit/miss counts and TTL info; `DELETE /cache/device`
clears the device cache immediately.
@@ -224,6 +224,8 @@ 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 |
|--------|-----|-------------|
@@ -363,6 +365,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
@@ -622,7 +638,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.
-91
View File
@@ -1,91 +0,0 @@
#!/usr/bin/env python3
"""Dry run a Micromate write against a live unit: do the reads, print the plan.
Sends READS only. The write frames are built from the unit's own blocks and
printed for review -- step 1 of the bench protocol for every first live write
(parity spec, Testing). The protocol's opcode gate refuses every write SUB on
this connection, so nothing else can go out even by mistake.
sg dialout -c ".venv/bin/python bridges/mm_dry_run.py /dev/ttyACM0 call-home-off"
.venv/bin/python bridges/mm_dry_run.py --host 10.0.0.5 --tcp-port 9034 setup-rewrite
The JSON carries a `reads` block (length of each block read, and for
setup-rewrite the blocks themselves in hex) so the plan can be checked against
what the unit actually said.
⚠ `0x1A` reads the keypad's edit buffer live. A setup read taken while someone
is in the unit's menu includes their unsaved edits, and pushing that plan would
commit them.
⚠ The setup-rewrite JSON embeds the unit's whole `0x1A` block (job number,
notes), so do not paste it anywhere public.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from micromate.client import CONTENT, MicromateClient # noqa: E402
from micromate.writes import ( # noqa: E402
plan_call_home_enabled, plan_setup_push, plan_start_monitoring, plan_stop_monitoring,
)
from minimateplus.transport import SerialTransport, TcpTransport # noqa: E402
ACTIONS = ("start", "stop", "call-home-on", "call-home-off", "setup-rewrite")
def _content(data: bytes) -> bytes:
"""The protocol's read_* methods return the response data with its 11-byte prefix."""
return bytes(data)[CONTENT:]
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("port", nargs="?", help="serial port, e.g. /dev/ttyACM0")
ap.add_argument("action", choices=ACTIONS)
ap.add_argument("--host")
ap.add_argument("--tcp-port", type=int, default=9034)
ap.add_argument("--baud", type=int, default=115200)
a = ap.parse_args()
if not (a.port or a.host):
ap.error("give a serial port or --host")
transport = TcpTransport(a.host, port=a.tcp_port) if a.host else SerialTransport(a.port, a.baud)
mm = MicromateClient(transport) # no execute(): nothing here can transmit a write
mm.open()
try:
info = mm.connect()
p = mm.protocol
reads = {}
if a.action == "start":
plan = plan_start_monitoring()
elif a.action == "stop":
plan = plan_stop_monitoring()
elif a.action.startswith("call-home"):
ch = _content(p.read_call_home_config())
reads["0x2C"] = {"len": len(ch)}
plan = plan_call_home_enabled(ch, a.action == "call-home-on")
else:
name = mm.get_active_setup()
prefs = _content(p.read_event_index())
trig = _content(p.read_trigger_config())
setup = _content(p.read_compliance_config())
reads = {"active_setup": name,
"0x08": {"len": len(prefs), "hex": prefs.hex()},
"0x2E": {"len": len(trig), "hex": trig.hex()},
"0x1A": {"len": len(setup), "hex": setup.hex()}}
plan = plan_setup_push(prefs, trig, setup, name)
out = plan.describe()
out["unit"] = {"serial": info.serial, "firmware_line": info.firmware_line}
out["reads"] = reads
print(json.dumps(out, indent=1))
finally:
mm.close()
return 0
if __name__ == "__main__":
sys.exit(main())
+69 -8
View File
@@ -11,12 +11,7 @@
| Date | Section | Change |
|---|---|---|
| 2026-10-27 | §3 writes | **⚠ RETRACTS the write-frame model (#46, measured).** Every Blastware request on record re-encodes under the uniform rule (02/03/04/10 escaped, SUM8): 3,869/3,869 frames in the Feb–Apr 2026 captures, plus BE9441's 26 write frames of 2026-10-26. A write's [4:6] is its data LENGTH. Config blocks are their header N + 2 bytes: event index (68) and trigger (82) are written as read plus `02 00` / `00 00` (constant on 15 sends); waveform data (69) and the 2,092-byte compliance image (71) are written whole, the latter in addressed chunks (params[2:4] = address; 1,024 B in March, 512 B with Blastware 10.74). The trailing two bytes are not a CRC and went out stale, so the unit evidently ignores them. "Only BW_CMD doubled", the "DLE-aware checksum", "offset = data[1] + 2" and "chunks 1,027 / 1,055 at offset 0x1004" were these frames read with their escape bytes in. The trigger block is read first (SUB 0x2E, 26 bytes); its byte 5 has been 01 / 03 / 04 by unit and session (meaning unknown). |
| 2026-10-26 (4) | §3, §10 | **Replies follow the request rule; a write-frame suspicion (inferred).** Measured on all 748 reply frames of the 10-26 recording: the unit escapes exactly 02/03/04/10 with a `10`, and the checksum is **SUM8 of the unescaped payload**, 748/748. The long-held "S3 response checksums frequently fail SUM8" (`protocol._validate_frame`) is `S3FrameParser`'s own doing: it keeps the `10` of `10 02/03/04` in its output (consumers rely on that) and sums it, so 502/540 A5 replies read invalid. 🔶 **Inferred only:** `build_bw_write_frame`'s model ("raw except BW_CMD", "DLE-aware checksum") shows the same fingerprints as the retracted 5A model -- SUB 71's "offset 0x1004" reads as length 0x0400 escaped, and Blastware escapes `03` in write data (§3 note, 2026-04-20). A write whose payload holds a bare 02/03/04/10 may be malformed; one Blastware config-write capture settles it. Not acted on. |
| 2026-10-26 (3) | §3, §7.8, §10 | **⚠ RETRACTS the 5A "non-standard frame" model; the 64 KB page bug is FIXED (measured).** A bridge recorded Blastware downloading all 8 of BE9441's events, 4 crossing a 64 KB page (`tests/fixtures/minimate-bench-10-26-26-blastware/`). **Every request** is the standard 16-byte payload with a SUM8 checksum and **every 02, 03, 04 and 10 DLE-escaped**, payload and checksum alike: 748/748 re-encode byte-identically. §10's "only 0x10 is stuffed" is half the rule. **A 5A request is an ordinary request** `[10 00 5A 00][length BE 2][address BE 4][zeros 6]`, where length is 0x0200 per chunk and the remainder for TERM. The walk: the event's start address, +0x200 at a time as plain 32-bit addresses (carrying into the page byte), then TERM at the next boundary for exactly the remainder, ending at STRT's full 32-bit end key. **Misreadings retracted:** the fixed "offset 0x1002" is length 0x0200 escaped (`10 02 00`); the "metadata pages at 0x1002 / 0x1004, global, read once per session" are the first event's own chunks at 0x0200 and 0x0400; the "11-byte params" counted the length's low byte; the "partial DLE stuffing" carve-outs were the escape rule seen half; the 16-bit counter is why a walk could not leave its page. **Verified live on BE9441:** all 8 events downloaded whole, the 4 crossings included, each matching the unit's own 0C peaks. Code `887e75d`. |
| 2026-10-26 (2) | §7.8 | **The 64 KB page bug, narrowed (measured, BE9441).** Blastware's own downloads of all 20 events (Brian, `example-events/10-25-26 - thumps`) give byte-exact ground truth. SFM's downloads of events 0, 1, 3, 4 and 10 are **byte-identical** to Blastware's. Importing Blastware's files first (the watcher route) makes SFM's downloads of the same events return `already_stored`: the unit's 0C and Blastware's file agree on (serial, timestamp). For an event that crosses a page (event 2, `0111c92c` → STRT end key `01122f06`, full 32 bits) a read-only test walk with the page byte carried (params `00 01 12 01 2c`) got a proper A5 reply for the first chunk in page 0x12, echoing `01 12 01 2c`. The second chunk, `00 01 12 03 2c`, got no reply frame: a raw 0x03 (ETX) inside the params. Page 0x11 never shows this, because event 1 skips 0x0000–0x05FF, so no counter there has a 02/03/04 byte. Every later page does. ⚠ How Blastware encodes a lone 02/03/04 inside params is unknown: §7.8 says `10 02/03/04` is kept as a literal pair, which would shift the address. A wire capture of Blastware downloading BE9441 event 2 or 19 settles it. Blastware's files are fixtures (`tests/fixtures/minimate-bench-10-25-26/blastware/`). |
| 2026-10-26 | §7.8 | **5A requests must DLE-escape a checksum that is a framing byte (measured, BE9441).** The request for chunk 0x7D06 of event 01122f06 ends `… 02 03`: a bare 0x02 checksum (STX) before ETX. BE9441 never answered it, twice on two days, and rebooted ~11 s later each time; that was the 'mid-download reboot' of 2026-10-25 (row below). Sent as `… 10 02 03` it answered in 28 ms. So did chunk 0x7F06 (checksum 0x04 → `10 04`) and 0x8B06 (checksum 0x10 → `10 10`; sent bare, that reads as DLE+ETX), and the event downloaded whole and matched the unit's peaks. Escape set {02, 03, 04, 10}: a Micromate's for every byte (251/251 THOR requests), and consistent with §7.8's de-stuffing rule (`10 02/03/04` literal). About 1 chunk request in 64 has such a checksum. ⚠ Not known: whether standard (non-5A) requests need the same. No such keyed-read checksum has been sent. Also measured on the re-run: events that end in the next 64 KB page (BE9441 events 2 and 19) read an end offset lower than their start (the known page bug); every other event downloaded whole and verified. |
| 2026-10-25 | §7.2, §7.8, §6 | **MiniMate bench check, BE9441 (S338.17, mic disabled, serial cable). SFM read its 24-entry event index, listed 20 events, and downloaded 4.** Measured: (1) **§7.2: the 0x15 serial is a C string.** `"BE9441\x00?"`: a six-character serial leaves a stray byte after its NUL. (2) **§7.8: every A5 reply echoes the address it answers at `data[2:6]`.** The metadata pages come back as `01 11 10 02` and `01 11 10 04`; sample chunks as their own address, e.g. `01 11 66 6a`. The event-1 walk fetches the metadata pages as frames 1 and 2. A non-first event's walk fetches none and goes straight from the probe to sample chunks. SFM's body builder assumed metadata pages in every stream, so every non-first event it assembled was 2 bytes short and decoded truncated; it now checks the echoed addresses. The bug was in SFM's assembly; the protocol was as already documented. (3) **§6: the unit boots when its serial port opens.** It sent `Operating System` ~3 s after the port opened (twice) and ignored a POLL sent before that. After a mid-download reboot it answered 8.8 s after its banner (one data point). (4) **The unit rebooted once mid-download.** The chunk at 0x7D06 got one stray `0x41`, then silence, then the banner 11 s later. Cause unknown, inferred not measured: battery 6.33–6.37 V, a firmware reset. ⚠ **RETRACTED 2026-10-26:** the cause is measured, and it was our request. The chunk request had a bare 0x02 checksum. See the 2026-10-26 row. (5) The event index said 24 while the header walk listed 20 full records. **Inferred:** the other 4 are monitor-log entries. Single-shot events at 4096 sps with a 5 s record give **21,504 samples per channel** (5 s record + 0.25 s pre-trigger = 5.25 s at 4096 sps), all three channels equal, peaks equal to the unit's own 0C values. |
| 2026-10-26 (5) | §7.8.9 | ✅ **The embedded event record: the instrument's trigger time, inside the 5A stream.** Every Blastware waveform file carries `00 28 05 00 ?? ?? fe 80 [trigger 8 B][stop 8 B]`, times as `dd mm yyyy(BE) 00 hh mm ss`. The trigger equals Blastware's report 1,320/1,320, the filename 7,935/7,935 and the unit's 0C record 10/10. It occurs once in the unit's own A5 payloads (8/8 events) and in SFM-only downloads (2/2): instrument data, not Blastware's. The footer's `ts2 - record time` is only an estimate, a second off on ~19%. Decoder rule, validation and an open case (3 waveform-named files the codec does not recognise) in §7.8.9. 🔶 The §7.5 `0C` "sub_code" timestamp variants look like the same 8-byte form read with its escapes. |
| 2026-10-17 | §7.6.1 | 🔶 **OPEN — the 6-byte "stable anchor" may be two settings at their defaults, not a constant.** Series IV's `0x1A` has the same field order as the S3 compliance block, and a keypad diff pass on a Micromate (UM20147) measured the bytes in the anchor's position: `[f32 BE pre-trigger, negative seconds][record stop mode, 00 00 = Fixed]`. `be 80 00 00` is exactly −0.25 s. If S3 matches — **inferred, not measured on S3** — then any S3 unit set to Record Stop Mode = Auto (a basic Blastware Compliance Setup option) or a non-default pre-trigger loses the anchor, and `client.py` silently decodes no recording mode / sample rate / interval / record time and skips them on write. No S3 capture has ever been taken in Auto stop mode (see the 2026-03-09 Auto Window rows), which would explain why the anchor never broke. To settle: one BW capture with Record Stop Mode = Auto. See `docs/micromate_protocol_reference.md` → *The `0x1A` field map from a keypad pass*. |
| 2026-08-26 | S7.6.2, S15 | **MULTI-INTERVAL HISTOGRAM BLOCKS - sub-minute intervals pack several per block.** The device always writes one minute of data per block, so a shorter histogram interval means more intervals packed into a longer block: 1 min -> 1 (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612), with `stride = 12 + n * 20`. Each 20-byte record holds 8 x uint16 **little**-endian values (peak/half-period per channel) plus a 2-word tail whose first word is `0000` on every real interval. The standard block is big-endian - the variant is not. This recovers **415 files** (216 on BE18193 at 2 s, 199 on BE9440 at 15 s) that previously decoded to nothing, and before that were being accepted by the WAVEFORM codec and returning garbage up to 400x the device-reported PPV. |
| 2026-08-25 (3) | S7.6.1, S15 | **THE WAVEFORM BODY IS A RECORD CHAIN, NOT A TAG STREAM — supersedes the segment-header model entirely.** Records are self-delimiting: `off+2` is a uint16 BE length and `next = off + 2 + len`; the chain ends on a record whose chan_id is `0x06`. `off+8` holds a 3-valued mode enum - `02 00` (14-byte header, anchors, cumulative deltas), `01 00` (10-byte, no anchors, ABSOLUTE values), `00 03` (10-byte, no tags at all, raw 12-bit absolute). **`40 NN` is an ordinary int16 BE data block of length 2*NN+2**, never a header; reading it as a 2*NN+16 header is what made walks drift, and the 'variable prefix' of 0/2/4/6/8 bytes reported earlier the same day was walker drift, exactly `4 - (old_stop - true_record_start)`. Verified: chain terminates on `06` in 1387/1388 files; all four channels equal length in **1388/1388** (was 156/1388); ASCII sample-count exact 72/75 -> **75/75**, fully exact 70/75 -> **73/75**; device PPV on a live decode **1306/1306** waveform (mean abs ratio error 0.00000) and **4458/4459** histogram. Also eliminated the walker-over-read class: 24 of those files were histograms the waveform codec was wrongly accepting. The superseded model is retained as `decode_waveform_legacy` because `micromate/idf_file.py` pins it for Thor IDFW body-offset search. |
@@ -559,8 +554,6 @@ Unit 2: serial="BE11529" trail=70 11 firmware=S337.17
> ❓ **Still unknown:** `trail[0]` is unit-specific. Does not derive from serial string via sum, XOR, or modulo. Possibly written at factory calibration. Needs a third unit or write-command capture to determine.
> ⚠ **2026-10-25 — AMENDED (measured, BE9441).** The 8-byte serial field is a **C string, not null-padded**. A six-character serial leaves a stray byte after its terminator: BE9441 sends `42 45 39 34 34 31 00 3f` = `"BE9441\x00?"`. Stripping trailing NULs alone keeps the `?`; cut at the first NUL. Every unit seen before had a seven-character serial, which fills the field exactly to the terminator.
### 7.3 Full Config Response (SUB FE) — 0x98 bytes
| Offset | Raw | Decoded | Certainty |
@@ -2248,6 +2241,74 @@ bulk stream protocol from §7.8.5. Use the `0x46` keys, not the `0x2C` keys, as
---
#### 7.8.9 The embedded event record — the instrument's trigger time, inside the 5A stream ✅ 2026-10-26
Every Blastware waveform file carries a copy of the instrument's **event record**, and it
holds the event's **trigger time to the second**. It is the instrument's data, not
Blastware's: it arrives in the unit's own 5A stream (provenance below). Found by reading a
dump in `seismo_lab.py`'s Inspector, where it sits in the trailing region the Inspector
labels "unknown", after the notes and channel blocks.
**Layout** — offsets relative to `M`, the position of the marker:
| bytes | content | measured on 7,935 waveforms (DL2 archive 6,541 + prod store 1,394) |
|---|---|---|
| `[M-6:M-2]` | `00 28 05 00` | constant, 7,935/7,935 ✅ (meaning ❓) |
| `[M-2:M]` | 2 bytes | vary; not decoded ❓ |
| `[M:M+2]` | `fe 80` — marker | 7,935/7,935 ✅. Histogram files carry `fe f5` here instead (#51) |
| `[M+2:M+10]` | **trigger** — `dd mm yyyy(BE) 00 hh mm ss` | = Blastware's report Event Time 1,320/1,320; = the filename's time 7,935/7,935; = the unit's `0C` record 10/10 ✅ |
| `[M+10:M+18]` | **stop**, same format | = the footer's `ts2` on 7,836; one second before it on 99 ✅ |
| `[M+18:M+40]` | `[+18]` `00` (7,933/7,935), `[+22:24]` `00 00`, `[+26:34]` eight `00`, `[+36]` `00`, `[+37:39]` `16 32`, `[+39]` `00` | constant; meaning ❓ |
**Relations** (7,935/7,935): footer `ts1` (session start) ≤ trigger ≤ stop; and
`(stop - trigger) - record time` lies in −3 … +6 s.
**Ambiguity:** 30 files hold a second `fe 80`; it never passes the checks below, and every
file has exactly one candidate that does.
**Provenance** (where it comes from — measured):
- **Blastware's download of 8 BE9441 events** (2026-10-26 recording,
`tests/fixtures/minimate-bench-10-26-26-blastware/`). Each event's 18-byte record, with
the 24 bytes before it and the 22 after, occurs **exactly once in the unit's own A5 reply
payloads**. Its trigger equals the unit's separate `0C` (SUB F3) record 8/8: F3 data
`[11:19]` is the same `dd mm yyyy 00 hh mm ss` form.
- **SFM's own downloads of BE9441 events 0 and 1** (2026-10-25, no Blastware anywhere). The
record is present, and its trigger = the `0C` record, 2/2.
- So it is instrument-transmitted. An event SFM receives directly carries it, with no
Blastware name involved.
**What it replaces.** The footer alone gives only an estimate. `ts2` is the stop to the
second (its byte `[4]` is `00` in all 1,330 report-paired files, so it holds no fraction),
and `ts2 - record time` is exact on 1,113/1,330 report-paired waveforms and a second late
on 217. On prod's 1,394 it is a second off on 260: 199 late, 61 early.
**Decoder** (`event_file_io._embedded_event_record`).
- **What qualifies.** A candidate counts only when it has the lead bytes, the marker, two
well-formed times (zero byte zero), `ts1 ≤ trigger ≤ stop`, a stop equal to `ts2` or one
second before it, and a length that agrees with the record time.
- **One answer or none.** Exactly one candidate must qualify. With none, or more than one,
the event keeps the footer estimate and carries a `decode_problems` entry; nothing is
guessed.
- **Names and reports are cross-checks only.** A Blastware filename is never a time source:
a disagreement is logged and the record kept. A paired report's time fills in only when
there is no validated record.
- Decoded from raw bytes with no name: every waveform the codec recognises takes the
record's time, 7,961/7,961 (DL2 6,538, prod 1,394, bench 29), with 0 disagreements
against the filename or a report. The 3 it does not recognise are the open case below.
🔶 **For the decoder audit (#53), inferred only.** The `0C` timestamp layouts documented in §7.5
look like this same 8-byte form, read without its escapes:
- the "sub_code 0x10" 9-byte form;
- the 10-byte "continuous mode" form, whose own example `10 03 10 04 07 ea 00 0f 14 11` reads
as day 3, month 4, escaped, at 15:20:17.
The early captures were all in April (month `04`, sent as `10 04`). Not changed here.
⚠ **Open:** 3 DL2 files named as waveforms (`K440I4LG.JK0W`, `K888HW07.7K0W`,
`R349KPNU.FK0W`) carry a valid record, but their body is not recognised by the waveform
codec. They are decoded as histograms and stamped with the footer start, 4 s off; `dev`
behaves the same. Prod's store has none. Tracked in #53.
## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) ✅
Fields visible in the Blastware "Compliance Setup" dialog. ✅ = byte offset confirmed in code. ❓ = not yet located in raw bytes.
+2 -229
View File
@@ -1782,36 +1782,6 @@ Do **not** retune `_GEO_LSB_IPS` — this is corroboration, not a correction.
- **Scheduler / call-home writes.** `callhome.MMB` is a file too, so it may go
through the same `0xDA` + block-write shape with a different target name.
### Write-plan dry run on a second unit and firmware line (2026-10-22)
Firmware, stated as line and version separately. UM20147: Thor firmware line
(flags `0x03`, measured 2026-10-22), version 11.0BD per the 2026-09-30 check;
UM12947: Blastware firmware line (flags `0xC5` in all 152 responses of the
seven write sessions), version 11.0CB.
2026-10-22 — UM20147 block sizes equal UM12947's: `0x1A`
content 2092 B, `0x08` 90 B, `0x2E` 28 B, `0x2C` 126 B (all CRCs good where a
CRC applies). Its dry-run plans (`bridges/mm_dry_run.py`) have the same SUB
order, offsets and data lengths as THOR's frames from UM12947: `0x96` / `0x97`
(offset `0xFFFF`, 0 B); `0x7E` @ `0x007E` 126 B + `0x7F`; `0xDA` @ `0x0100` 256 B,
`0x68` @ `0x005A` 88 B, `0x73`, `0x82` @ `0x001C` 28 B, `0x83`, `0x71` @ `0x082C`
2090 B, `0x72`. So THOR's write offsets apply to both firmware lines **as far
as size goes** (measured, one unit each; **nothing sent** -- reads only; the
opcode gate was armed throughout and refused nothing, because no write was
attempted). Not shown: that 11.0BD *accepts* these
frames. The call-home on/off plans differ in exactly one data byte (`[5]`);
the setup-rewrite `0x71` data equals the unit's `0x1A` content `[3:2090]` behind
three zero bytes.
🔶 **Unobserved:** UM20147 call-home `content[5]` reads `0x01` (THOR's UM12947:
`0x04`/`0x05`). Our "off" plan writes `0x00`, which no capture shows being
written. Unobserved; settle at the phase-4 bench.
Breadth of the reproduction (measured): across the five pushes, the `0xDA`,
`0x68` and `0x82` inputs are byte-identical (one distinct name, prefs and
trigger block), and the three no-edit `0x71` reproductions are the same frame.
So each block was reproduced from one distinct input, not five.
### ✅ `0xDA` CREATES setup files (confirmed on the device, 2026-09-24)
`TEST1.mmb` did not exist on the unit before the push. Afterwards it is
@@ -2217,13 +2187,6 @@ having: nothing else read so far reports the unit's own time.
↑ data[11]: 0x02 monitoring, 0x00 idle
```
> **Amended 2026-10-25.** There are four values now. `0x03` is a call-home
> session; see *Correction: `SUB 0x49` has a third state value*. `0x01` reads
> for about 18 s after a stop; its meaning is inferred to be a call-home attempt
> that has not connected. See *The first commands this project originated against a Micromate*.
> `0x02` was also read 2.5 s after a start, while the screen showed the sensor
> check.
**A second monitoring indicator, in a 21-byte response instead of `0x1C`'s 60.**
Different encoding from `0x1C`'s flag (`0x02` vs `0x0E`), so they are separate
fields, not the same byte read twice. For a polling client this is the cheaper
@@ -2564,28 +2527,6 @@ POLL 0x15 0x49 POLL 0x1C 0x15 0x49 0x06
0x93 0x06 0x93 0x1E 0x0A×9 ← re-walk the list
```
**2026-10-21 -- direct-by-key download equals the interleaved download (measured, one unit over USB, 5 events listed, 1 waveform compared).**
On UM20147 (`/dev/ttyACM0`), with `list_events()` having walked the cursor to the
end of the chain, `download_event(ref, chunk_size=1024)` of `055d4a82` returned
30,230 B, byte-identical to the same event fetched inside `iter_events()` at the
cursor, and to the file SFM stored through the server (30,230 B).
So `0x5A` does not need the cursor parked at the event, at least on this unit
and event; not tried on a BD unit, over cellular, or on a histogram.
`s4_download_event` was not changed.
**2026-10-21 -- in Histogram Combo, a histogram's `0x0C` peaks equal the largest
waveform recorded inside it (measured, UM20147, 2 histogram/waveform pairs).**
UM20147's list showed histogram 13:27:33 and waveform 13:27:43 with identical
peaks and PVS to the last float bit, and likewise histogram 13:28:09 and
waveform 13:59:33 (31 minutes apart, before the next histogram at 13:59:53).
Not a listing bug: the histogram file's *own* interval data peaks at vert 5,021 /
tran 735 / long 675 counts = 1.5581 / 0.2281 / 0.2095 in/s at 0.000310308 in/s
per count, the waveform's peaks exactly. The histogram's record reports the
maximum over its whole window. 🔶 Inferred: the record is finalised when the
window closes but stamped with its start, which is how it can carry the peak of
a waveform that triggered later inside it. Do not "fix" equal peaks across
such a pair.
**`SUB 0x93` → ack `0x6C`** is sent before every event, with empty params and an
all-zero ack. It is the Series IV analogue of Series III's `1E(token=0xFE)` arm
step, and it is simpler: no token, no params.
@@ -2929,58 +2870,6 @@ There is no inbound connection, no dial, nothing to accept.
to every unit continuously — 1,039 lines of it in 37 minutes. The call-home
mechanism depends on that connection existing.
> **2026-10-29 (Brian, operator-reported; not measured by us):** the watchdog's
> interval is a THOR setting. It can check every 5 s, every hour, or never. The
> 1,039 lines above were taken at whatever that THOR was set to, so "continuously"
> describes that setting, not THOR's fixed behaviour. Two things are still
> unmeasured: whether a check holds the line open afterwards or drops it, and
> how a unit's call-home reaches THOR when the watchdog is set to never (the
> modem dialling out to `ListenerAchTcp`, presumably, which this capture never
> saw used). The ring-path bench test in the parity spec now varies this
> setting on purpose.
#### THOR's logs, and what the 2026-10-29 log showed
**Location: `C:\THORDATA\Logs\` on the THOR PC** (Brian, 2026-10-29). The main
log is `thor.log.<YYYY-MM-DD>`.
Measured from that day's log (UM20147 added as a bench test unit, on a fleet-config
RX55 at `63.45.161.30`):
- **Watchdog cadence on this THOR:** per unit, `GET UNIT Connection STATUS` →
`ReadSerialNumber` → "received connected" every **~15 s**, with
`GET UNIT STATUS` → `ReadUnitStatus` reads in between.
- **`Unit_CommandOutOfRange` follows `ReadUnitStatus` for every unit** (UM20146,
UM13981, UM14133, UM6047, UM11719, UM11402, UM12420, UM20147), so it is
fleet-wide noise, not a fault of one unit. 🔶 Inferred: THOR's status read
includes a command the firmware rejects.
- **After a manual Disconnect in THOR (19:48:07), UM20147 stopped answering
anyone.** Until then THOR read its serial every ~15 s. After it, SFM's
call-ups (19:51:35, 19:52, 20:01) were accepted by the modem and got **zero
bytes** back, and THOR's own reconnect at 19:57:10 logged `Mismatch connection
found for 63.45.161.30:9034` four times, then "lost connection" at 19:57:38.
Cause not yet known (a unit reset and a modem power cycle did not restore it
by 20:01; it answered again at 20:16:51 after another reset and time). See the
parity spec's ring-path bench notes.
#### A call-home that rings on someone else's connection is lost (2026-10-29)
Measured with THOR's watchdog off and auto call-home on. SFM held UM20147's line
and sent a stop (`0x97`, 20:21:13.001); the unit answered with `RADIO RING`
instead of the ack (20:21:13.7). SFM hung up, then reconnected 0.1 s later for a
status read, and the unit answered it. The unit's screen: "connecting..." →
"call home data transfer..." for under a minute → idle. **It did not retry**,
and THOR never saw the call. The same stop from the keypad with nobody on the
line reached THOR through `ListenerAchTcp` (above).
🔶 Inferred: the unit counts the connection its ring rode up as the call and
waits for the server to run the session; a receiver that is not THOR (or not
running an ACH session) swallows the call-home. One observation.
While THOR **holds** the line (polling every ~5–15 s), a second TCP connection to
the modem is accepted but receives **nothing** (SFM: 0 bytes in 10 s), and THOR's
own reads continue to be answered -- measured 20:44:35.9.
#### THOR has a second, unused ACH path
`ListenerAchTcp` logs `Waiting for a ACH connection on :: Port 12346` — and in
@@ -2989,17 +2878,6 @@ own reads continue to be answered -- measured 20:44:35.9.
units that genuinely dial, on some other modem arrangement) but is not what a
PAD-connected Micromate uses.
> ⚠ **RETRACTED 2026-10-29 (measured):** the listener *is* used by a
> PAD-connected Micromate, whenever nothing holds the modem's session. With
> THOR's watchdog off and nobody connected, UM20147's call-home (keypad stop)
> arrived as `ListenerAchTcp - Connection accepted from 63.45.161.30:36648`
> (20:37:28.5), THOR read the serial, and `RADIO RING` then came **up that
> connection** to start the session. So both paths are real and timing decides:
> the ring rides an existing connection (10-14, THOR's watchdog), or the modem
> dials its destination (here `50.197.32.91:12345`, the office) and the ring
> follows. THOR's listener port is **12345** (Brian, 2026-10-29); the 12346 in
> the 10-14 log was that day's setup.
#### What this means for a homebrew receiver
⚠ **`bridges/mm_ach_server.py` is built on the wrong model for this deployment.**
@@ -4235,110 +4113,8 @@ assumed:
device will not stop it and the ack will not distinguish it. That guard has
to live in SFM.
## ✅ The first commands this project originated against a Micromate: start and stop on UM20147 (2026-10-25)
These were the first frames this project ever sent to a **Micromate** that
change its state. Every Micromate write before this one was THOR's, recorded
while we watched. (Series III is different: the `minimateplus` stack has sent
writes — start/stop, config push, erase, call-home config — since April 2026.)
Brian gave a go at the bench for each send.
**Setup.**
- **Unit:** UM20147, firmware `11.0BD` (Thor line, reply flags `0x03`), on USB
CDC-ACM `/dev/ttyACM0`.
- **Sensors:** none attached.
- **Active setup:** `BENCH01`.
- **Sender:** SFM's `POST /device/monitor/start|stop?serial=UM20147` (branch
`feat/series4-sfm-parity` at `b1c87ec`), with every TX frame and every
validated RX frame logged at millisecond resolution.
- **Path:** each send went through the phase-3 safety core in this order:
1. a fresh serial read;
2. a `0x49` state read;
3. the audit row written;
4. one `execute()`;
5. read back every 2 s.
### What was sent and what came back (measured)
| time (EDT) | sent | ack | ack latency | `0x49` content[0] afterwards |
|---|---|---|---|---|
| 15:43:47.430 | `0x96` `41021010009600ffff00000000000000000000a403` | `0x69`, 11 zero bytes | **464 ms** | `0x02` at the first read, 2.0 s after the ack |
| 15:45:51.922 | `0x97` `41021010009700ffff00000000000000000000a503` | `0x68`, 11 zero bytes | **116 ms** | **`0x01` on all 9 reads from +2.1 s to +18.2 s**, then `0x00` from +20.3 s |
| 15:52:42.645 | `0x97` (unit already idle; `even_if_already`) | `0x68`, 11 zero bytes | **10 ms** | `0x00`, unchanged |
| 15:53:51.871 | `0x97` (idle again, screen watched) | `0x68`, 11 zero bytes | **10 ms** | `0x00`, unchanged |
- **The frames.** Both are THOR's own bytes, offset `0xFFFF` included. The phase-2
bench question "is offset `0x0000` honoured" was not tested and does not need
to be.
- **`0x1C` `data[12]` agrees.** It read `0x00` idle before the start, `0x0E` at
the start's read-back and at the stop's preamble, and `0x00` again at +20 s.
`0x0E` is the same monitoring value UM12947 showed on 2026-09-24. `0x1C` was
not read during the `0x01` window.
- **The start's screen** showed a sensor check, then monitoring. With no sensors
attached, the check passed without complaint (Brian, watching).
- **The start's state.** `0x49` already read `0x02` at +2.5 s, so the state
byte very probably reads monitoring *during* the sensor check. That is
inferred, not measured: the check's length on screen was not timed.
Consequence: a second start sent during the check would see "monitoring" and
be skipped, not sent.
- **One histogram was recorded and closed.** The event is timestamped
15:44:01, 14 s after the start, which is roughly the length of the sensor
check. The event count went 5 → 6 at the stop (`UM20147_20261025154401.IDFH`,
7,976 B).
- Its peaks are 0.00186 in/s on all three channels, identical, because no
sensors were attached.
- Free memory fell 4,096 B at the start and another 4,096 B by the stop. The
same 4 KiB step was seen in the 2026-09-24 session.
- **The stop's screen.** The unit tried to call home right after the stop. Brian
says it always does this when taken out of monitor mode. It never connected,
because it has no modem, and it ran out of attempts. A watch of `0x49`
once a second from 15:47:19 to 15:49:50 read `0x00` throughout.
- **A stop sent to an idle unit is harmless.** It was acked in 10 ms, twice.
Nothing changed: not the state, the event count, free memory or the screen,
and there was no call-home attempt. The ~10x shorter ack suggests the
firmware skips its close-down work. This settles the spec's open question
"what does a stop-while-stopped do".
### 🔶 `0x49` content[0] = `0x01`: a fourth state value (value measured, meaning inferred)
The values are now `0x00` idle, `0x02` monitoring and `0x03` in a call-home
session (10 of 10 reads, 2026-10-14). The new one is **`0x01`, for about 18 s
right after a stop**.
**Inferred meaning: a call-home *attempt* in progress, dialling and not
connected.** It is distinct from `0x03`, a call-home *session* that has
connected. The timing fits: the `0x01` window opened 2 s after the stop, on
screen the unit was trying to call home, and it closed when the attempts ran
out.
**Not excluded:** `0x01` could instead mean "stopping, closing the record", with
the call-home attempts overlapping it. Two tests would separate them:
- a stop with call-home-after-event switched off;
- a stop on a unit whose modem connects, where the inference predicts
`0x01` → `0x03`. This fits into the ring-path Run A/B.
**What SFM does with it.** `read_run_state()` names it `unknown(0x01)`, so the
change path refuses any start or stop in that window ("never been measured --
nothing sent", HTTP 409). That is deliberate: name it only once its meaning is
measured. The stop's read-back simply kept polling through it, because `0x01`
is not idle, and the stop verified at +20 s, well inside the 60 s window.
### Audit rows (SFM `device_commands`, scratch bench DB)
All four rows read `outcome=sent`, `verified=ok`, `sent=1`, caller
`bench-brian`. Their `states` columns:
- **start:** `idle → [idle, monitoring] → monitoring`
- **stop:** `monitoring → [monitoring, 9 × unknown(0x01), idle] → idle`
- **the two forced stops:** `idle → [idle, idle] → idle`, each carrying the note
that the read-back cannot show the send changed anything.
## ⚠ Untested and unsafe-until-agreed
> ✅ **Retracted in part (2026-10-25):** the opening line below was true until
> 2026-10-25. Start and stop (`0x96` / `0x97`) have now been **originated by
> SFM** against UM20147. See *The first commands this project originated against a Micromate*. Every
> other item in this section remains never-sent.
**Nothing below has been sent to a unit by us, and nothing should be without an
explicit decision.**
@@ -4355,15 +4131,12 @@ is known; our encoder is unwritten and unproven.
`0x55`. **Destructive.** Series III's `0xA3`/`0xA2` erase-all has *not* been
seen on Series IV and may not exist
- **Start / stop monitoring** (`0x96` / `0x97`) — observed via Thor 2026-09-24,
acks `0x69` / `0x68`. ✅ **Originated by SFM 2026-10-25** on UM20147 (4 sends,
all acked and verified) — no longer untested
acks `0x69` / `0x68`
- **Scheduler enable** (`0x47`) — observed; `params[7]` semantics still unclear
Every one of these is now *observed*. **None has ever been originated by us**,
and that is the line that still matters: the wire format is known, our encoder is
unwritten and unproven. *(2026-10-25: true still of every item here except
start/stop, which SFM originated at the bench — see the retraction note at the
top of this section.)*
unwritten and unproven.
- `0x1F` (advance event pointer) — non-destructive on Series III but it does
move device state, so it is parked with the rest
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,207 +0,0 @@
# SFM phase 1c — the webapp on the serial-based endpoints, plus wrong-series safeguards
> **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:** The SFM standalone page (`sfm/sfm_webapp.html`) drives both series through the serial-based device endpoints. In addition, no MiniMate-only write or erase can reach a unit that has not identified itself as Series 3.
**Architecture:**
- **Server:** one helper refuses the legacy Series-3 write/erase routes unless the unit's own serial (read on the same connection) says Series 3.
- **Page:** the series routing and button rules live in a marked block of pure functions, tested through Node. The DOM wiring calls those functions and nothing else to build a `/device/` URL or decide a button's state.
**Tech Stack:** Python 3.10 / FastAPI (`sfm/server.py`), vanilla JS in one HTML file, pytest. Node 20 (`~/.local/bin/node`) runs the page-logic tests.
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` covers "The webapp", "Scope: the parity table" rows 1–5 and 7, and "Build phases" 1c. The design agreed with Brian on 2026-10-28 is recorded in the Global Constraints below.
## Global Constraints
- Work in worktree `~/seismo-relay-parity`, on branch `feat/series4-sfm-parity`. Never commit to `main`. Check with `git branch --show-current` before every commit.
- Run tests with `/home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider`. The baseline is **16 known failures** (15 in `test_bw_ascii_report.py`, 1 in `test_event_file_io.py`). Read the failure list before committing. A `pytest | tail` exits 0.
- **Serial optional:** with a serial, the Live tabs use the serial-based endpoints: `/device/info`, `/device/monitor/status`, `/device/settings`, `/device/events`, `POST /device/events/download`, and `POST /device/monitor/start|stop` (all with `serial=`), plus `POST /device/hangup?host=&tcp_port=`. With the serial blank, every read behaves exactly as today.
- **Series comes from the unit's reply.** The badge and every series-specific control follow the `series` field of the last `/device/info` reply, and only if its `serial` equals the typed one. A typed serial alone never enables a series-specific control.
- **Write buttons:**
- Start/stop use the audited serial path for both series.
- Config write and Call-Home write are **disabled for both series**. Their tooltips read exactly "Coming in phase 5 (#46)" and "Coming in phase 4".
- Diagnostics (erase, rescue, slow drip, blind stop) is enabled only when the confirmed series is 3.
- Hang up is shown only when the confirmed series is 4.
- **Start feedback:** while a start is in flight, show "Starting — the unit runs its sensor check first (about 35 s)". The legacy 60-second `_pollMonitorConfirm` loop is not used in serial mode.
- **Results are reported as SFM returned them:** outcome, verified, state before → after, and the first 8 characters of the audit id. HTTP error `detail` strings are shown verbatim.
- **Speed (Brian):** no new request may be added to a path unless the plan says why. The server identity check reuses the serial that `connect()` already reads. On `rescue` and `POST /device/call_home` it adds exactly one SUB 0x15 read.
- No codec, store or DB change. The legacy `/device/*` routes keep their URLs and parameters (a new optional `serial` is added).
## Review Focus
1. **A typed `BE…` serial at an address that holds a Micromate.** The server must refuse every guarded route with 409 and send no write. In the page, Diagnostics stays disabled until `/device/info` answers Series 3. Pinned by Task 1 (`test_guarded_route_refuses_a_unit_that_answers_as_series4`) and Task 2 (`controls: typed serial is not confirmation`).
2. **The serial is edited after a successful identify.** The confirmation must stop counting the moment the typed serial no longer matches. Pinned by Task 2 (`controls: confirmation drops when the serial changes`).
3. **Lower-case or space-padded serials** (`" be9441 "`) are normalised the same way the server normalises them. Pinned by Task 2 (`seriesFromSerial` and `unitQuery` cases).
4. **A start that times out (504) or reads back a mismatch (409).** The page must show the server's detail and the audit id, never "started". Pinned by Task 2 (`changeSummary` cases for `failed`/`mismatch`) and Task 5 (an error-path render).
5. **A download that is already stored** (`inserted: false`) is reported as "already stored" and still opens the stored event. Pinned by Task 2 (`downloadSummary`).
---
### Task 1: Server — legacy Series-3 writes refuse a unit that isn't Series 3
**Files:**
- Modify: `sfm/server.py`:
- `device_config` (~1107), `device_events_erase` (~1427), `device_rescue` (~1763), the `device_call_home` POST (~2066);
- `device_config_project` passes `serial` through.
- Modify: `minimateplus/client.py`: add `MiniMateClient.read_serial()`.
- Test: create `tests/test_server_series3_guard.py`.
**Interfaces:**
- Produces: `MiniMateClient.read_serial(self) -> str`. Requires an open, polled session. It runs the SUB 0x15 read (`self._require_proto().read(SUB_SERIAL_NUMBER)`) and returns `_decode_serial_number(...).serial`.
- Produces: `sfm.server._require_series3(unit_serial: Optional[str], expected: Optional[str]) -> None`. It raises `HTTPException(409, detail)` when either:
- `series_for_serial(unit_serial)` is not 3 (an unknown serial counts as not 3), with detail `f"the unit at this address answers as {unit_serial!r}, not a Series-3 unit -- nothing sent"`; or
- `expected` is given and `normalise_serial(expected) != normalise_serial(unit_serial)`, with detail `f"the unit at this address is {unit_serial}, not {expected} -- nothing sent"`.
- Each guarded route gains `serial: Optional[str] = Query(None, description=_SERIAL_DOC)`. It calls the guard right after it knows the unit's serial, and before its first write:
- `device_config` and `device_events_erase`: `info = client.connect()` → `_require_series3(info.serial, serial)`;
- `device_rescue` and `device_call_home` (POST): after `client.poll()` → `_require_series3(client.read_serial(), serial)`.
- Not guarded, and each gets a one-line comment saying why: legacy `monitor/start|stop`, `stop_monitoring_blind`, `stop_monitoring_slow_drip`, `stop_monitoring_spam`. They send only `0x96`/`0x97`, which mean the same on both series (measured 2026-10-25/27), and the rescue tools must work on a unit too wedged to answer.
- [ ] **Step 1: Write the failing tests** in `tests/test_server_series3_guard.py`. Use `monkeypatch.setattr(srv, "_build_client", factory)` as `tests/test_server_device_access.py:398` does. The fake client records every call:
- `test_guarded_route_refuses_a_unit_that_answers_as_series4[route]`: parametrise over the four routes. The fake's `connect()` returns a `DeviceInfo(serial="UM20147")`, or its `read_serial()` returns `"UM20147"`. Assert `HTTPException.status_code == 409`, and that the recorded calls contain no write method (`delete_all_events`, `apply_config`, `set_call_home_config`, `stop_monitoring`).
- `test_guarded_route_refuses_a_different_series3_unit`: the unit answers `"BE9441"`, the request names `serial="BE12599"`, so the response is 409 with `"not BE12599"` in the detail.
- `test_guarded_route_proceeds_for_the_named_series3_unit`: the unit answers `"BE9441"` with `serial="be9441 "` (normalised), and the write method is called once.
- `test_unguarded_stop_routes_send_without_an_identity_read`: `stop_monitoring_blind` (it writes through a bare `TcpTransport`; stub `srv.TcpTransport`) sends its stop frames, and nothing builds a client or reads a serial.
- [ ] **Step 2: Run them.** `…pytest tests/test_server_series3_guard.py -q` → FAIL (`_require_series3` / `read_serial` don't exist).
- [ ] **Step 3: Implement** `read_serial`, `_require_series3`, the `serial` query parameter, and the four guard calls as specified.
- [ ] **Step 4: Run** the new tests plus `tests/test_server_device_access.py` → PASS. Then the full suite → only the 16 known failures.
- [ ] **Step 5: Commit** `fix(sfm): legacy Series-3 writes and erase refuse a unit that does not answer as Series 3`.
### Task 2: Page — the device-routing block (pure functions) and its Node-run tests
**Files:**
- Modify: `sfm/sfm_webapp.html`. Add one `<script>` block, delimited by the lines `/* <device-routing> */` and `/* </device-routing> */`. It must not touch `document` or `fetch`.
- Test: create `tests/test_webapp_device_routing.py`. It extracts the block, appends `module.exports = {…}`, and runs cases through `node -e` (via `subprocess`, reading JSON on stdout). Skip with a clear reason if `shutil.which("node")` is `None`.
**Interfaces (Produces, used by Tasks 3–6):**
- `seriesFromSerial(serial) -> 3 | 4 | null`: trims and upper-cases; `UM…` → 4, `BE…`/`BA…` → 3 (prefix plus at least one more character), anything else → `null`. Mirrors `sfm/device_access/series.py`.
- `unitQuery(unit) -> string`, where `unit = {serial, host, tcpPort}`:
- serial mode: `serial=<NORMALISED>&host=<h>&tcp_port=<p>`;
- blank serial: `host=<h>&tcp_port=<p>`;
- every value goes through `encodeURIComponent`.
- `deviceUrl(action, unit, params = {}) -> {method, path}`: `path` is relative, e.g. `/device/info?serial=…`. Actions:
- `info`, `status`, `settings`, `events` → GET;
- `download` (needs `params.event_id`), `start`, `stop` → POST;
- `hangup` → POST, with no `serial` (host/port only);
- legacy actions: `storage_range`, `index`, `erase`, `rescue`, `blind_stop`, `slow_drip`, `call_home_read` (GET `/device/call_home`), `call_home_write`, `config_write` (POST `/device/config`).
`settings`, `download` and `hangup` with a blank serial return `null`, since there is no legacy equivalent. Unknown actions throw.
- `confirmedSeries(unit) -> 3 | 4 | null`, where `unit.confirmed = {serial, series}` comes from the last `/device/info` reply:
- returns `unit.confirmed.series` only when the normalised typed serial equals `unit.confirmed.serial`;
- with a blank typed serial, returns `unit.confirmed.series` from a legacy identify;
- otherwise `null`.
- `controlsFor(unit) -> {startStop, hangup, diagnostics, callHomeRead, configWrite, callHomeWrite, reasons}`, all booleans except `reasons`:
- `startStop` = serial mode and `confirmedSeries ∈ {3, 4}`;
- `hangup` = `confirmedSeries === 4`;
- `diagnostics` = `confirmedSeries === 3`;
- `callHomeRead` = `confirmedSeries === 3`;
- `configWrite` = `callHomeWrite` = `false`;
- `reasons` = `{configWrite: "Coming in phase 5 (#46)", callHomeWrite: "Coming in phase 4"}`.
- `changeSummary(body) -> string`, for a ChangeResult JSON (`action, outcome, verified, state_before, state_after, audit_id, plan`):
- `dry_run` → `"<action>: dry run — would send <subs comma-joined>"`;
- `skipped` → `"<action>: already <state_before> — nothing sent"`;
- `sent` + `ok` → `"<action>: confirmed — <state_before> → <state_after> (audit <id8>)"`;
- anything else → `"<action>: <outcome>, <verified> (audit <id8>)"`.
- `downloadSummary(body) -> string`, for an EventDownload JSON:
- `inserted: false` → `"already stored — <stored_filename>"`;
- otherwise `"stored <stored_filename>, <filesize> bytes, check: <detail.check>"`.
- [ ] **Step 1: Write the failing test file.** Each case is `(function, args, expected)` and runs as `node` evaluating `JSON.stringify(fn(...args))`. Cases that must be present:
- `seriesFromSerial`: `"UM20147"`→4, `" be9441 "`→3, `"BA123"`→3, `"BE"`→null, `"XX1"`→null.
- `unitQuery`: serial mode upper-cases and trims; blank serial omits `serial=`; a host with `&` is encoded.
- `deviceUrl`: `info` with a serial → `{method:"GET", path:"/device/info?serial=BE9441&host=h&tcp_port=9034"}`; `hangup` → no `serial`; `settings` with a blank serial → `null`; `download` carries `event_id`.
- controls (named for Review Focus 1 and 2):
- **typed serial is not confirmation**: typed `BE9441` with `confirmed:null` → `diagnostics:false, startStop:false`;
- **confirmed S3**: diagnostics true, hangup false;
- **confirmed S4**: hangup true, diagnostics false, callHomeRead false;
- **confirmation drops when the serial changes**: confirmed `{serial:"BE9441",series:3}` with typed `BE9442` → all false;
- config/call-home write always false, with the exact reason strings.
- `changeSummary`: one case per outcome, including `failed` with `verified:"not_checked"` and `sent` with `verified:"mismatch"`.
- `downloadSummary`: inserted and already-stored.
- [ ] **Step 2: Run** → FAIL (no block in the page).
- [ ] **Step 3: Implement** the block in the page, just before the existing main `<script>`'s first function. Exactly the functions above, no DOM.
- [ ] **Step 4: Run** → PASS. Full suite → only the 16 known failures.
- [ ] **Step 5: Commit** `feat(webapp): the device-routing rules as pure functions, tested through Node`.
### Task 3: Page — unit bar, series badge, Device tab and status panel, Hang up
**Files:** Modify `sfm/sfm_webapp.html`. Test: extend `tests/test_webapp_device_routing.py` with the static check below.
**Interfaces:**
- Consumes: `unitQuery`, `deviceUrl`, `confirmedSeries`, `controlsFor` (Task 2).
- Produces: a page-level `currentUnit()` returning `{serial, host, tcpPort, confirmed}`. `confirmed` is held in a module variable set only by `connectUnit()` from the `/device/info` reply (`{serial: body.serial, series: body.series}`), and cleared whenever the serial or host field changes. Also `applyControls()`, which sets every series-specific control's `disabled`/`hidden` state and tooltip from `controlsFor(currentUnit())`. Tasks 4–6 call `applyControls()` after any state change.
- [ ] **Step 1: Write the failing static test.** `test_every_device_url_is_built_by_deviceUrl`: outside the device-routing block, the page source contains no `` `${api()}/device/ `` and no `'/device/` string literal. The `deviceUrl` call sites are the only way to build one.
- [ ] **Step 2: Run** → FAIL (today's page builds them by hand).
- [ ] **Step 3: Implement.**
- A **Serial** input beside host/port, `id="dev-serial"`, with placeholder `"BE…/BA… or UM… (optional)"`.
- A badge `id="series-badge"` showing `Series 3` / `Series 4` from `confirmedSeries`, or hidden.
- `connectUnit()` and `refreshMonitorStatus()` go through `deviceUrl('info'|'status', …)`. The Device tab and status panel render `UnitInfo`/`UnitStatus` fields with "—" for null (`device_time` and `event_count` are null on Series 3).
- A **Hang up** button `id="hangup-btn"`, visible only when `controlsFor().hangup`, which POSTs `deviceUrl('hangup')`.
- Convert every remaining hand-built `/device/` URL to `deviceUrl` (legacy actions included), so the static test passes. With a blank serial, behaviour is unchanged.
- [ ] **Step 4: Run** the page tests and the full suite → PASS, only the 16 known failures.
- [ ] **Step 5: Commit** `feat(webapp): name a unit by serial; series badge from the unit's own answer; Hang up for Series 4`.
### Task 4: Page — Events tab by serial
**Files:** Modify `sfm/sfm_webapp.html`.
**Interfaces:**
- Consumes: `deviceUrl('events'|'download')`, `downloadSummary` (Task 2), `currentUnit()` (Task 3), and the existing `openSidecarModal(dbEventId)` (~line 2780).
- [ ] **Step 1: Implement.** In serial mode, the Events tab lists `EventList.events`: index, `timestamp`, `record_type`, PVS and peaks, or "—". Each row has a **Download** button that POSTs `deviceUrl('download', unit, {event_id})`, shows `downloadSummary(body)` in the status bar, and then calls `openSidecarModal(body.db_event_id)` when it isn't null. HTTP errors show `detail` verbatim. With a blank serial, the existing legacy list and waveform behaviour is unchanged.
- [ ] **Step 2: Verify** the page tests and the full suite → only the 16 known failures. The bench check covers the live behaviour.
- [ ] **Step 3: Commit** `feat(webapp): list and download events by serial, for both series`.
### Task 5: Page — Start/Stop through the audited path
**Files:** Modify `sfm/sfm_webapp.html`.
**Interfaces:**
- Consumes: `deviceUrl('start'|'stop')`, `changeSummary`, `controlsFor().startStop` (Task 2).
- [ ] **Step 1: Implement.**
- In serial mode, `startMonitoring()`/`stopMonitoring()` `confirm()` with `"Start monitoring on <serial>?"` / `"Stop monitoring on <serial>?"`.
- Then POST once (never retried). While a start is in flight, show "Starting — the unit runs its sensor check first (about 35 s)".
- Show `changeSummary(body)` for any JSON body, including a 409/502 ChangeResult; show `detail` verbatim for an error without one (e.g. 504).
- Then call `refreshMonitorStatus()`.
- Buttons are enabled only by `controlsFor().startStop`.
- In serial mode the legacy `_pollMonitorConfirm` isn't called. With a blank serial, the legacy behaviour is unchanged.
- [ ] **Step 2: Verify** the page tests and the full suite → only the 16 known failures. Task 2's `changeSummary` cases cover the 409/`mismatch` and `failed` bodies; the bench check covers the live behaviour.
- [ ] **Step 3: Commit** `feat(webapp): start/stop through the audited serial path, with the honest result`.
### Task 6: Page — Config, Call Home and Diagnostics gating
**Files:** Modify `sfm/sfm_webapp.html`.
**Interfaces:**
- Consumes: `deviceUrl('settings'|'call_home_read'|…)`, `controlsFor()` (Task 2), `applyControls()` (Task 3).
- [ ] **Step 1: Implement.**
- **Config tab:** in serial mode, **Read** shows `UnitSettings` (setup name, record mode, sample rate, record time, histogram interval, geo trigger, notes, with "—" for null). **Write** is disabled for both series, with the tooltip from `reasons.configWrite`.
- **Call Home tab:** read enabled only by `callHomeRead`; for Series 4 it says "Not yet available for Series 4". Write is disabled, with `reasons.callHomeWrite`.
- **Diagnostics:** every button is enabled only by `controlsFor().diagnostics`; the erase confirmation stays as is. Diagnostics requests pass `serial` when one is typed, so the server guard (Task 1) checks it as well.
- With a blank serial, the legacy reads are unchanged, while writes and erase follow `controlsFor`. A legacy identify (blank serial) that answers as BE… confirms Series 3.
- [ ] **Step 2: Verify** the page tests and the full suite → only the 16 known failures.
- [ ] **Step 3: Commit** `feat(webapp): config and call-home writes wait for phases 4-5; Diagnostics only for a confirmed Series-3 unit`.
### Task 7: Docs
**Files:** `CLAUDE.md` (the SFM REST API section, and "Where things stand"), `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` (the 1c entry in Build phases).
- [ ] **Step 1:** Document:
- the legacy-route Series-3 guard (which routes, why the stop tools are exempt);
- the page's serial mode;
- the `node` requirement for `tests/test_webapp_device_routing.py`.
No CHANGELOG (feature branch).
- [ ] **Step 2: Commit** `docs: phase 1c -- the webapp by serial, and the Series-3 guard on legacy writes`.
**After Task 7 (controller, with Brian, not an implementer task):** a bench pass on BE9441 and UM20147, through the bridge or cellular:
- identify;
- status;
- settings read;
- events list and one download each;
- one audited start/stop each (Brian's go per send);
- for the Micromate, Hang up;
- Diagnostics disabled on UM20147, and enabled only after BE9441 identifies.
@@ -1,974 +0,0 @@
# SFM: Series-4 parity and a device safety layer — design
**Date:** 2026-10-20 · **Branch:** `feat/series4-sfm-parity` · **Status:** draft for review
**Decided with:** Brian, in conversation 2026-10-19/20.
## In plain terms
SFM can already *read* a Micromate almost as well as it reads a MiniMate, but
only through the Python library and bench scripts. SFM's web endpoints still
only speak Series 3. This design does three things:
1. Gives Series 4 the same everyday jobs in SFM that Series 3 has: identify a
unit, check its status, read its settings, list and download events,
start/stop monitoring, and change its settings.
2. Adds a **safety layer** every device request goes through. It makes sure a
command only reaches the unit it was meant for, logs every change, and
checks every change by reading the unit back.
3. Lets SFM **stay on the line** with a Micromate. It calls up once, confirms
the serial, and keeps the connection open for later commands instead of
reconnecting each time.
**The guiding principle (Brian): talking to a Series 3 unit and talking to a
Series 4 unit is the same for the user.** It is the same screens, the same
endpoints, the same way of naming a unit, and the same shape of answer. The
only visible difference is the serial (`UM…` vs `BE…`) and the settings each
model has. The differences live underneath, in one adapter per series.
It does **not** cover the emergency tools (runaway-unit stops, rescue, erase),
the call-home receiver, or anything async. Those come later, as features
shared by both series.
**Production reach, stated honestly:** while THOR is set to stay connected to
production Micromates, a modem's single connection is taken. SFM can't reach
those units until THOR lets go or SFM takes over call-home. In this phase,
Series-4 SFM is for the bench and for units THOR is not holding.
---
## Decisions
| decision | why | who |
|---|---|---|
| **One user experience for both series** | the user's method is identical; only the serial prefix and each model's settings differ; adapters absorb the rest | Brian |
| Match **jobs**, not endpoints | some Series-3 endpoints only exist to work around Series-3 quirks | agreed |
| **No Series-4 emergency tools** yet (runaway stop, rescue, erase) | Micromates rarely need them | Brian |
| The series comes from the **serial prefix**: `UM` = Micromate, `BE` = MiniMate Plus, `BA` = Blastmate | the prefixes are definitive, so there is no probing | Brian |
| Before any **write**, confirm the unit that answered is the one named | SFM addresses units by IP; a moved modem or stale IP means a different unit answers | agreed |
| **Synchronous** endpoints for now; async later, for both series together | parity first, then shared features | agreed |
| **No library of setup files on the PC** (unlike THOR). The unit's own settings are the truth: SFM reads them from the unit, and verifies every push by reading the unit back | THOR keeps one copy of each setup on the PC and another on the unit, linked only by file name. Nothing checks the contents match, so the PC's `test2` and the unit's `test2` can say different things | Brian |
| **Sessions for Series 4 now; Series 3 only after a bench test** | THOR holds Micromate lines daily without harm; a MiniMate's hangup/DCD behaviour is untested | Brian |
| Audit log in **SFM's database** (new table) | Terra-View can show it; it fits the existing `CREATE TABLE IF NOT EXISTS` pattern | proposed |
---
## Scope: the parity table
Rows 8 and 11 of the original inventory (runaway stops, rescue/erase) are out
of scope by decision. Row 6 (monitor log) moved to the parking lot: it is its
own piece of work, together with call-in monitor-log ingest.
| # | job | Series 3 in SFM today | Series 4: protocol status | Series 4 in this phase |
|---|---|---|---|---|
| 1 | Identify a unit | `/device/info` (walks the whole chain, slow) | implemented: `connect()` | dispatch to the Micromate client |
| 2 | Quick status (monitoring, battery, memory, clock) | `monitor/status`, `storage_range`, `events/index` | implemented: `get_state()`; the `0x06` event count is decoded only in the bench tool | same endpoints; move the count decode into the client |
| 3 | Read settings | compliance in `/device/info`; `GET /device/call_home` | `get_setup()` implemented and verified on hardware; call-home: enable + dial string observed, rest unmapped | setup in full; call-home returns enable + dial string + raw |
| 4 | List events | `/device/events` (downloads every event to list them) | implemented, and cheap: the chain walk returns sizes | the same event-list shape as Series 3, each event carrying an `event_id` |
| 5 | Download an event | `/event/{i}`, `/waveform`, `/blastware_file` | implemented: streams the `.IDFW`/`.IDFH` itself, with a decode self-check | the same download and save-to-DB actions as Series 3. Underneath, Series 4 saves through `/db/import/idf_file` |
| 7 | Start / stop monitoring | `monitor/start`, `monitor/stop` | mapped, identical to Series 3 (`0x96`/`0x97`, acks `0x69`/`0x68`); never sent | **first write.** Verify with `0x49` state |
| 9 | Change call-home settings | `POST /device/call_home` | write mapped (`0x2C` → `0x7E`/`0x7F`, same as Series 3); field map mostly unknown | enable/disable only; the rest waits for the THOR round |
| 10 | Change recording settings | `POST /device/config` | sequence mapped (`0xDA` → `0x68/73` → `0x82/83` → `0x71/72`); no encoder | read-modify-write, stop → push → restart, verify with `get_setup()` |
---
## Architecture
### One door for every device request
A new module, `sfm/device_access.py`, sits between the `/device/*` handlers and
the two device libraries. No handler opens a transport or picks a library
itself any more.
```
/device/* handler
│ (serial, address, action, tier)
▼
device_access ── series from serial prefix ── session / per-unit lock
│ │ │
│ ▼ ▼
│ minimateplus (S3) or micromate (S4) audit table
▼
read-back verification (changes only)
```
- **Naming a unit is the same for both: `serial` + address.** The prefix picks
the adapter: `UM` → Series 4 (`micromate`); `BE` or `BA` → Series 3
(`minimateplus`); any other prefix → 422. A request with no `serial` is
treated as Series 3. That is a **legacy path** kept only so existing scripts
keep working; the webapp and every new caller always send `serial`.
- **One contract.** Same `/device/*` paths, same request parameters, and
**the same response models for both series**:
- `UnitInfo`, `UnitStatus`, `UnitSettings`, `EventRef`, `ChangeResult`
- Anything only one series has goes under a `detail` object inside the same
model, never as a different top-level shape. `"series": 3 | 4` is
informational.
- **Events have one identity.** An opaque `event_id` string from the event
list, passed back to download it. Underneath it is Series 3's position or
Series 4's device key, plus the serial; the user never handles either.
- **Not-yet-supported is uniform.** If one series can't do something yet,
the endpoint still exists and answers **501 "not supported for Series N
yet"**. It is never a missing route or a different call.
- **Work separate from HTTP.** Each operation is a plain function taking the
session. The handler is a thin wrapper, so making an operation an async job
later means changing the wrapper, not the operation.
### Adapters
Each series implements the same operation set behind `device_access`:
| operation | Series 3 adapter | Series 4 adapter |
|---|---|---|
| `identify` | STARTUP + serial + config | `connect()` |
| `status` | `0x1C` (+ `0x06`) | `get_state()` + `0x06` count |
| `read_settings` | `0x1A` compliance decode | `get_setup()` |
| `list_events` | today's walk | chain walk (cheap) |
| `download_event` | 5A → Blastware file | 5A → `.IDFW`/`.IDFH` |
| `start` / `stop` | `0x96` / `0x97` (exists) | `0x96` / `0x97` (new) |
| `read_call_home` / `set_call_home_enabled` | exists | `0x2C` / `0x7E`+`0x7F` |
| `push_settings` | `/device/config` path (exists) | setup push (new) |
| `call_up` / `hang_up` | connect-per-request underneath, until the bench test | held session |
Each adapter maps its native data into the shared models. `UnitSettings` keeps
the fields both series have under the same names and units: record mode,
sample rate, record time, histogram interval, trigger levels, the notes as
label → value. Model-specific fields go under `detail`.
**Requests that include `serial` get the shared models; requests without it
keep today's Series-3 shapes, unchanged.** Nothing breaks in between: the
webapp moves to `serial` in phase 1c, and the old path retires after that and
after `watch_unit.sh` moves. Terra-View does not call `/device/*`. The
emergency endpoints (`stop_monitoring_*`, `rescue`, `events/erase`) are not
touched and stay Series-3 only; a `UM` serial gets 501.
### The webapp
The same screens for both series. You name a unit by serial + address (today
it takes host/port only), and the series shows as a badge, nothing more. Read
panels for both series land in phase 1; each write button appears for Series 4
in the phase that adds that write.
### The safety layer
**Tiers.** Every operation declares one:
| tier | examples | what the layer does |
|---|---|---|
| read | info, status, setup, events, download | runs; no identity check |
| change | start/stop, call-home, setup push | identity check → audit → send → **read back** → audit the result |
| destructive | delete, erase (none in this phase) | everything above + the caller must send the unit's serial as `confirm` |
**Identity check (changes only).** Before the first change in a connection,
compare the serial the unit reports with the one requested; on a mismatch,
refuse (409) and send nothing. Series 4 already reads the serial in
`connect()`. A Series-3 change adds one serial read (`SUB 0x15`), about one
round trip.
**Opcode guard.** A send-side check that refuses known cross-series
collisions. It starts with **`0xA2`**, which is CONFIRM ERASE on Series 3 and
"end call-home" on Series 4. This phase never sends `0xA2`; the guard makes
that impossible by accident. The table of colliding opcodes lives in one
place.
**One connection per unit.** A per-unit lock keyed by address
(`tcp:host:port` / `serial:port`). A request for a busy unit waits up to
**20 s** (configurable; under Terra-View's 60 s proxy timeout), then gets
**423 "unit busy"** instead of opening a second connection. This applies to Series 3 as well. The webapp's Diagnostics
refresh currently fires three device requests at once against a modem that
allows one; under the lock they queue.
**Read-back verification.** A zero-data ack has never been proof that a write
applied. Every change is followed by a read:
- start/stop → `0x49` state: start expects `0x02`, stop expects `0x00`. Record
the value either way; `0x03` is the in-call-home state
- call-home → re-read `0x2C` and compare the edited bytes
- setup push → `get_setup()` and compare every field that was set
A mismatch is reported as a failed change (and audited as one), even if the
ack was clean.
**Errors that say what happened.** Distinct responses for:
- 503: couldn't connect
- 504: connected but the unit didn't answer
- 423: unit busy
- 409: wrong unit
- 422: bad input
- 502: the reply was malformed
Today 502 covers both of the first two.
**Audit table.** New table `device_commands`, created on startup like the
others. It is additive, but still a schema change, so the changelog says so.
One row per change attempt:
| column | content |
|---|---|
| `ts`, `serial`, `series`, `address` | who and where |
| `action`, `tier` | e.g. `monitor_stop`, `change` |
| `request` | parameters, plus hex of what was sent |
| `ack` | reply summary |
| `verified` | read-back result: `ok` / `mismatch` / `not_checked` |
| `outcome`, `error` | final result |
| `caller` | best-effort origin (`webapp`, `terra-view`, `script`) |
Reads are not audited.
### Sessions
1. **Call up.** Connect, `connect()` (POLL / SERIAL / STATE), identity check
against the requested serial.
2. **On the line.** Requests for that unit run in turn on the same connection,
behind the per-unit lock.
3. **Keep-alive.** A POLL every 60 s while idle. The ACEmanager TCP idle
timeout is 2 min.
4. **Hang up.** On `POST /device/hangup`, after 5 idle minutes, or on any
transport error. A reconnect is a new session with a new identity check.
5. **Ring safety.** If `RADIO RING` arrives on an SFM session, log it and hang
up **immediately**. Until SFM is the call-home destination, the unit's
retry should reach THOR. 🔶 *Inferred:* the unit retries; its `0x2C`
retries field reads 3.
**Call up and hang up are the same for both series.** Underneath, the
Series-3 adapter keeps today's connect-per-request behaviour until the bench
test under *Testing*; the user sees the same actions either way.
### Series-4 write path
**Encoder.** Extend `micromate/framing.py`:
- a request builder that carries a data section
- the same escape set `{02,03,04,10}`, applied to data, params and checksum
- plain SUM8 of the destuffed payload (*not* Series 3's write format)
Rules: `micromate_protocol_reference.md` → *The escape set — exactly four bytes*,
*Checksum — plain SUM8 of the de-stuffed payload*, *Write-frame destuffing*.
**Dry run.** Every Series-4 write accepts `dry_run=true`. It returns the exact
frames it would send and sends nothing. The first live send of each write is
reviewed this way first.
**Per operation:**
| operation | frames | verify | open questions it settles |
|---|---|---|---|
| start / stop | `0x96` / `0x97`, offset `0xFFFF`, zero params | `0x49` | the ack when already in that state |
| call-home enable/disable | read `0x2C` → `0x7E` (126 B content, offset `0x007E`) → `0x7F` | re-read `0x2C` | none new; bit 0 of `write[5]` |
| setup push | read `0x08`, `0x2E`, `0x1A` → `0xDA` (name) → `0x68`/`0x73` → `0x82`/`0x83` → `0x71`/`0x72` | `get_setup()` | the offset rule; whether `0x68`/`0x82` are needed |
**Setup push, details:**
- Read-modify-write of **all three** blocks, as THOR appears to do.
🔶 *Inferred from two captures:* `0x68` = the preferences content with
`[0:3]` zeroed; `0x82` = the `0x2E` content with `[0:3]` and the CRC slot
zeroed; `0x71` = the `0x1A` content `[0:2090]` with the length echo zeroed.
- Offsets come from THOR's observed constants. 🔶 The hypothesis "offset =
the read block's length + 2" fits all four, but each has been seen at one
size only.
- The edited fields come from `MicromateSetup` and are written back at the
offsets `setup_block.py` already uses. Only fields graded **measured** may
be edited.
- Sequence: stop monitoring (if running) → push → restart (if it was running)
→ verify. THOR's "must be idle" is policy, not the device, but stopping
first removes a variable from the first live write.
- ⚠ **Edit-buffer hazard.** `0x1A` reads the keypad's unsaved edits, so a
read-modify-write taken while someone is in the menu would commit them.
This can't be detected from the wire; it is documented in the endpoint and
audited.
- **Target file:** the active setup, overwritten in place, by default. A
named target is allowed, but overwriting a *non-active* setup or
`factory.MMB` is untested, so it is refused in this phase.
---
## Testing
**Offline (CI-capable):**
- **Frame reproduction.** The new encoder must reproduce THOR's captured write
frames byte for byte: `0x96`/`0x97`, `0x7E`/`0x7F`, and the full setup push,
from the 9-24 / 9-25 / 10-14 captures. This is the same method that proved
the reads (218/218). The needed frames are copied into force-added fixtures,
since `bridges/captures/` is gitignored.
- **Safety layer on fakes:**
- series by prefix
- identity mismatch → 409, nothing sent
- `0xA2` refused
- lock → 423
- read-back mismatch → failed change
- audit row written for every change attempt
- RADIO RING → session ends
- **Endpoints** through FastAPI's `TestClient` against the scripted transport
already used in `tests/test_micromate_client.py`.
- **Contract tests.** The same test, run against both adapters with fakes,
asserts that each job returns the same model with the same field names and
units. A field present for one series and absent for the other is a test
failure unless it lives under `detail`. This is the test that keeps the
guiding principle true as the code grows.
**Bench (UM20147, with Brian):** each write's first live send follows the same
protocol:
1. Dry run.
2. Review the frames.
3. Send once, with a capture running.
4. Read back.
5. Write the result into the reference.
Order: stop/start → call-home off/on → setup push of one field → setup push of
several fields.
**Series-3 session test (before Series-3 sessions are built):** hold a call-up
session open to a MiniMate that is monitoring, for several minutes. Record:
- does it keep monitoring (does an event still record)?
- after hangup, is it monitoring?
- does it behave differently on an RV55 with the DCD issue?
---
## Build phases
Each safety piece arrives with its first real use, so nothing sits untested.
1. **One contract, reads only.** `device_access.py`, the two adapters, the
shared models, series selection, the per-unit lock, the error mapping, and
sessions with ring safety. Rows 1–5 for **both** series through the same
endpoints. **No writes.** Split into three plans:
- 1a. The foundation plus identify / status / settings for both series.
- 1b. Event list and download for both series (rows 4–5). Decided with
Brian 2026-10-21:
- **MiniMate events are listed from their headers** (`0A` + `1E` arm +
`0C` + `1F` browse, no `5A`) instead of downloading every event to list
it, and one event downloads without the ones before it. It reuses the
bypass `skip_waveform_for_events` already takes, so no new command
reaches the wire. The legacy serial-less `/device/events` keeps its
full-download walk. 🔶 Unproven on a unit: **a MiniMate bench check is
owed before this branch merges.** Its scope (final review,
2026-10-21):
- a list of three or more events, confirming `1F(browse)` advances
after a `1E(arm)` without `1F(arm)`;
- a non-first event;
- a histogram-mode event, capturing its `0C` (which would let Series
3's `record_type`, `null` today, be decoded);
- an event past 64 KB, expecting the named 502;
- a stale-id download, confirming no `5A` goes out;
- a download of an event Blastware's call-home already delivered (one
waveform, one histogram), expecting `already_stored`. This is the
only way to measure that Series 3's (serial, timestamp) agrees
between the unit's `0C` and the watcher's import; if it does not,
a download silently stores a duplicate row (never a downgrade).
Measured for Series 4: 1,016/1,016 watcher imports found by the
lookup (2026-10-21).
- a dropped reply, via `bridges/mm_link.py`-style fault injection.
**First run, 2026-10-25, on BE9441** (S338.17, mic disabled, serial
cable). It found four bugs; all four are fixed with tests built on its
logged bytes (`a8cc516`, `352f694`, `75d79ec`, `36f4e5d`, `d73a27d`).
- ✅ **List: 20 events,** in order, with distinct keys. The header walk
advances.
- ❌→✅ **A non-first event:** stored 2 bytes short, so it decoded
truncated. The body builder assumed metadata pages in every stream.
Fixed. A Series-3 download is now checked against the unit's own
peaks, so this class of bug is refused rather than stored.
- ❌→✅ **The first request after the port opens failed.** The unit
boots on connect, and its banner came ~3 s after the POLL had already
gone out. Fixed: startup waits for a unit it sees booting.
- ❌→✅ **A reboot mid-download stored a partial event as a success.**
This was the dropped reply, occurring live. Fixed: a one-event
download is whole or it is an error.
**Re-run, 2026-10-26, same unit, fixes in place:**
- ✅ Identify: the unit booted on connect and SFM waited for it.
- ✅ Events 0, 1, 3, 4 and 10 downloaded whole and **verified**.
Events 0 and 1 are byte-identical to their fixture checksums.
- ❌→✅ **Event 3 failed again at chunk `0x7D06`, the same address
both days.** The request's checksum was a bare `0x02`, which the
unit reads as STX; it never answered, and rebooted ~11 s later. That
was the "mid-download reboot". Escaped (`10 02`) it answered at once
(`d56dde7`).
- ✅ **The 64 KB page boundary:** events 2 and 19 cross it, and are now
refused by name (502) before any chunk (`bf9e32c`). The page bug
itself remains.
- ✅ **Stale id:** 409 after a header walk, with no 5A sent.
- ✅ **A repeat download:** `already_stored`, nothing written.
- ✅ **Against Blastware's own files** (Brian's downloads of all 20
events): SFM's events 0, 1, 3, 4 and 10 are **byte-identical** to
Blastware's. Importing Blastware's files first through the watcher
route makes SFM's downloads return `already_stored`, with no
duplicate rows.
- ✅ **The 64 KB page bug is FIXED (`887e75d`).** A recording of
Blastware downloading all 8 events (4 crossing a page) showed every
request escapes 02/03/04/10, and that a 5A request is an ordinary one
carrying a length and a 32-bit linear address. Live on BE9441, all 8
events downloaded whole and verified, the 4 crossings included.
Review follow-ups: the chunk cap is sized from STRT (a caller's 128
cut events past ~66 KB short, e.g. large histograms), a misread STRT
is refused, TERM only for a true tail.
- ✅ **A histogram event, over 66 KB (2026-10-26 evening).** BE9441,
2 s intervals, 4,096 sps, 3,398 intervals, 71,106 B: 139 requests and
two 64 KB crossings. SFM's download (by serial, through the bridge)
is byte-identical to Blastware's file, as is the 59 KB waveform. The
mic-off histogram was refused ("decodes as neither") until #47 (on dev)
reaches this branch. Fixture `minimate-bench-10-26-26-histogram/`.
- ✅ **Stop through the new path (2026-10-26 18:53).** Brian's go. The
flag read 0x0B (histogram monitoring); SFM had shown "not monitoring"
and refused the state as unknown until `d990466` (0x0B measured; the
status also misread an escaped 04 in free memory). The stop frame was
Blastware's bytes; it was acked 0x68 and read back idle, audit
`c9c17128`. No call-home attempt after it.
- ✅ **Start through the new path (2026-10-27 00:12).** Brian's go;
idle → monitoring, verified, audit `cb540970`, 36.7 s; the stop that
followed verified too (`2618c81a`). Two earlier starts were acked and
the unit recorded, but their read-backs went unanswered: a bare 0x1C
(`9886422` added the wake), then a single wake sent 2 s in, inside the
~30 s sensor check (`ca5c401`: a start's first read waits 30 s, then the
wake repeats every 5 s up to 60 s). A third was cancelled at the
keypad mid sensor check; SFM read it back honestly as a mismatch
("unit reads idle", 30 reads), audit `b019ae6d`.
- 🔶 **A stop starts a call-home when auto-call-home is on** (Brian,
2026-10-27): stopping by command or keypad makes the unit call home and
upload its events + MLG, which can take minutes. UM20147's `0x01` for
~18 s after a stop (10-25) fits; BE9441 never called home (ACH
presumably off). For SFM: after a stop the read-back may meet a
call-home state, a ring, or silence, and on cellular the unit contends
for the modem's one TCP session SFM may be holding. **Series 3's 0x1C
value during a call-home is unmeasured** -- the change path would
refuse it as unknown. To measure: a MiniMate stop with ACH on, through
the bridge.
- ⚠ **MiniMate config push (#46): framing fixed (`b5037b0`), NOT
usable yet.** Review 2026-10-27, measured on recorded reads: (C1)
`read_compliance_config` keeps three escape bytes from its reply
headers, so every real config is refused -- now before any frame is
sent (`push_config_raw` checks all four blocks first); (C2) fixing that
read alone lets the encoder write some fields to the wrong bytes while
the image still passes the N+2 guard (e.g. 4,096 sps written as 4,112).
The rework: read the compliance block logically (reply page bytes +
data, unescaped), encode at the measured logical offsets (mode [5],
rate [6:8], interval [8:10], record time [18:22], trigger Tran+30,
alarm Tran+38) -- with #48 --, diff-check that only the requested
fields changed, pin N per SUB, refuse unless 0x1C reads idle, give
`POST /device/config` the start/stop safeguards, and test
`apply_config` from recorded replies. Review findings I2-I4, M1-M4
are in the #46 thread.
- Still owed:
- **before merging to dev, align `persist_download`'s already-stored
check with what v0.32.0 shipped** (dev `04acb99`; restamp `5737168`,
then `3a6df9d` fix/waveform-time-from-record). A Series-3 waveform's
time comes from the unit's **embedded event record** in the 5A stream
(`00 28 05 00 ?? ?? fe 80 [trigger][stop]`,
`event_file_io._embedded_event_record`), which SFM's own downloads
carry too; the filename is a cross-check only, never a fallback.
`Event.timestamp_source` says which ("event_record" / "report" /
"footer" / "estimate"). Mirror the DB rules: match by stored file
as well as (serial, timestamp) (`SeismoDb._restamp_by_file`), and an
**"estimate" time never matches, moves or duplicates a row**
(`SeismoDb._estimate_guard`). Take the semantics from the merged
code. Expect a trivial conflict at the top of the Series-III
reference's changelog table (dev added 2026-10-26 (5)).
- a dropped reply via fault injection. It happened for real on
10-25, but that was our checksum bug, not a lossy link;
- ~~whether standard (non-5A) requests need the same checksum
escape~~: settled 2026-10-26. Every request escapes 02/03/04/10
(748/748 Blastware requests), and `build_bw_frame` now does.
- **Download = fetch, check, store** in SFM's database, the same as
Series 3's `blastware_file` route, and returns the stored row's id. The
file and waveform are then served by the existing `/db/events/{id}/…`
routes. The database matches on (serial, timestamp), so storing an
event already stored, including one THOR's watcher forwarded, ~~refreshes
the row instead of duplicating it~~. **Changed by the final review
(2026-10-21):** it returns the existing row and writes nothing
(`inserted: false`, `detail.already_stored: true`). Never merge: the
watcher's copy, with its paired report, is the richer one, and a
refresh measurably downgraded it (PVS, project strings and ZC
frequencies went NULL).
- **`event_id` = `<serial>:<key>:<YYYYmmddHHMMSS>`.** Both series reuse
keys (after an erase, and across Micromates), so a download whose key
now holds a different event fails with 409 instead of fetching it.
- **Micromate downloads walk to the event first** (the only order captured
from THOR), with THOR's 1,024-byte chunks.
- 1c. **The webapp:** serial + address, and the same read panels for both
series.
- ~~**HARD PREREQUISITE:** before any poller or webapp sends `serial`, add a
per-address cool-down after a RADIO RING~~ -- **changed 2026-10-23
(Brian): test first, build only if needed.** Before any poller or webapp
sends `serial`, run the ring-path bench test under *Open questions this
design leaves for the bench*. If Run B shows a poller keeps the call
from reaching THOR, add the per-address cool-down: call-ups to that
address answer 503 + `Retry-After` until it expires, and
`POST /device/hangup` clears it, with its length taken from Run A. If
THOR gets the call anyway, no cool-down is needed.
- **Built 2026-10-29** (plan `docs/superpowers/plans/2026-10-28-sfm-phase1c-webapp.md`).
A Serial field beside host/port; with one, identify, status, settings
(read-only), events (a Download per row) and audited start/stop go
through the serial routes for both series, and Hang up shows for a
Series 4. Series-specific controls follow the unit's own `/device/info`
answer and drop when the serial, host or port is edited; config and
call-home writes are off for both series until phases 5 and 4;
Diagnostics needs a confirmed Series 3. Without a serial the page reads
as before. The rules are pure functions in one marked block, tested
through Node (`tests/test_webapp_device_routing.py`).
**Server side, the same phase:** the legacy Series-3 writes and erase
(`/device/config`, `/config/project`, `/events/erase`, `/rescue`,
`POST /device/call_home`) refuse 409 before any write unless the unit
answers as Series 3 (and as the named unit, given `serial=`). The stop
tools stay exempt: 0x96/0x97 mean the same on both series.
- **Bench pass 2026-10-29 (BE9441 and UM20147, each on its own modem):**
identify, status, settings, list, one download, start and stop through the
page on both series. Sixteen findings, listed under *Left open by the 1c
bench* below.
- **Ring path, 2026-10-29 (measured; details under *Open questions ... for
the bench*):** with THOR's watchdog off, a call-home **reaches THOR** when
nobody holds the line (Run 0), and **is lost** when SFM holds it (Run A):
the unit takes SFM's connection for the call, sits in "call home data
transfer", times out, goes idle and does not retry. With THOR polling, SFM
cannot reach the unit at all and does not disturb THOR (A2, step 1).
The 5-minute Micromate line hold makes SFM a call-home sink whenever THOR
is not holding the line; a cool-down alone would not help (the unit does
not retry).
✅ **Decided 2026-10-29 (Brian): keep the hold as it is for now** -- not
expected to be a problem in practice -- and the long-term fix is **SFM
handling auto call-ins itself** (the ADR 0003 call-in server). This
settles the 1c ring-path merge gate; Run B (a poller in THOR's reconnect
gap) stays open, not blocking.
- Of the items parked for 1c below: **CORS ordering** does not bite the
page, which SFM serves itself (same origin); the **Series-4 mic** is not
shown (the event list shows geophone peaks only). The rest are server-side
and stay open.
2. **Encoder + opcode guard + dry run + frame-reproduction tests.** Still
nothing sent.
(2026-10-22) "Dry run" in this phase means the **write plan**: the exact
frames, in order, with their expected acks, built from the unit's own reads
(`micromate.writes`), plus a bench tool that prints one from a live unit's
reads (`bridges/mm_dry_run.py`). Each write endpoint's `dry_run=true`
arrives with that write in phases 3-5 and returns the plan. The opcode
guard is a **send-side gate** in `MicromateProtocol._send`: every write SUB
is refused unless the connection was built with it allowed (none is, in
this phase), and `0xA2` is refused always.
3. **Start/stop monitoring** (row 7): the first live write, at the bench.
Brings the identity check, the audit table and the read-back framework.
- **Preconditions from the phase-2 final review (2026-10-22):**
- **Write permission is scoped to one call, not a connection.**
`MicromateProtocol.execute(plan)` is the only write path: it transmits
exactly that plan's frames and nothing else. The connection's own
`allowed_writes` stays empty -- a held `Series4Session` lives for
minutes, and a grant made at call-up would outlive the request.
- **A code-reviewed ceiling** in `micromate/opcodes.py` lists the write
SUBs any code may transmit: `{0x96, 0x97}` in this phase, each later
phase adding its own. Delete (`0xA8`/`0xAA`), raw file writes
(`0x8D`/`0x8E` -- they could reach the modem settings) and `0xA2` are
enabled only by a spec change.
- **A write is never retried.** `DeviceAccess._dispatch`'s retry-once
refuses change-tier operations structurally, not by comment.
- **Build the plan inside the unit lock, on the same line, right before
sending.** A plan returned by an earlier dry run is never transmitted;
optionally the dry run returns a digest the live call must echo.
- **Read state first** (`0x49` for start/stop, `0x2C` for call-home) and
decide on purpose whether "already in that state" is skipped or is the
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).
5. **Setup push** (row 10): one field first, then several.
Each phase is its own implementation plan. **All phases land on
`feat/series4-sfm-parity` and merge to `dev` once, when everything here is
implemented** (Brian, 2026-10-21) — not one merge per phase.
---
## Out of scope (this phase)
- Series-4 emergency tools: runaway stops, rescue, per-event delete, erase.
(Erase-all is also unmapped.)
- Async jobs; auth (Terra-View as jump host); the call-home receiver. These
are shared features for later.
- Scheduler read/write/enable; clock set; remote sensor check; restart;
firmware.
- Series-3 sessions, pending the bench test.
- Mapping the rest of `0x2C` (the THOR round).
## Fix list (found 2026-10-19, separate small changes)
- `bridges/ach_server.py:524`: `seen_keys` is undefined. Series-3 call-home
monitor-log collection has failed every session since `9afa348`
(2026-05-07).
- `bridges/mm_ach_server.py:262`: `_cstring`/`_content` aren't imported, so
the ring-answer path would raise `NameError`. From `8f67608` (2026-10-14).
- Series-3 `5A` 64 KB page-boundary bug (known; surfaces as HTTP 500).
- `POST /device/config` writes a fixed 29-byte `0x82` blob from one 3-11-26
capture, whatever the unit's trigger settings.
- `/device/events` runs a full 5A download per event just to list headers.
- `0x08` is named `read_event_index` in `micromate/`; it is the preferences
block.
## Left open by the phase 1a review (2026-10-21)
Minor findings from the whole-branch review, parked here so they outlive the
plan's scratch ledger. None blocks 1a; the phase each one matters to is named.
- **CORS ordering (1c, if a browser calls SFM directly).** The `/device` guard
middleware is registered after CORS, so it sits outside it: its 409/501
responses carry no `access-control-allow-origin`, and an OPTIONS preflight to
a guarded URL gets the guard's refusal instead of CORS's 200. Register CORS
last, or let OPTIONS through. Terra-View proxies server-side and is not
affected.
- **Legacy handlers take no unit lock (1c / phase 3).** The guard checks for a
held line and then lets the legacy handler run unlocked; a legacy request
admitted just before a Series-4 call-up at the same address can overlap it.
- **Address keys are not normalised.** `tcp:<host>:<port>` is the raw string:
a hostname vs an IP, or `/dev/serial/by-id/...` vs `/dev/ttyACM0`, gets two
locks for one link.
- **A serial-less request to an UNHELD Micromate still runs Series-3 bytes.**
The guard only knows about lines SFM holds. ~~This is the phase-2 opcode
guard's job.~~
**Measured by the phase-2 final review (2026-10-22):** the phase-2 gate
covers `micromate/` only and cannot see this traffic. Only the three blind
stop tools (`/device/stop_monitoring_blind`, `_slow_drip`, `_spam`) send a
write before any parsed reply. Every other legacy write route needs a
parsed `0xA4` POLL reply, and `S3FrameParser` never yields one from
Micromate bytes (364 real responses → 29 spurious frames, none `0xA4`). So
erase, config and call-home writes cannot reach a Micromate. Worst case
(inferred): an unheld Micromate at the address stops monitoring, via the
Series-3 `0x97` at offset 0x0000, never sent to one. The hazard is identity
(a moved modem or a stale IP), not series. **Brian's decision** (the legacy
routes are bound by 'behave exactly as today'): accept until the legacy path
retires after 1c, then require `serial` on the blind tools; or, as an
interim, refuse a blind tool when SFM's DB last saw a `UM` serial at that
host.
- **`tcp_port` coercion mismatch.** The guard parses with `int()`, pydantic
coerces more loosely (`"9034.0"`), so such a request passes the guard
unchecked. Parse with pydantic's own int coercion, or fail closed.
- **Test gaps.** The middleware wrapper itself is untested (a raw ASGI call
works without httpx); the contract test compares field names of one shared
dataclass, which cannot fail, and does not enforce "a field absent for one
series lives under `detail`".
- **`_ensure_reaper` race.** Two first Series-4 requests at once can start two
reaper threads; harmless because `try_hold` keeps them off each other's units.
- **Held serial lines share `/dev/ttyACM0` silently.** pyserial's open is not
exclusive, so a bench script beside a held line interleaves bytes with the
keep-alive; it looks like a dead unit. Open with `exclusive=True`, or don't
hold serial links.
## Left open by the phase 1b review (2026-10-21)
Parked from the whole-branch review of 1b; none blocks it. The phase each
matters to is named.
- **Retry re-runs a whole download (1c).** The retry-once on a held-line timeout re-runs the full download, roughly doubling time-to-error; narrow it to failures before the first reply.
- **`last_used` after a kept-line error (1c).** It is not refreshed when an op's verdict (404/409) keeps the line, so the idle hang-up comes early.
- **`verified: null` is ambiguous (1c).** It means both "a histogram" (no check exists) and "a waveform whose check could not run".
- **Mic naming and the Series-4 mic decode (1c).** `detail.mic_psi` on Series 3, `detail.mic` on Series 4; Series 4's `0x0C` mic decodes as a denormal (~5e-39) — fix the decode before 1c shows it.
- **500 detail leaks paths (1c, before SFM is reachable beyond Terra-View).** The download handler's 500 detail includes raw exception text, filesystem paths included.
- **Serial as a directory name (1c).** The serial is never checked against `[A-Z0-9]+` before it names a store directory; only the unit can choose it, but the check is cheap.
- **No server-level RADIO RING mid-download test (1c).** Covered structurally (DeviceAccess-level test + the ring transport), not through the handler.
- **Series-3 stored `record_type` (MiniMate bench check).** Rows SFM stores for Series 3 still say "Waveform" for histograms — pre-existing, the same as the legacy `blastware_file` route; fix it with the `0C` decode.
- **A fresh Series-4 download's gaps (1c).** No `sample_rate` is stored, and the sidecar has no vector sum; the DB row has the unit's PVS (overlaid from `0x0C`).
- **Orphan files (SDM).** An event file in the store with no DB row is still overwritten by a download.
## Left open by the 1c bench (2026-10-29)
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
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`
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.
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
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
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.
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
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 --
another program may be holding this unit's line".
- **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`
or `1F`, but a lost `0C` still lists the event with no timestamp and an
`event_id` ending `:-`. Downloading that id skips the stale check and runs the
full `5A`. If the `0C` is lost again it is refused (no timestamp, no filename);
if it reads, whatever event now sits at that key is stored with no stale check:
self-consistent data, but possibly not the event that was listed. Fix: raise on a lost `0C` in strict mode, or
refuse `:-` ids for Series 3.
- **A lost reply on a Series-3 TCP walk re-runs it once (1c)** under the adapter's
cold-boot retry before the 504, doubling time-to-error on a bad link.
- **A Series-3 download of an already-stored event still runs the full `5A`**
before the database lookup finds it (the lookup is on the SDM side, after the
device layer). Wasted transfer, not bad data (1c).
## Left open by the phase 2 review (2026-10-22)
- **`plan_setup_push` takes any name (phase 5).** It is not tied to the `0x41`
read, and it does not refuse `factory.MMB` or a non-active target, which the
spec requires; the name's case varies (`test2.MMB` vs `test2.mmb`).
- **Stripped-name caveat.** `get_active_setup()` strips whitespace, so a name
with leading or trailing spaces does not round-trip.
- **Bench questions.** Whether a Micromate honours offset 0x0000 on
`0x96`/`0x97`, accepts a no-op call-home write, or accepts 0x00 at `[5]`.
Settle all three at the bench.
- **Phase-5 lead (inferred).** Comparing `0x1A` against the active `.MMB` read
through `0x94`/`0x48` may detect unsaved keypad edits, which would undercut
"can't be detected from the wire". One bench check.
## Left open by the phase 3 review (2026-10-23)
The whole-phase review judged phase 3 ready for the bench, with nothing that
sends twice, sends without an audit row, or sends to an unverified unit. These
items were left for later on purpose:
- **Series-3 change path shape. Settle before the MiniMate bench check.**
- The change path makes one POLL at a 120 s receive timeout, with no retry. A
cold MiniMate that drops that POLL costs 120 s of a locked unit and then a
504. The legacy route retried `poll()` on the same connection at 10 s.
- The identity read is a full `connect()` (POLL, `0x15`, `0x01`, `0x1A`, `0x08`).
The spec asks for one serial read.
- Proposed: 10 s timeouts before the send, one identity-poll retry on the same
connection (a read, never the write), POLL plus `0x15` in place of
`connect()`, and the long timeout only on the read-back polls.
- That needs two measurements first: whether a *monitoring* MiniMate answers
the full `connect()` over TCP, and what `0x1C` reads during the ~40 s sensor
check.
- **For 1c (the webapp).**
- 409 means three things. "Wrong unit" and "unmeasured state" sent nothing;
"mismatch" sent a frame with a clean ack. Only the body tells them apart.
- `ChangeResult.detail` is a dict, so the webapp's `e.detail || r.statusText`
would print `[object Object]`.
- The 60 s verify window, plus the call-up, plus up to 20 s of lock wait,
exceeds the 60 s Terra-View proxy timeout. A mismatch could never be
delivered through that proxy.
- Nothing marks `pending` rows left by a restart mid-change. Reconcile them at
server start only, never on every `SeismoDb` open.
- **A late `0x69` after a lost ack.** When the ack is lost but the follow-up
read validates, the line is kept, and a late `0x69` then breaks the next
unrelated request with a 502. Safe, but confusing. Hanging up after any lost
ack needs a way to release the line on a path that returns a result.
- **Legacy routes take no per-address lock.** They can interleave with an
audited change on the same address. This belongs with the blind-stop-tools
decision, which is still open.
- **Test and scan gaps.**
- The `protocol.execute(` caller scan does not catch an aliased caller.
- Dropping the S4 ack's `data` field is not caught by any test.
- The fake's `fail` queue is also consumed by `read_unsolicited` on the change
path.
- **Docs nits.**
- `s4.py` says `ChangeUnconfirmed` follows "a link fault or a ring". It also
follows a `calling_home` read.
- The 2026-10-02 CLAUDE.md bullet still says "Read-only".
- The route docstrings' 409 line omits the held-line `WrongUnit`.
- **For the merge to dev.** The changelog states: a new `device_commands` table
(`CREATE TABLE IF NOT EXISTS`) plus a `_migrate` step that adds `sent` and
`states` to tables created from this branch. Prod: no migration, no backfill.
- **The MiniMate bench fixes, for the changelog** (2026-10-25, reviewed).
- **The body builder changed in the codec library** (`blastware_file.py`).
`TOOL_VERSION` is not bumped, because no stored file is affected, so nothing
is owed. The `.h5` regenerated from an `.a5.pkl` *would* change for a
non-first event, but no store holds one (below).
- **Operational consequence: none.** Measured: the dev store holds 0
`.a5.pkl` files. Inferred: prod runs no SFM receivers, and it ingests
Blastware's own files, which these functions never touch.
- The commit `352f694` says ".a5.pkl sidecars can rebuild them". That is
wrong: no tool rewrites the event file.
- **Behaviour change.** A probe timeout in a one-event download was
`502 "no waveform data received"`. It is now `NoAnswer` 504, and over TCP
it is retried once as a whole new session. That is a read, so it is
acceptable.
- **Orphaned diagnostic rows.** `be12599-diag`'s `ach_state.json` and its DB
key BE9557 as `'BE9557\x00G'`, the old serial bug. That is diagnostic data
only. SQLite `GLOB` stops at the NUL, so search with `hex()`.
- **Bench-test first, then decide.** A unit that answers a re-poll more than
2 s late, or answers polls it buffered while booting, could leave an extra A4
that is taken as `POLL_DATA`'s reply. `connect()` then fails at the `0x15`
check: an error, never corruption. A short drain after the re-poll would fix
it if a bench shows it happens.
- **The download check refuses what it cannot classify** (inferred, untested
configurations). A waveform with the geophones disabled (MicL only) leaves
Tran/Vert/Long empty, takes the histogram path and is refused; before
`c32a9e7` it was stored unverified. Histogram+Continuous events have never
been downloaded over 5A either. That is failing safe by design. A bench
check on such a unit decides whether a MicL-only branch (END check, no peaks)
is needed.
## Table 2: to be added later (both series)
| area | item |
|---|---|
| infrastructure | async jobs; auth via Terra-View |
| THOR has it, SFM doesn't | clock set; remote sensor check; scheduler; one setup to many units; restart |
| call-home receiver | hold lines open (S4); "already downloaded" tracking; rules by serial prefix (copy events, monitor log, delete, set clock); detect "Monitor While Calling Home" blocking deletes (⚠ one unexplained 21 → 5 count drop in THOR's log); hand off to `/db/import/*` instead of the watchers |
| settings, the no-PC-files way | intended settings per deployment; drift report (intended vs actual); push then verify |
| notifications | email/SMS by event type and PPV (THOR does it; may belong in Terra-View) |
| emergency tools for S4 | if a Micromate ever needs them |
## Parking lot
- **Deleting events after a call-in is the call-in receiver's job, not 1c's**
(Brian, 2026-10-29). In production Blastware ACH (Series 3) and THOR (Series
4) download, then delete; SFM gets the files afterwards from the watchers. If
SFM ever becomes the receiver, deletion comes with it:
- the protocol is already mapped: erase-all `A3 → 1C → 06 → A2` (S3), and
per-event `0xA8` + `0xAA` (S4);
- "Monitor While Calling Home" silently blocks erase while reporting
success, so the server-side high-water mark is load-bearing;
- `0xA2` means CONFIRM ERASE on S3 and END CALL on S4.
1c touches only Diagnostics' S3 erase-all, which it gates to a confirmed
Series-3 unit, server- and page-side.
- **Speed (Brian's goal: faster than Blastware), after 1c.** Measured on
BE9441, 2026-10-27 23:41, serial cable:
- wake + serial number take 0.16 s;
- `MiniMateClient.connect()` also reads 01 + 1A + 08 on every request, ~3 s;
- a fixed **2.0 s "safety drain"** at the end of `read_compliance_config` runs
on every connect;
- the read-back polls every 2 s.
Ideas, each measured before and after against Blastware's own timings in the
bridge recordings: a light connect (wake + serial) for start/stop, status and
event list; drop or shorten the drain; reuse within a session (MiniMates
reconnect per request). New safeguards must state their time cost
(1c's identity check reuses the serial read connect already does).
**Monitor logs.** Its own piece of work, data side as much as device side.
A unit calls in at least once or twice a day. With no events (e.g. waveform
mode, no blast that day) it still delivers a **monitor log**: "monitoring from
X to Y". The watchers (one for BW-ACH / Series 3, one for THOR-ACH / Series 4)
use the newest file per unit, event or `.MLG`, as SFM's "last heard from" age.
They forward waveform and histogram files but **not** monitor logs. To decide:
- Ingest call-in monitor logs into SFM. SFM's DB **already has** a
`monitor_log` table (one row per interval, deduped by serial + start time),
and `minimateplus/blastware_file.py` already parses Series-3 `.MLG`.
Missing: anything that takes `.MLG` in from the watchers, and knowledge of
THOR's Series-4 monitor-log file format.
- A live monitor-log read over a connection (Series 4: `0x0A` exists, no
wrapper or decoder; Series 3 in SFM: none).
- What it is for: proof of coverage ("was it monitoring when they blasted?")
and visible gaps.
- Related fix-list item: `ach_server.py`'s `seen_keys`.
**How SFM handles setup files and schedules.** This phase only reads and
pushes the unit's *active* setup, with no PC-side library (the `.mmb`
same-name/different-contents gotcha). Still to decide, as one question because
the two are coupled:
- The unit stores up to 25 named `.MMB` files. Should SFM manage them (list,
select, rename, delete, push to a named file), or only ever touch the active
one?
- **Schedules name setup files.** A schedule entry switches the unit to a
setup by name, so a schedule is only as reliable as the files it points to.
What if it points to a file that isn't there? That is untested.
- How "intended settings per deployment" (Table 2) fits with files and
schedules.
- Scheduler read/write is mostly mapped (file transfer + `0x47`); **disable has
never been captured**.
**A modem-side agent on the RX55.** AirLink
OS on the RX55 has "Container Applications (Early Adopter)", and Brian already
runs `slmm-proxy` there. A small program owning the unit's serial port could:
- let THOR and SFM share the line
- dial out to SFM, avoiding the IP whitelist
- handle `RADIO RING` locally
- **Brian's hunch:** make RX55s work with Series 3 by driving DTR/DCD itself
Open questions:
- Can a container open the RS-232 port?
- Can it set the control lines?
- How is it deployed to a fleet, and does it Autostart?
- Will a firmware update keep the beta feature?
## Open questions this design leaves for the bench
- **Ring path and retries: does a Micromate's call-home reach THOR when SFM
holds its line?** (Test designed 2026-10-23; decides whether 1c needs a
cool-down.)
- *Already measured (10-14):* with THOR holding the line, the ring arrived on
THOR's own outbound connection (`TcpClientSystemNet ... RADIO RING IS
RECEIVED FROM IP:...:9034`), so the modem did not divert it to the
destination. Unmeasured: the same with SFM as the holder, and what the
unit does after the holder releases.
- *Known from the firmware strings:* "three attempts and it's over".
🔶 Inferred: 60 s between attempts (`0x2C` content `[120:122]` = `00 3c`,
Series III's "time between retries" offset), and about 21 s of ringing per
attempt (10-14 capture).
- ~~*Setup:* a bench Micromate on a modem whose destination is the office
THOR-ACH server, and a unit THOR is not otherwise watching.~~
**Revised 2026-10-29:** THOR receives a call-home on its *own* connection to
the unit (10-14, measured), so a unit THOR does not watch would not test the
production path. And THOR's watchdog interval is a THOR setting -- every 5 s,
hourly, or never (Brian) -- so the runs vary it on purpose.
- *Setup:* UM20147 added to THOR as a test unit, its modem's destination set to
the office THOR server. SFM runs from the parity branch on a test port with
a scratch DB and a timestamped log (it logs every ring and hang-up). THOR's
ACH log open; note THOR's clock against ours. Run after the 1c bench pass:
the call-home uploads UM20147's events, and may erase them per THOR's
test-unit settings.
- **Run 0, baseline (watchdog never, nobody on the line):** trigger a
call-home. Does it reach THOR -- i.e. does the modem dial out by itself?
- **Run A, one call-up (watchdog never):** SFM calls the unit up and holds
the line (any serial-named read). Trigger a call-home. Record:
- whether SFM logs the RADIO RING and hangs up, with the time;
- whether and when THOR starts a session (its ACH log);
- the number and spacing of rings and attempts.
- **Run A2 (watchdog at the fleet's setting):** as A, with THOR competing for
the line. First: can SFM get on at all, and does a watchdog check hold the
line or drop it? Then: after SFM hangs up on the ring, does THOR get back on
before the unit's next attempt?
- **Run B, a poller (watchdog at the fleet's setting):** as A2, but a script
requests the unit's status every ~10 s throughout. If THOR still gets the
call, no cool-down is needed; if the poller keeps the call from reaching
THOR, build it, sized from Run A.
- *Also settles:* whether the modem routes a call-home to its destination
on its own (Run 0), in which case SFM never sees a ring and THOR gets the call
while SFM is still connected.
- **Results, 2026-10-29** (UM20147 on a fleet-config RX55 at `63.45.161.30`,
added to THOR as a test unit; THOR log `C:\THORDATA\Logs\`; all measured
unless marked):
- **Run A (watchdog off, SFM holding the line).** SFM's stop (`0x97`,
20:21:13.001) was answered by `RADIO RING` instead of its ack (20:21:13.7);
SFM hung up. The page's post-change status read called the unit straight
back up (20:21:13.8 → held to 20:21:47; the reaper listens every 5 s, no
second ring). The unit showed "connecting..." → "call home data
transfer..." for under a minute → idle, **no retry**; THOR logged nothing
for the unit through 20:23:57.
- **Run 0 (watchdog off, nobody on the line, keypad start/stop).** The modem
dialled `50.197.32.91:12345`: `ListenerAchTcp - Connection accepted from
63.45.161.30:36648` (20:37:28.5) → serial → `RADIO RING IS RECEIVED` on that
connection → a full THOR session (count 8, download, **DeleteEventState**
per event, reports, email, Vision). SFM sent nothing 20:22–20:37.
- **A2, step 1 (THOR polling, ~5–15 s).** An SFM status read at 20:44:35.9:
the modem accepted the connection, 0 bytes back in 10 s (504). THOR's reads
of the unit at 20:44:37.4 and 20:44:44.3 were answered; no disconnect.
- **Conclusion:** the risk is confined to when THOR is not holding the line
(watchdog off, THOR down, reconnect gaps), and a cool-down would not fix
it. Run B (a poller) is deprioritised: while THOR polls it only collects
504s; the open point is a reconnect gap.
- Also seen: after a manual THOR Disconnect (19:48:07) the unit answered
nobody until a reset (back 20:16:51); THOR's reconnect logged `Mismatch
connection found`. Cause unknown.
- The ack for start/stop when the unit is already in that state.
✅ **Answered for stop (2026-10-25, UM20147):** a stop sent to an idle unit
is acked `0x68` in 10 ms (twice) and changes nothing: not the state, the
events, memory or the screen. Start while already monitoring has not been
tried. Also measured at that bench: `0x49` reads `0x01` for ~18 s after a
real stop. Its meaning is inferred to be the unit's call-home attempts, and
Run A/B can settle it: the inference predicts `0x01` → `0x03` when the modem
connects.
- The offset rule, and whether `0x68`/`0x82` are required, for the setup push.
- Whether the device ever refuses a write while monitoring. Only THOR's policy
has been seen.
- How a failed write is signalled. It has never been observed.
- MiniMate behaviour with a held session (above).
+6 -65
View File
@@ -2,8 +2,7 @@
client.py — high-level API for a live Micromate (Series IV).
Owns the transport, turns raw payloads into models. Read-only, like the layer
below it: nothing here writes, erases, or changes monitoring state, and the
protocol's opcode gate (`micromate.opcodes`) enforces that in code.
below it: nothing here writes, erases, or changes monitoring state.
with MicromateClient(TcpTransport("63.45.161.30", 9034)) as mm:
info = mm.connect()
@@ -40,13 +39,7 @@ from typing import Optional
from minimateplus.transport import BaseTransport
from .models import (
MicromateDeviceInfo,
MicromateEventRef,
MicromateRunState,
MicromateSetup,
MicromateState,
)
from .models import MicromateDeviceInfo, MicromateEventRef, MicromateSetup, MicromateState
from .protocol import MicromateProtocol, ProtocolError
from .setup_block import decode_setup
@@ -60,11 +53,6 @@ CONTENT = 11
# two of them disagree with docs/micromate_protocol_reference.md.
_STATE_FLAG = 0 # 0x49: 0x00 idle, 0x02 monitoring
# 0x06 storage range. content[0:4] is the event count: 3/3 against the chain
# walk, and THOR's ReadEventRecordCount agrees. content[4:8] is very likely
# the monitor-log count -- graded a strong candidate, not settled, so not exposed.
_SR_EVENT_COUNT = slice(0, 4)
_MS_FLAG = 1 # 0x1C: monitoring flag — test NON-ZERO
_MS_DAY, _MS_MONTH, _MS_YEAR = 2, 3, slice(4, 6)
_MS_UNKNOWN_6 = 6 # ⚠ sub-second tick (~4020/s, step 4, 64 ms wrap) — NOT the hour
@@ -140,10 +128,7 @@ class MicromateClient:
self._transport.disconnect()
def is_open(self) -> bool:
# `is_connected` is a PROPERTY on BaseTransport. Calling it raised
# TypeError on every real transport; only a test double that defined
# it as a method hid that.
return bool(self._transport.is_connected)
return self._transport.is_connected()
def __enter__(self) -> "MicromateClient":
self.open()
@@ -276,23 +261,6 @@ class MicromateClient:
raw=data,
)
def get_event_count(self) -> int:
"""`SUB 0x06` -- events stored. One read; no chain walk."""
c = _content(self._proto.read_storage_range())
if len(c) < 4:
raise ProtocolError(f"storage range content is {len(c)} B, need at least 4")
return int.from_bytes(c[_SR_EVENT_COUNT], "big")
def read_unsolicited(self) -> bytes:
"""Whatever the unit sent unprompted. **Sends nothing.**
One transport read. Bytes between commands are noise to the protocol
(every request resets the parser), so reading them here takes nothing
the protocol needs. A session calls this while idle to notice
RADIO RING without waiting for its next keep-alive.
"""
return self._transport.read(4096)
@staticmethod
def _parse_clock(c: bytes) -> Optional[datetime.datetime]:
"""The unit's own clock, in its own local time.
@@ -371,32 +339,16 @@ class MicromateClient:
# ── Events ────────────────────────────────────────────────────────────────
def serial(self, *, refresh: bool = False) -> str:
def serial(self) -> str:
"""The unit's serial, cached from `connect()` or read on demand.
Needed by anything that handles an event, because an event key is
ambiguous without it — see `MicromateEventRef`.
`refresh=True` forces a fresh `0x15` read. A change operation passes it
right before writing, so the identity check never runs against a serial
cached from an earlier call-up (a modem may have moved to another unit).
"""
if refresh or self._serial is None:
if self._serial is None:
self._serial = _cstring(_content(self._proto.read_serial()))
return self._serial
# Anything else reads unknown(0x..): the safe default, which the change path refuses.
_RUN_STATES = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
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)."""
c = _content(self._proto.read_state())
if not c:
raise ProtocolError("0x49 state reply has no content")
code = c[_STATE_FLAG]
return MicromateRunState(code, self._RUN_STATES.get(code, f"unknown(0x{code:02X})"))
def list_events(self, *, with_records: bool = True) -> list[MicromateEventRef]:
"""Walk the event chain. `0x93 → 1E`, then `0x93 → 1F` until the sentinel.
@@ -573,17 +525,6 @@ class MicromateClient:
Histograms are not verified: `samples` is empty for them.
"""
return self.fetch_event(ref, verify=verify, tolerance=tolerance,
chunk_size=chunk_size)[1]
def fetch_event(self, ref: MicromateEventRef, *, verify: bool = True,
tolerance: float = 0.01, chunk_size: Optional[int] = None):
"""`get_event()`, returning the raw bytes too: `(blob, result)`.
For a caller that stores the file AND wants the self-check: the bytes go
to the waveform store unchanged, and a DecodeMismatch stops them being
stored at all.
"""
if not ref.record_type:
raise ValueError(
f"event {ref.key_hex}: record_type is unknown, so the codec "
@@ -614,7 +555,7 @@ class MicromateClient:
)
if err is not None:
log.debug("event %s: PVS agrees to %+.4f%%", ref.uid, 100 * err)
return blob, result
return result
@staticmethod
def decode_error(ref: MicromateEventRef, result) -> Optional[float]:
+4 -30
View File
@@ -126,14 +126,12 @@ def checksum(payload: bytes) -> int:
# ── Request builder ───────────────────────────────────────────────────────────
def build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: bytes = b"") -> bytes:
def build_request(sub: int, offset: int = 0, params: bytes = bytes(10)) -> bytes:
"""Build a host→unit command frame.
⚠ Do **not** substitute `minimateplus.framing.build_bw_frame()` here, even
though the payload layout is identical. That builder escaped only `0x10`,
so it reproduced just **161 of Thor's 218** captured read frames. (Since
2026-10-26 it escapes the same four values -- a MiniMate wants them too -- but
the Micromate framing differs in other ways; keep the two builders apart.) The 57 it
though the payload layout is identical. That builder escapes only `0x10`,
so it reproduces just **161 of Thor's 218** captured read frames. The 57 it
gets wrong are not edge cases:
* every `SUB 0x5A` bulk download — `offset = 0x0400` puts a literal
@@ -152,9 +150,6 @@ def build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: by
Thor asks for `0xFFFF` and gets the whole block — so this is
usually `0xFFFF`, not Series III's probe-then-data pair.
params: exactly 10 bytes at payload[6:16].
data: the write section after params (empty for every read and for
write confirms). Escaped and checksummed exactly like the rest
of the payload -- reproduces all 33 data-carrying THOR frames.
A `0x10` inside `params` is fine and needs no special handling: Thor sends
`SUB 0x5A` with `params = 00 00 10 00 …` and the wire carries `10 10`.
@@ -167,32 +162,11 @@ def build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: by
if not 0 <= sub <= 0xFF:
raise ValueError(f"sub must be a single byte, got {sub:#x}")
payload = (bytes([MM_CMD, 0x00, sub, 0x00, (offset >> 8) & 0xFF, offset & 0xFF])
+ params + bytes(data))
payload = bytes([MM_CMD, 0x00, sub, 0x00, (offset >> 8) & 0xFF, offset & 0xFF]) + params
body = payload + bytes([checksum(payload)])
return bytes([ACK, STX]) + stuff(body) + bytes([ETX])
def request_sub(frame: bytes) -> int:
"""The SUB of a built host->unit frame (`41 02 <stuffed body> 03`).
Used by the protocol's send-side opcode gate, which must see exactly what is
about to go on the wire rather than trust the caller's word for it.
"""
if len(frame) < 5 or frame[0] != ACK or frame[1] != STX or frame[-1] != ETX:
raise ValueError(f"not a host->unit request frame: {bytes(frame[:8]).hex()}")
body = unstuff(frame[2:-1])
if len(body) < 17 or body[0] != MM_CMD:
raise ValueError(f"not a host->unit request frame: {bytes(frame[:8]).hex()}")
# Canonical form only: what this check reads must be exactly what the unit
# parses. An unescaped 02/03/04, a `10 XX` outside {02,03,04,10} or a
# trailing lone DLE would be read one way here and another by the unit.
if stuff(body) != frame[2:-1]:
raise ValueError(
f"not a canonical request frame (stuffing differs): {bytes(frame[:8]).hex()}")
return body[2]
# ── Response frame ────────────────────────────────────────────────────────────
@dataclass
-8
View File
@@ -155,14 +155,6 @@ class IdfReport:
)
@dataclass(frozen=True)
class MicromateRunState:
"""`SUB 0x49` content[0]. 0x00 idle, 0x02 monitoring, 0x03 calling home
(ten of ten in the 10-14 ACH session); anything else is named, not guessed."""
code: int
name: str
# ── IdfPeaks / IdfProjectInfo / IdfSensorCheck (narrow grouping types) ───────
-113
View File
@@ -1,113 +0,0 @@
"""Micromate (Series IV) opcode table: which SUBs write, and which collide.
One place, as the parity spec requires. The gate is an ALLOWLIST: a SUB is
transmitted only if it is a catalogued read (READ_SUBS) or a catalogued write
that arrives through `MicromateProtocol.execute` (one call's permission, capped at
ENABLEABLE_WRITES; the connection itself holds none). An unknown SUB is refused -- clock-set
and delete-all have Series-IV opcodes nobody has catalogued yet, and "unknown
means read" is the wrong default. `MicromateProtocol._send` consults it
on every outgoing frame, so a write cannot reach a unit by a path nobody
thought about -- a scratch tool calling `protocol._send`, a hand-built frame, a
method added later.
Every SUB here was seen as a host->unit request in THOR's captures
(`docs/micromate_protocol_reference.md`). The table classifies REQUESTS: a few
of these values are also ACK SUBs of other commands (0x71 acks 0x8E, 0x72 acks
0x8D), which is irrelevant to a send-side check.
"""
from __future__ import annotations
from types import MappingProxyType
from typing import Dict, FrozenSet, Mapping
_WRITE_SUBS: Dict[int, str] = {
0x47: "scheduler enable/disable",
0x68: "setup push: preferences block (0x08)",
0x71: "setup push: setup block (0x1A)",
0x72: "setup push: setup confirm",
0x73: "setup push: preferences confirm",
0x7E: "call-home config write (0x2C)",
0x7F: "call-home config confirm",
0x82: "setup push: trigger block (0x2E)",
0x83: "setup push: trigger confirm",
0x8D: "file open for write",
0x8E: "file body write",
0x96: "start monitoring",
0x97: "stop monitoring",
0xA2: "end call-home",
0xA8: "delete one event",
0xAA: "delete-event confirm",
0xDA: "setup push: file name",
}
# Same SUB, opposite consequence on the other series (not the same bytes:
# Series III's CONFIRM ERASE carries offset 0x0000 and token 0xFE, THOR's 0xA2
# carries offset 0xFFFF). Never transmitted on
# Series IV, allowed or not: if a Series-III unit is at the address (a moved
# modem, a stale IP), it would execute the other meaning. Lifting an entry is
# a spec change, not a parameter.
_CROSS_SERIES_COLLISIONS: Dict[int, str] = {
0xA2: "CONFIRM ERASE on Series III -- erases every stored event; "
"'end call-home' on Series IV",
}
_READ_SUBS: Dict[int, str] = {
0x01: "device info",
0x06: "storage range",
0x08: "event index / preferences block",
0x0A: "monitor log",
0x0C: "event record",
0x15: "serial number",
0x1A: "setup block",
0x1C: "monitor status",
0x1E: "event first",
0x1F: "event next",
0x2C: "call-home config",
0x2E: "trigger config",
0x3F: "setup list first",
0x40: "setup list next",
0x41: "active setup",
0x48: "file read next page",
0x49: "state",
0x5A: "bulk download",
0x5B: "poll",
0x93: "arm event",
0x94: "file open for read",
}
# Read-only views: a stray .pop() anywhere in the process cannot disable a gate.
WRITE_SUBS: Mapping[int, str] = MappingProxyType(_WRITE_SUBS)
CROSS_SERIES_COLLISIONS: Mapping[int, str] = MappingProxyType(_CROSS_SERIES_COLLISIONS)
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})
class OpcodeRefused(RuntimeError):
"""A frame was stopped before it reached the wire."""
def check_transmit(sub: int, allowed_writes: FrozenSet[int] = frozenset()) -> None:
"""Raise OpcodeRefused unless `sub` may go on the wire.
Precedence: (1) a cross-series collision is refused always; (2) a
SUB in neither READ_SUBS nor WRITE_SUBS is unknown and refused whatever
`allowed_writes` says; (3) a catalogued write is refused unless in
`allowed_writes`.
"""
if sub in CROSS_SERIES_COLLISIONS:
raise OpcodeRefused(
f"refused to transmit SUB 0x{sub:02X}: {CROSS_SERIES_COLLISIONS[sub]}")
if sub not in READ_SUBS and sub not in WRITE_SUBS:
raise OpcodeRefused(
f"refused to transmit SUB 0x{sub:02X}: unknown opcode -- not in "
"micromate.opcodes; catalogue it first (allowing it does not help)")
if sub in WRITE_SUBS and sub not in allowed_writes:
raise OpcodeRefused(
f"refused to transmit SUB 0x{sub:02X} ({WRITE_SUBS[sub]}): writes are "
"not enabled on this connection")
+22 -92
View File
@@ -4,24 +4,13 @@ protocol.py — one method per Micromate (Series IV) wire command.
Returns raw payload bytes. Interpretation belongs in ``client.py``; this layer
knows frames, offsets and sequencing, and nothing about what a field means.
Scope: **reads, plus start/stop monitoring through `execute()` only --
enforced** (in this package: the Series-3 `minimateplus` stack and raw-socket
bench bridges are outside the gate). Every outgoing frame passes
`micromate.opcodes.check_transmit()` in `_send`: a write opcode is refused
unless it arrives through `execute()` (the connection itself holds no write
permission), `execute()` can permit only SUBs under `ENABLEABLE_WRITES`
(`0x96` / `0x97`), and `0xA2` -- CONFIRM ERASE on Series III -- is refused
always. The one caller of `execute()` is SFM's change path,
`sfm/device_access/s4.py` (a test pins that). The gate is an allowlist: a SUB
not catalogued in `opcodes` (read or write) is refused as unknown. No command
has ever been originated against a unit by this project; every write in ``docs/micromate_protocol_reference.md`` was performed
by THOR while we recorded. The first thing this codebase ever sends to a
customer's instrument should be a decision someone made on purpose, not a side
effect of a client that grew a method. Write frames are *built* in
``micromate.writes`` as reviewable plans; building one sends nothing.
``execute(plan)`` is the only write path: one call's permission, at most
``ENABLEABLE_WRITES``, and only on a connection that has had Micromate-flagged
replies.
Scope: **reads only.** Nothing here writes, erases, or changes monitoring
state. That is deliberate and worth keeping — no command has ever been
originated against a unit by this project; every write in
``docs/micromate_protocol_reference.md`` was performed by THOR while we
recorded. The first thing this codebase ever sends to a customer's instrument
should be a decision someone made on purpose, not a side effect of a client
that grew a method.
Every offset and params layout below was read off THOR's own frames in
``bridges/captures/9-24-26 - micromate2/`` rather than taken from the spec
@@ -50,18 +39,11 @@ import logging
import math
import struct
import time
from typing import TYPE_CHECKING, Optional
from typing import Optional
from minimateplus.transport import BaseTransport
from .framing import (
FLAGS_BLASTWARE, FLAGS_THOR, MicromateFrame, MicromateFrameParser,
build_request, request_sub,
)
from .opcodes import ENABLEABLE_WRITES, OpcodeRefused, check_transmit
if TYPE_CHECKING:
from .writes import WritePlan
from .framing import MicromateFrame, MicromateFrameParser, build_request
log = logging.getLogger(__name__)
@@ -231,9 +213,8 @@ def chunk_params(key4: bytes, byte_offset: int) -> bytes:
⚠ This is the **Series III 64 KB page-boundary bug in a new guise** — there,
`parse_strt_end_offset()` discards the key's page byte and the `5A` walk
crashed once a unit's buffer crossed 64 KB (fixed 2026-10-26: a Blastware
recording showed its 5A address is a plain 32-bit linear one, like this).
The lesson that transfers: an address field whose high bytes are zero
crashes once a unit's buffer crosses 64 KB, which is *still open* on that
side. The lesson that transfers: an address field whose high bytes are zero
in every capture is not a narrow field, it is an untested one.
"""
if byte_offset == 0:
@@ -283,7 +264,6 @@ class MicromateProtocol:
self._strict = strict_checksums
self._parser = MicromateFrameParser()
self._pending: list[MicromateFrame] = []
self.last_flags: Optional[int] = None
# ── Identity and state ────────────────────────────────────────────────────
@@ -309,19 +289,10 @@ class MicromateProtocol:
return self._read(SUB_DEVICE_INFO)
def read_state(self) -> bytes:
"""`0x49` → `0xB6`. A cheap state check; 16 B of data.
"""`0x49` → `0xB6`. A cheap monitoring check; 16 B.
`data[11]` (content[0]) is the run state. Measured: `0x00` idle,
`0x02` monitoring (every monitoring sample so far), and `0x03` while
calling home (ten reads of ten in the captured 2026-10-14 ACH
session). No other value has been seen.
`MicromateClient.read_run_state` matches those three exactly and names
anything else `unknown(0x..)`, which the change path refuses;
`connect()`'s `monitoring` tests non-zero, so `0x03` reads True there.
⚠ `0x0E` and `0x0C` (both read while monitoring, so "test for
non-zero") belong to `SUB 0x1C` `data[12]`, a separate field -- not to
this byte. See the reference's `0x49` and `0x1C` sections.
⚠ Test `data[11]` for **non-zero**, never against a constant — it has
read both `0x0E` and `0x0C` while monitoring.
"""
return self._read(SUB_STATE)
@@ -526,58 +497,18 @@ class MicromateProtocol:
) -> MicromateFrame:
if offset is None:
offset = _OFFSETS.get(sub, READ_ALL)
# `_request` starts every exchange clean (drops any half-frame and any
# stashed frame): this is a strict request/response protocol, so anything
# already buffered when we send is stale.
return self._request(build_request(sub, offset, params), 0xFF - sub,
timeout=timeout)
def _request(self, frame: bytes, expected_sub: int, *, timeout: Optional[float] = None,
permit: frozenset = frozenset()) -> MicromateFrame:
"""Clean slate, send one frame, receive its reply. The one sequence
every exchange -- read or execute -- goes through."""
# Start every exchange clean: drop any half-frame and any frame left
# stashed by the last one. This is a strict request/response protocol,
# so anything already buffered when we send is by definition stale, and
# `expected_sub` would reject it anyway — better to discard it here than
# to raise a confusing UnexpectedResponse one command later.
self._parser.reset()
self._pending.clear()
self._send(frame, permit=permit)
return self._recv_one(expected_sub=expected_sub, timeout=timeout,
self._send(build_request(sub, offset, params))
return self._recv_one(expected_sub=0xFF - sub, timeout=timeout,
reset_parser=False)
def execute(self, plan: "WritePlan") -> list[MicromateFrame]:
"""Transmit a `micromate.writes.WritePlan` -- the only write path.
Permission is granted for this call alone, one step at a time, and only
for SUBs under `ENABLEABLE_WRITES`. Refuses unless the last reply on
this connection carried Micromate flags (0xC5 / 0x03). Each step's ack
is awaited before the next is sent. Never retries: a timeout raises,
and what happened is the caller's to find out by reading the unit back.
"""
# Deferred: writes -> setup_block -> protocol would be circular at import.
from .writes import WritePlan
if not isinstance(plan, WritePlan):
raise TypeError(f"execute takes a WritePlan, got {type(plan).__name__}")
beyond = {st.sub for st in plan.steps} - ENABLEABLE_WRITES
if beyond:
raise OpcodeRefused(
"plan holds SUB(s) above the write ceiling: "
+ ", ".join(f"0x{s:02X}" for s in sorted(beyond)))
if self.last_flags not in (FLAGS_BLASTWARE, FLAGS_THOR):
raise OpcodeRefused(
"no Micromate-flagged reply seen on this connection -- "
"refusing to write")
acks = []
for step in plan.steps:
acks.append(self._request(step.frame, step.ack_sub,
permit=frozenset({step.sub})))
return acks
def _send(self, frame: bytes, *, permit: frozenset = frozenset()) -> None:
# The gate sees the bytes about to go out, not the caller's intent.
# `permit` is passed only via _request, from execute(), for one step.
frame = bytes(frame)
# Trust means the most recent request got a validated Micromate reply.
self.last_flags = None
# The ceiling is enforced here, where frames leave, whatever was permitted.
check_transmit(request_sub(frame), permit & ENABLEABLE_WRITES)
def _send(self, frame: bytes) -> None:
log.debug("TX %d bytes: %s", len(frame), frame.hex())
self._transport.write(frame)
@@ -631,5 +562,4 @@ class MicromateProtocol:
raise UnexpectedResponse(
f"expected SUB 0x{expected_sub:02X}, got 0x{frame.sub:02X}"
)
self.last_flags = frame.flags
return frame
-181
View File
@@ -1,181 +0,0 @@
"""Write plans for a Micromate: the exact frames a write would send, in order.
A plan is what a dry run returns. Building one sends nothing; transmitting it
is `MicromateProtocol.execute(plan)` and nothing else: the connection holds no
write permission of its own (see `micromate.opcodes`).
Every input is the unit's OWN read of the block being written (content, i.e.
response data[11:]), and every plan sends back exactly what was read except
the one thing the operation changes. THOR works the same way, and the
reproduction tests hold the plans to THOR's frames byte for byte.
Offsets are THOR's observed constants. 🔶 Each was seen at one block size
only, so a plan refuses a block of any other size rather than guess.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import FrozenSet, List, Tuple
from .framing import build_request
from .opcodes import CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused
from .setup_block import crc_ok
_CONFIRM = 0xFFFF
# 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
_NAME_FIELD = 256
@dataclass(frozen=True)
class WriteStep:
sub: int
offset: int
data: bytes = b""
params: bytes = field(default=bytes(10))
what: str = ""
def __post_init__(self) -> None:
# Freeze the bytes: a caller's bytearray must not change a validated step.
object.__setattr__(self, "data", bytes(self.data))
object.__setattr__(self, "params", bytes(self.params))
if len(self.params) != 10:
raise ValueError(f"params must be 10 bytes, got {len(self.params)}")
if not 0 <= self.offset <= 0xFFFF:
raise ValueError(f"offset 0x{self.offset:X} does not fit a uint16")
if not 0 <= self.sub <= 0xFF:
raise ValueError(f"SUB {self.sub!r} does not fit a byte")
@property
def ack_sub(self) -> int:
return 0xFF - self.sub
@property
def frame(self) -> bytes:
return build_request(self.sub, self.offset, self.params, self.data)
def describe(self) -> dict:
return {"sub": f"0x{self.sub:02X}", "what": self.what,
"offset": f"0x{self.offset:04X}", "data_len": len(self.data),
"expect_ack": f"0x{self.ack_sub:02X}", "frame": self.frame.hex()}
@dataclass(frozen=True)
class WritePlan:
action: str
steps: Tuple[WriteStep, ...]
warnings: Tuple[str, ...] = ()
def __post_init__(self) -> None:
# Copy: a caller's list must not be able to add a step after validation.
object.__setattr__(self, "steps", tuple(self.steps))
object.__setattr__(self, "warnings", tuple(self.warnings))
for s in self.steps:
if not isinstance(s, WriteStep):
raise TypeError(f"a plan holds WriteStep objects, got {type(s).__name__}")
if s.sub in CROSS_SERIES_COLLISIONS:
raise OpcodeRefused(
f"a plan cannot hold SUB 0x{s.sub:02X}: {CROSS_SERIES_COLLISIONS[s.sub]}")
if s.sub not in WRITE_SUBS:
raise ValueError(f"SUB 0x{s.sub:02X} is not a write opcode")
@property
def subs(self) -> FrozenSet[int]:
return frozenset(s.sub for s in self.steps)
def frames(self) -> List[bytes]:
return [s.frame for s in self.steps]
def describe(self) -> dict:
return {"action": self.action, "sends_nothing": True,
"warnings": list(self.warnings),
"steps": [s.describe() for s in self.steps]}
def plan_start_monitoring() -> WritePlan:
return WritePlan("start monitoring", (WriteStep(0x96, _CONFIRM, what="start monitoring"),))
def plan_stop_monitoring() -> WritePlan:
return WritePlan("stop monitoring", (WriteStep(0x97, _CONFIRM, what="stop monitoring"),))
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.
"""
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)}")
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 b5 == start:
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
" -- this write changes nothing")
return WritePlan(what, (
WriteStep(0x7E, 0x007E, data, what="call-home config write"),
WriteStep(0x7F, _CONFIRM, what="call-home config confirm"),
), tuple(warnings))
def _checked(block: bytes, size: int, label: str) -> bytes:
if len(block) != size:
raise ValueError(f"{label} block size {len(block)} B is not the {size} B "
"THOR's offset was observed at -- refusing to guess")
if int.from_bytes(block[0:2], "big") != size - 2:
raise ValueError(f"{label} block's own header says "
f"{int.from_bytes(block[0:2], 'big')}, expected {size - 2} -- "
"not the block it claims to be")
if not crc_ok(block):
raise ValueError(f"{label} block failed its checksum -- refusing to write a "
"corrupt read back to the unit")
return block
def plan_setup_push(prefs: bytes, trigger: bytes, setup: bytes, name: str) -> WritePlan:
"""Rewrite a setup as THOR does: read 0x08, 0x2E, 0x1A, send each back.
No field editing here (phase 5). Each block goes back with its length echo
[0:3] zeroed; the unit recomputes the CRCs, so 0x68 and 0x71 drop the CRC
slot and 0x82 sends it zeroed -- exactly THOR's frames.
⚠ `0x1A` reads the keypad's edit buffer live. A setup read taken while
someone is in the unit's menu includes their unsaved edits, and pushing
this plan would commit them.
The name goes out exactly as given. `MicromateClient.get_active_setup()`
strips whitespace, so a setup name with leading or trailing spaces would
not round-trip through it; phase 5 decides whether to take the unstripped
name from the 0x41 read.
"""
_checked(prefs, _PREFS_LEN, "preferences (0x08)")
_checked(trigger, _TRIGGER_LEN, "trigger (0x2E)")
_checked(setup, _SETUP_LEN, "setup (0x1A)")
try:
raw = name.encode("ascii")
except UnicodeEncodeError:
raise ValueError(f"setup name must be ASCII: {name!r}") from None
if not raw or b"\x00" in raw or len(raw) >= _NAME_FIELD:
raise ValueError(f"setup name must be 1-{_NAME_FIELD - 1} ASCII bytes "
f"with no NUL: {name!r}")
return WritePlan(f"setup push: {name}", (
WriteStep(0xDA, 0x0100, raw.ljust(_NAME_FIELD, b"\x00"), what="setup file name"),
WriteStep(0x68, 0x005A, bytes(3) + prefs[3:88], what="preferences block"),
WriteStep(0x73, _CONFIRM, what="preferences confirm"),
WriteStep(0x82, 0x001C, bytes(3) + trigger[3:26] + bytes(2), what="trigger block"),
WriteStep(0x83, _CONFIRM, what="trigger confirm"),
WriteStep(0x71, 0x082C, bytes(3) + setup[3:2090], what="setup block"),
WriteStep(0x72, _CONFIRM, what="setup confirm"),
))
+47 -37
View File
@@ -152,6 +152,7 @@ from __future__ import annotations
import datetime
import logging
import re
import struct
from pathlib import Path
from typing import Optional, Union
@@ -416,6 +417,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.
@@ -552,31 +578,6 @@ def classify_frame(frame: S3Frame) -> str:
# ── Waveform file writer ───────────────────────────────────────────────────────────
_A5_HEADER = 12 # every A5 reply's header after the probe, in stripped bytes
_A5_TERM_HEADER = 11 # the TERM reply's header
def _raw_skip(data, stripped_len: int) -> int:
"""Raw bytes of `data` covering its first `stripped_len` bytes, an inner DLE
pair (10 02 / 10 03 / 10 04) counting as one -- the rule `probe_skip` and
`_strip_inner_frame_dles` already use.
Every A5 header is 12 bytes in that sense (the TERM's 11), but its raw length
varies with the address it echoes: 13 for the metadata pages at 0x1002 and
0x1004, and for a sample chunk that lands there; 12 otherwise. A fixed
"frames 1 and 2 are metadata pages, skip 13" cut two bytes from every
non-first event, which has no metadata pages (BE9441, 2026-10-25).
"""
raw_i = stripped = 0
while stripped < stripped_len and raw_i < len(data):
if data[raw_i] == 0x10 and raw_i + 1 < len(data) and data[raw_i + 1] in (0x02, 0x03, 0x04):
raw_i += 2
else:
raw_i += 1
stripped += 1
return raw_i
def extract_body_bytes(a5_frames):
"""Reconstruct the Blastware-file body bytes from a list of A5 frames.
@@ -639,11 +640,16 @@ def extract_body_bytes(a5_frames):
all_bytes = bytearray()
for fi, frame in enumerate(body_frames):
skip = probe_skip if fi == 0 else _raw_skip(frame.data, _A5_HEADER)
if fi == 0:
skip = probe_skip
elif fi in (1, 2):
skip = 13 # metadata pages
else:
skip = 12 # sample chunks
all_bytes.extend(_frame_body_bytes(frame, skip))
if term_frame is not None:
all_bytes.extend(_frame_body_bytes(term_frame, _raw_skip(term_frame.data, _A5_TERM_HEADER)))
all_bytes.extend(_frame_body_bytes(term_frame, 11))
# Find the first valid `0e 08` footer marker.
footer_pos = -1
@@ -806,9 +812,9 @@ def write_blastware_file(
# Frame contribution loop (v0.14.0 BW-exact walk).
# Skip values:
# probe (fi=0): probe_skip
# every later frame: 12 stripped bytes (_raw_skip): 13 raw for an
# address with an inner DLE pair (the metadata
# pages 0x1002 / 0x1004, or a chunk there), else 12
# meta@0x1002 (fi=1): 13 (6-byte inner header)
# meta@0x1004 (fi=2): 13 (6-byte inner header)
# sample chunks (fi=3+): 12 (5-byte inner header)
last_fi = len(body_frames) - 1
log.debug(
@@ -819,7 +825,12 @@ def write_blastware_file(
all_bytes = bytearray()
for fi, frame in enumerate(body_frames):
skip = probe_skip if fi == 0 else _raw_skip(frame.data, _A5_HEADER)
if fi == 0:
skip = probe_skip
elif fi in (1, 2):
skip = 13 # metadata pages
else:
skip = 12 # sample chunks
contribution = _frame_body_bytes(frame, skip)
log.debug("write_blastware_file: fi=%d skip=%d raw_data=%d contribution=%d",
@@ -827,15 +838,14 @@ def write_blastware_file(
all_bytes.extend(contribution)
# Terminator contributes its content, which ends with the 26-byte footer.
# 11 stripped bytes (not 12): the terminator's inner frame header is one
# shorter than a chunk's. Confirmed 2026-04-21.
# skip=11 (not 12) because the terminator's inner frame header is 4 bytes,
# one shorter than chunk frames' 5-byte inner header. Confirmed 2026-04-21.
if term_frame is not None:
term_skip = _raw_skip(term_frame.data, _A5_TERM_HEADER)
term_contribution = _frame_body_bytes(term_frame, term_skip)
term_contribution = _frame_body_bytes(term_frame, 11)
log.debug(
"write_blastware_file: term_frame data_len=%d skip=%d "
"write_blastware_file: term_frame data_len=%d skip=11 "
"contribution_len=%d first8=%s",
len(term_frame.data), term_skip,
len(term_frame.data),
len(term_contribution),
term_contribution[:8].hex() if len(term_contribution) >= 8 else term_contribution.hex(),
)
+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)
+17 -135
View File
@@ -34,7 +34,7 @@ import re
import struct
from typing import Optional
from .framing import S3Frame, unescape_reply
from .framing import S3Frame
from .models import (
CallHomeConfig,
ComplianceConfig,
@@ -60,18 +60,16 @@ from .transport import SerialTransport, BaseTransport
log = logging.getLogger(__name__)
# SUB 0x1C state-flag values measured while a unit was monitoring: 0x10 (BE11529,
# 2026-04-08, 98 frames) and 0x0B (BE9441 recording a histogram, 2026-10-26).
# Idle is 0x00 on both.
S3_MONITORING_FLAGS = frozenset({0x10, 0x0B})
# ── Module-level constants ────────────────────────────────────────────────────
# ⚠ 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).
# Trigger config payload hardcoded from 3-11-26 BW TX capture (BW frame 108).
# No SUB 0x22 read exists in the capture — Blastware writes this fixed blob.
# 29 bytes: [00][1A][D5][00][00][10][03][08][0A] + 18×FF + [00][00]
_TRIGGER_DATA_HARDCODED: bytes = bytes.fromhex(
"001ad500001003080a"
"ffffffffffffffffffffffffffffffffffffff"
"0000"
)
# Compliance ASCII slot format (confirmed from 3-11-26 capture + label search):
# Each label occupies a 64-byte slot.
@@ -452,7 +450,7 @@ class MiniMateClient:
proto.confirm_erase_all()
log.info("delete_all_events: erase confirmed — device memory cleared")
def get_events(self, full_waveform: bool = False, debug: bool = False, stop_after_index: Optional[int] = None, skip_waveform_for_keys: Optional[set] = None, skip_waveform_for_events: Optional[dict] = None, extra_chunks_after_metadata: int = 1, headers_only: bool = False, only_key: Optional[bytes] = None, only_key_timestamp: Optional[str] = None) -> list[Event]:
def get_events(self, full_waveform: bool = False, debug: bool = False, stop_after_index: Optional[int] = None, skip_waveform_for_keys: Optional[set] = None, skip_waveform_for_events: Optional[dict] = None, extra_chunks_after_metadata: int = 1) -> list[Event]:
"""
Download all stored events from the device using the confirmed
1E → 0A → 0C → 5A → 1F event-iterator protocol.
@@ -481,26 +479,8 @@ class MiniMateClient:
Raises:
ProtocolError: on unrecoverable communication failure.
headers_only: never start a 5A -- every event takes the bypass below.
only_key: download only the event with this key (in full, per
full_waveform); walk the others without their 5A, and stop once
that event is read.
only_key_timestamp: with only_key, the ISO timestamp (as
`_event_timestamp_iso` formats it, e.g. "2026-10-01T08:00:00") the
event was listed with. If the 0C at only_key says another time, or
gave none, that event is returned without its 5A -- 1F(arm), POLL
and 5A are not sent -- and the caller reports which.
Strict mode (headers_only, or only_key): a list or a one-event download
must be all or nothing, so a lost 0A or 1F reply re-raises its
ProtocolError instead of skipping an event or ending the walk early,
and a 1F that returns a key already walked raises ProtocolError.
Without those options (legacy) the walk is exactly as it was.
"""
proto = self._require_proto()
strict = headers_only or only_key is not None
# Passed only when on, so the legacy walk's 5A call is unchanged.
strict_5a = {"strict": True} if strict else {}
log.info("get_events: requesting first event (SUB 1E)")
try:
@@ -517,7 +497,6 @@ class MiniMateClient:
events: list[Event] = []
idx = 0
seen: set = set() # strict mode: keys walked, to catch a chain that does not advance
# Legacy bare-key skip set is deprecated: the device's key counter
# resets to 0x01110000 after every memory erase, so a key in this set
@@ -535,10 +514,6 @@ class MiniMateClient:
while data8[4:8] != b"\x00\x00\x00\x00":
cur_key = key4 # key for this event's 0A/1E-arm/0C/5A calls
if strict and cur_key in seen:
raise ProtocolError(
f"event chain did not advance: key {cur_key.hex()} came back twice")
seen.add(cur_key)
log.info("get_events: record %d key=%s", idx, cur_key.hex())
ev = Event(index=idx)
@@ -556,8 +531,6 @@ class MiniMateClient:
)
proceed = False
except ProtocolError as exc:
if strict:
raise
log.warning(
"get_events: 0A failed for key=%s: %s — skipping",
cur_key.hex(), exc,
@@ -604,19 +577,6 @@ class MiniMateClient:
"get_events: key=%s (key, ts=%s) match — skipping 5A bulk download",
cur_key.hex(), actual_ts,
)
elif headers_only or (only_key is not None and cur_key != only_key):
# The same bypass as a (key, ts) match: 0A + 1E(arm) + 0C were
# read; 1F(arm) + POLL + 5A are not sent, and 1F(browse) below is
# safe because no 5A was ever started.
skip_5a = True
elif (only_key is not None and only_key_timestamp is not None
and actual_ts != only_key_timestamp):
# The event at this key is not the one asked for -- erased or
# wrapped since it was listed, or its 0C reply was lost. Do
# not download it; the caller reports which.
log.info("get_events: key=%s is from %r, not %r -- no 5A",
cur_key.hex(), actual_ts, only_key_timestamp)
skip_5a = True
arm_key4: Optional[bytes] = None
a5_ok = False
@@ -657,7 +617,7 @@ class MiniMateClient:
)
a5_frames = proto.read_bulk_waveform_stream(
cur_key, stop_after_metadata=False, max_chunks=128,
include_terminator=True, **strict_5a,
include_terminator=True,
)
if a5_frames:
a5_ok = True
@@ -676,7 +636,7 @@ class MiniMateClient:
cur_key, stop_after_metadata=True,
include_terminator=True,
extra_chunks_after_metadata=extra_chunks_after_metadata,
max_chunks=128, **strict_5a,
max_chunks=128,
)
if a5_frames:
a5_ok = True
@@ -688,8 +648,6 @@ class MiniMateClient:
ev.project_info.operator if ev.project_info else None,
)
except ProtocolError as exc:
if strict:
raise # a one-event download is whole or it is an error
log.warning(
"get_events: 5A failed for key=%s: %s — metadata unavailable",
cur_key.hex(), exc,
@@ -722,8 +680,6 @@ class MiniMateClient:
key4.hex(), data8[4:8].hex(),
)
except ProtocolError as exc:
if strict:
raise
log.warning("get_events: 1F(browse) failed: %s — stopping", exc)
key4 = b"\x00\x00\x00\x00"
data8 = b"\x00\x00\x00\x00\x00\x00\x00\x00"
@@ -757,10 +713,6 @@ class MiniMateClient:
events.append(ev)
idx += 1
if only_key is not None and cur_key == only_key:
log.info("get_events: read key=%s -- stopping", cur_key.hex())
break
# Early exit: if the caller only wants events up to a specific
# index, stop iterating once we've collected it.
if stop_after_index is not None and idx > stop_after_index:
@@ -783,44 +735,12 @@ class MiniMateClient:
key4.hex(), data8[4:8].hex(),
)
except ProtocolError as exc:
if strict:
raise
log.warning("get_events: 1F failed: %s — stopping iteration", exc)
break
log.info("get_events: downloaded %d event(s)", len(events))
return events
def list_event_headers(self) -> list[Event]:
"""Every stored event's 0C record -- timestamp, type, peaks -- without its 5A.
`get_events()` downloads every event in full even for metadata
(`stop_after_metadata` is a no-op), so listing that way costs one
complete download per event. This walks 0A + 1E(arm) + 0C + 1F(browse)
per event -- the bypass `skip_waveform_for_events` already takes -- and
never starts a 5A. The events carry no `_a5_frames`.
"""
return self.get_events(headers_only=True)
def download_event_by_key(self, key4: bytes, *, expected_timestamp: Optional[str] = None) -> Optional[Event]:
"""Download ONE event in full; walk past the events before it without
their 5A. None if no full record has that key.
`get_events(stop_after_index=N)` downloads events 0..N in full and keeps
one; this downloads only the one asked for.
`expected_timestamp` (ISO, as `_event_timestamp_iso` writes it): the
time the event was listed with. If the 0C read at that key says
otherwise -- or could not be read -- the event comes back without its
5A (`_a5_frames` None) and nothing is downloaded; the caller compares
the timestamp and says which.
"""
for ev in self.get_events(full_waveform=True, only_key=key4,
only_key_timestamp=expected_timestamp):
if ev._waveform_key == key4:
return ev
return None
def download_waveform(self, event: Event) -> None:
"""
Download the full raw ADC waveform for a previously-retrieved event
@@ -956,17 +876,6 @@ class MiniMateClient:
"""
proto = self._require_proto()
# Every block is checked before the first frame goes out (review of #46,
# 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)
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)
# 68 → 73
log.info("push_config_raw: write event index (SUB 68)")
proto.write_event_index(event_index_data)
@@ -1045,7 +954,7 @@ class MiniMateClient:
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)
trigger_data : 29 bytes — hardcoded from 3-11-26 capture
waveform_data : 204 bytes — read live via SUB 09
Raises:
@@ -1065,8 +974,7 @@ class MiniMateClient:
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
trigger_data = _TRIGGER_DATA_HARDCODED # 29 bytes
# 2. Patch the compliance buffer and build the 2128-byte write payload
compliance_data = _encode_compliance_config(
@@ -1212,17 +1120,6 @@ class MiniMateClient:
log.debug("poll: startup handshake")
proto.startup()
def read_serial(self) -> str:
"""The unit's own serial (SUB 0x15), on an open, polled session. The
cheap identity read the legacy write routes check before writing."""
return _decode_serial_number(self._require_proto().read(SUB_SERIAL_NUMBER)).serial
def wake(self, attempt_s: float = 5.0, deadline_s: float = 60.0) -> None:
"""SESSION_RESET + POLL, re-sent until the unit answers (see
MiniMateProtocol.wake) -- for a unit that may be busy, e.g. sensor-checking
right after a start."""
self._require_proto().wake(attempt_s=attempt_s, deadline_s=deadline_s)
# ── Monitoring ────────────────────────────────────────────────────────────
def get_monitor_status(self) -> MonitorStatus:
@@ -1334,15 +1231,12 @@ def _decode_serial_number(data: bytes) -> DeviceInfo:
# Actual serial payload starts at data[11].
actual = data[11:] if len(data) > 11 else data
# The serial is a C string: cut at the first NUL. A short serial leaves a
# stray byte after its terminator (BE9441 sends b"BE9441\x00?"), so
# stripping trailing NULs alone is not enough.
if len(actual) < 9:
# Short payload — gracefully degrade
serial = actual.split(b"\x00", 1)[0].decode("ascii", errors="replace")
serial = actual.rstrip(b"\x00").decode("ascii", errors="replace")
return DeviceInfo(serial=serial, firmware_minor=0)
serial = actual[:8].split(b"\x00", 1)[0].decode("ascii", errors="replace")
serial = actual[:8].rstrip(b"\x00").decode("ascii", errors="replace")
trail_0 = actual[8] if len(actual) > 8 else None
fw_minor = actual[9] if len(actual) > 9 else 0
@@ -2707,10 +2601,6 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
mem_total 0x000EFFF2 = 983026 bytes ≈ 960 KB
mem_free 0x000E9E52 = 958034 bytes ≈ 935 KB
"""
# Unescape first (2026-10-26): BE9441's free memory 0x000D0E04 arrived as
# `0d 0e 10 04`, and with the parser's kept 10 every field counted from the
# end read one byte off -- 419.84 V and 251,655,168 bytes for 6.76 V and 983,028.
data = unescape_reply(data)
# The data section starts at offset 11 (after the S3 section header).
section = data[11:] if len(data) > 11 else data
@@ -2723,14 +2613,7 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
# Confirmed from byte diff of all 144 0xE3 data frames in 4-8-26/2ndtry capture:
# section[1] = 0x00 in all IDLE frames, 0x10 in all MONITORING frames.
# (section[6] also changes but has non-binary values 0xea/0x07 — device-specific.)
#
# 2026-10-26: 0x0B on BE9441 recording a HISTOGRAM (confirmed at the unit);
# 0x00 on the same unit idle. Only measured values count as monitoring --
# sfm.device_access.s3.S3_RUN_STATES refuses any other for a change.
is_monitoring = len(section) > 1 and section[1] in S3_MONITORING_FLAGS
# The same byte, raw -- but only from a real section: for data of 11 bytes
# or fewer, `section` above falls back to the header itself.
state_flag = data[12] if len(data) > 12 else None
is_monitoring = len(section) > 1 and section[1] == 0x10
battery_v = None
memory_total = None
@@ -2756,7 +2639,6 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
battery_v=battery_v,
memory_total=memory_total,
memory_free=memory_free,
state_flag=state_flag,
)
+161 -29
View File
@@ -50,7 +50,7 @@ SIDECAR_KIND = "sfm.event"
# bumped without a `pip install` re-run — leading to confusing stale
# version stamps in sidecars. Bump this constant and CHANGELOG.md
# together at release time.
TOOL_VERSION = "0.31.0" # +/sensor_check group (schema v2); gates the backfill regen
TOOL_VERSION = "0.32.0" # waveform times from the event record, report dates, histogram reader; gates the backfill regen
try:
# Best-effort: prefer the installed metadata when it's NEWER than the
@@ -157,6 +157,9 @@ def _bw_report_to_dict(report: BwAsciiReport) -> dict:
"available": True,
"event_type": report.event_type,
"version": report.version,
# Blastware's exact trigger, so a backfill can re-apply it
# (apply_bw_report_dict_to_event); absent from sidecars before 0.32.0.
"event_datetime": report.event_datetime.isoformat() if report.event_datetime else None,
"trigger": {
"channel": report.trigger_channel,
"geo_level_ips": report.geo_trigger_level_ips,
@@ -296,16 +299,29 @@ def apply_report_to_event(event: Event, report: BwAsciiReport) -> None:
event.sample_rate = report.sample_rate_sps
if report.record_time_s is not None:
event.rectime_seconds = report.record_time_s
# The report's event_datetime is Blastware's exact trigger time (parsed
# from Event Time + Event Date). Prefer it over the binary footer's stop
# time so a report-paired import matches BW to the second.
edt = report.event_datetime
if edt is not None:
event.timestamp = Timestamp(
raw=b"", flag=0x10,
year=edt.year, unknown_byte=0, month=edt.month, day=edt.day,
hour=edt.hour, minute=edt.minute, second=edt.second,
)
# The report's event_datetime is Blastware's copy of the unit's trigger time
# (Event Time + Event Date) -- see _apply_report_time.
if report.event_datetime is not None:
_apply_report_time(event, report.event_datetime)
def _apply_report_time(event: Event, edt: datetime.datetime) -> None:
"""A paired report's time fills in only when the instrument's own event
record gave none. Against a validated record it is a cross-check: a
disagreement is logged and the record kept. (They agree on 1,320/1,320.)"""
if event.timestamp_source == "event_record" and event.timestamp is not None:
ts = event.timestamp
cur = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
if cur != edt.replace(microsecond=0):
log.warning("event record says %s, its paired report %s; the event record "
"is kept", cur, edt)
return
event.timestamp = Timestamp(
raw=b"", flag=0x10,
year=edt.year, unknown_byte=0, month=edt.month, day=edt.day,
hour=edt.hour, minute=edt.minute, second=edt.second,
)
event.timestamp_source = "report"
def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
@@ -371,6 +387,16 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
rt = rec.get("record_time_s")
if rt is not None:
event.rectime_seconds = rt
# As apply_report_to_event: the report's time fills in only without a
# validated event record (_apply_report_time).
edt = bw_report.get("event_datetime")
if edt:
try:
t = datetime.datetime.fromisoformat(edt)
except (TypeError, ValueError):
t = None
if t is not None:
_apply_report_time(event, t)
def _project_info_to_dict(pi: Optional[ProjectInfo]) -> dict:
@@ -427,9 +453,8 @@ def event_to_sidecar_dict(
supplies a non-empty value (the report mirrors the device's
compliance config, which is what BW shows in its event report).
- ``event.timestamp`` is overlaid from the report's Event Date +
Event Time (BW's report timestamps are second-resolution and
match the binary's footer; we prefer the report value because
the BW-binary footer timestamp can drift on some firmware).
Event Time -- unless it came from the instrument's own embedded event
record, which the report only cross-checks (see _apply_report_time).
"""
if source_kind not in {"sfm-live", "sfm-ach", "bw-import", "idf-import"}:
raise ValueError(f"unknown source_kind: {source_kind!r}")
@@ -438,7 +463,7 @@ def event_to_sidecar_dict(
# ── Overlay event fields from the report when present ───────────────────
timestamp_iso = _ts_iso(event.timestamp)
if bw_report and bw_report.event_datetime:
if bw_report and bw_report.event_datetime and event.timestamp_source != "event_record":
timestamp_iso = bw_report.event_datetime.isoformat()
# Build peak_values, optionally overlaid from the report. The report
@@ -468,6 +493,7 @@ def event_to_sidecar_dict(
event_block = {
"serial": serial,
"timestamp": timestamp_iso,
"timestamp_source": event.timestamp_source,
"waveform_key": event._waveform_key.hex() if event._waveform_key else None,
"record_type": event.record_type,
"sample_rate": event.sample_rate,
@@ -475,6 +501,8 @@ def event_to_sidecar_dict(
"total_samples": event.total_samples,
"pretrig_samples": event.pretrig_samples,
}
if event.decode_problems:
event_block["decode_problems"] = list(event.decode_problems)
if bw_report:
# Report values are authoritative — they're the user-configured
# values BW reads back, not STRT-derived guesses. In particular
@@ -822,11 +850,75 @@ def derive_record_type_from_filename(filename, default: str = "Waveform") -> str
# float32 within it. The configured post-trigger record time (seconds) is a
# big-endian float32 exactly 30 bytes before the "Standard Recording Setup"
# label. Verified across the corpus reading 1.0 / 2.0 / 3.0 s on different
# setups — and ts2 - record_time reproduces Blastware's trigger to the second
# (N844LQHB: stop 10:33:32 - 3.0 = 10:33:29).
# setups. ⚠ ts2 - record_time is only an estimate of the trigger: a second off
# on ~19% of files (measured 2026-10-26); the event record below is exact.
_RECSETUP_MARKER = b"Standard Recording Setup"
_RECTIME_OFFSET_BEFORE_MARKER = 30
# The instrument's own event record, which the unit sends in its 5A stream and
# Blastware therefore copies into every waveform file (measured 2026-10-26; see
# the Series-III reference, "The embedded event record"):
#
# [-6:-2] 00 28 05 00 [0:2] fe 80 [2:10] trigger [10:18] stop
#
# each time `dd mm yyyy(BE) 00 hh mm ss`. On 7,935 waveforms exactly one
# candidate passes every check below, and its trigger equals Blastware's report
# (1,320/1,320), its filename (7,935/7,935) and the unit's own 0C record.
_EVENT_RECORD_LEAD = b"\x00\x28\x05\x00"
_EVENT_RECORD_MARKER = b"\xfe\x80"
# (stop - trigger) - record time, seconds. Measured -3 .. +6 on 7,935 files.
_EVENT_RECORD_SLACK_S = (-5.0, 10.0)
def _ts8(b: bytes) -> Optional[datetime.datetime]:
"""`dd mm yyyy(BE) 00 hh mm ss`, strictly: the zero byte must be zero."""
if len(b) < 8 or b[4] != 0:
return None
try:
return datetime.datetime((b[2] << 8) | b[3], b[1], b[0], b[5], b[6], b[7])
except ValueError:
return None
def _embedded_event_record(
raw: bytes, end: int, start: Optional[datetime.datetime],
stop: Optional[datetime.datetime], record_time: Optional[float],
) -> tuple[Optional[datetime.datetime], str]:
"""The trigger time from the instrument's embedded event record, or (None, why).
Every `fe 80` before `end` (the footer) is a candidate. One counts only if
its lead bytes match, both its times are well formed, the footer's session
start <= trigger <= its stop, its stop is the footer's stop or a second
before it, and its length agrees with the record time. Exactly one may
pass: none, or more than one, is reported rather than guessed between.
"""
if start is None or stop is None:
return None, "the footer has no start and stop to check one against"
found, rejected = [], 0
i = raw.find(_EVENT_RECORD_MARKER, 6)
while 0 <= i and i + 18 <= end:
trig, rec_stop = _ts8(raw[i + 2:i + 10]), _ts8(raw[i + 10:i + 18])
valid = (
raw[i - 6:i - 2] == _EVENT_RECORD_LEAD
and trig is not None and rec_stop is not None
and start <= trig <= rec_stop
and 0 <= (stop - rec_stop).total_seconds() <= 1
and (record_time is None
or _EVENT_RECORD_SLACK_S[0]
<= (rec_stop - trig).total_seconds() - record_time
<= _EVENT_RECORD_SLACK_S[1])
)
if valid:
found.append(trig)
else:
rejected += 1
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
if len(found) == 1:
return found[0], ""
if found:
return None, f"{len(found)} candidates validate"
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
"""The configured post-trigger record time in seconds, from the recording-
@@ -842,14 +934,28 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
return rt if 0.05 <= rt <= 600.0 else None
def read_blastware_file(path: Union[str, Path]) -> Event:
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
"""Parse a Blastware event file into an Event: `decode_blastware_bytes` on its
bytes, `name` defaulting to the file's own (see there -- never a time source)."""
path = Path(path)
return decode_blastware_bytes(path.read_bytes(), name=name or path.name)
def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
"""
Parse a Blastware waveform file into an Event.
Parse a Blastware event's bytes into an Event. No filename is needed.
`name`, when given, labels the record type and is compared with the decoded
time -- a disagreement is logged -- but never supplies it: an event SFM
receives straight from a unit has no Blastware name.
Recovers:
- waveform_key, rectime_seconds, total_samples, pretrig_samples
(from the STRT record)
- timestamp (from the footer's start-time field)
- timestamp: a waveform's from the instrument's embedded event record
(`timestamp_source` "event_record"); without a validated one, an
estimate from the footer with a `decode_problems` entry; a histogram's
from the footer start ("footer")
- project_info (from ASCII labels embedded in the body)
- raw_samples (Tran/Vert/Long/MicL int16 lists)
- peak_values (computed from raw_samples; approximate — see notes
@@ -860,21 +966,20 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
byte-for-byte regeneration of the BW file from this Event alone is
not possible — the on-disk BW file IS the byte-for-byte source.
"""
path = Path(path)
raw = path.read_bytes()
label = name or "<bytes>"
if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26:
raise ValueError(f"{path}: file too short ({len(raw)} bytes) to be a BW event")
raise ValueError(f"{label}: file too short ({len(raw)} bytes) to be a BW event")
# Header: validate magic prefix.
header = raw[:_bw._WAVEFORM_HEADER_SIZE]
if not header.startswith(_bw._FILE_HEADER_PREFIX):
raise ValueError(f"{path}: not a Blastware file (bad header prefix)")
raise ValueError(f"{label}: not a Blastware file (bad header prefix)")
# STRT record: 21 bytes immediately after the header.
strt_raw = raw[_bw._WAVEFORM_HEADER_SIZE : _bw._WAVEFORM_HEADER_SIZE + 21]
strt_fields = _decode_strt(strt_raw)
if not strt_fields:
raise ValueError(f"{path}: STRT record missing or malformed")
raise ValueError(f"{label}: STRT record missing or malformed")
# Footer: locate the 0e 08 marker, validating the year is in a sane range.
body_start = _bw._WAVEFORM_HEADER_SIZE + 21
@@ -913,7 +1018,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
if footer_pos < 0 and len(raw) >= 26:
footer_pos = len(raw) - 26
if footer_pos < body_start:
raise ValueError(f"{path}: footer not found")
raise ValueError(f"{label}: footer not found")
body = raw[body_start : footer_pos]
footer = raw[footer_pos : footer_pos + 26]
@@ -960,7 +1065,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
if decoded is None:
log.warning(
"%s: body codec failed to decode (body starts %s) — "
"raw_samples will be empty", path, body[:8].hex(" "),
"raw_samples will be empty", label, body[:8].hex(" "),
)
samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
else:
@@ -981,7 +1086,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
# ".bw" suffix, so the derivation falls back to "Waveform" and the
# caller overrides ev.record_type using the original filename — see
# waveform_store.save_imported_bw.
ev.record_type = derive_record_type_from_filename(path.name)
ev.record_type = derive_record_type_from_filename(name)
ev.rectime_seconds = strt_fields.get("rectime_seconds")
ev.total_samples = strt_fields.get("total_samples")
ev.pretrig_samples = strt_fields.get("pretrig_samples")
@@ -999,11 +1104,37 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
# * Histogram / undecodable: ts1 = the window start, which IS the event
# time — keep it.
# Discriminate by ``is_waveform_body`` (the codec), not the filename.
#
# ⚠ 2026-10-26 (measured): ts2 - record time is a second off on ~19% of
# waveforms. The exact trigger is in the instrument's own event record,
# embedded in the 5A stream (_embedded_event_record), so a waveform takes
# it from there. Without a validated one the estimate stands, reported as a
# decode problem -- never a filename's time, which is only a cross-check.
# Histograms stay on ts1 although it runs a second early on 97% (their
# record, marker fe f5, holds the exact start): in Blastware's timing a
# waveform and its histogram share a second 209 times in prod's store, and
# events is unique on (serial, timestamp) -- #51.
if is_waveform_body and ts2 is not None:
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
ts2.hour, ts2.minute, ts2.second)
_rt = _parse_record_time_seconds(raw)
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop
_start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second)
if ts1 is not None else None)
_trig, _why = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
if _trig is not None:
ev.timestamp_source = "event_record"
else:
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop
ev.timestamp_source = "estimate"
_problem = (f"no validated embedded event record ({_why}); the time is "
"estimated as the footer stop minus the record time, which is a "
"second off on ~19% of measured files")
ev.decode_problems.append(_problem)
log.warning("%s: %s", label, _problem)
_named = _bw.blastware_filename_time(name) if name else None
if _named is not None and _named != _trig:
log.warning("%s: decoded event time %s (%s) disagrees with the filename's %s; "
"the decoded time is kept", label, _trig, ev.timestamp_source, _named)
ev.timestamp = Timestamp(
raw=footer[10:18],
flag=0x10,
@@ -1017,6 +1148,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day,
hour=ts1.hour, minute=ts1.minute, second=ts1.second,
)
ev.timestamp_source = "footer"
ev.project_info = ProjectInfo(
project=project, client=client, operator=user, sensor_location=seisloc,
+94 -118
View File
@@ -28,10 +28,6 @@ De-stuffed payload layout:
DLE stuffing rule: any 0x10 byte in the payload is doubled on the wire (0x10 → 0x10 0x10).
This applies to the checksum byte too.
⚠ AMENDED 2026-10-26 (measured): a request escapes FOUR values, not one -- every 02, 03,
04 and 10 in payload and checksum gets a DLE in front. Blastware's 748 recorded requests
re-encode byte-identically under that rule (tests/test_5a_blastware_walk.py); a bare 02 or
03 left a request unanswered. See `s3_stuff()`.
Confirmed from live captures (s3_parser.py validation + raw_bw.bin / raw_s3.bin).
"""
@@ -87,24 +83,6 @@ def dle_unstuff(data: bytes) -> bytes:
# ── Checksum ─────────────────────────────────────────────────────────────────
# Every byte value a request DLE-escapes (2026-10-26, measured): Blastware's 748
# requests from a whole download session re-encode byte-identically with this set,
# payload and checksum alike. A bare 0x02 checksum or a 0x03 inside the params left
# BE9441 silent (and the 0x02 made it reset ~11 s later). It is a Micromate's set
# too (micromate.framing._ESCAPED).
_ESCAPED = frozenset({STX, ETX, 0x04, DLE})
def s3_stuff(data: bytes) -> bytes:
"""Escape every byte a request escapes: `XX` → `10 XX` for 02, 03, 04 and 10."""
out = bytearray()
for b in data:
if b in _ESCAPED:
out.append(DLE)
out.append(b)
return bytes(out)
def checksum(payload: bytes) -> int:
"""SUM8: sum of all de-stuffed payload bytes, mod 256."""
return sum(payload) & 0xFF
@@ -112,34 +90,13 @@ def checksum(payload: bytes) -> int:
# ── BW→S3 frame builder ───────────────────────────────────────────────────────
# SUB byte for 5A (protocol.py has the full constant set; defined here to
# avoid a circular import).
# SUB byte for 5A — used by build_5a_frame below (protocol.py has the full
# constant set; defined here to avoid a circular import).
SUB_5A = 0x5A
def build_5a_request(address: int, length: int) -> bytes:
"""A SUB 5A read of `length` bytes at the unit's 32-bit `address`.
Measured 2026-10-26 from Blastware downloading all 8 of BE9441's events (four
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.
"""
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.
@@ -226,14 +183,7 @@ def build_5a_frame(offset_word: int, raw_params: bytes) -> bytes:
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])
return bytes([ACK, STX]) + bytes(s) + bytes([chk, ETX])
def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> bytes:
@@ -253,7 +203,7 @@ def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> byte
byte lives at params[6] (= payload[12]). Use waveform_key_params() and
token_params() helpers to build these safely.
Wire output: [ACK] [STX] s3_stuff(payload + checksum) [ETX]
Wire output: [ACK] [STX] dle_stuff(payload + checksum) [ETX]
Args:
sub: SUB command byte (e.g. 0x01 = FULL_CONFIG_READ)
@@ -276,7 +226,7 @@ def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> byte
offset_lo = offset & 0xFF
payload = bytes([BW_CMD, 0x00, sub, 0x00, offset_hi, offset_lo]) + params
chk = checksum(payload)
wire = bytes([ACK, STX]) + s3_stuff(payload + bytes([chk])) + bytes([ETX])
wire = bytes([ACK, STX]) + dle_stuff(payload + bytes([chk])) + bytes([ETX])
return wire
@@ -284,34 +234,103 @@ def build_bw_write_frame(
sub: int,
data: bytes,
*,
offset: Optional[int] = None,
offset: int = 0,
params: bytes = bytes(10),
) -> bytes:
"""A write request: the standard 16-byte request followed by `data`, escaped
and checksummed like every other request (s3_stuff, SUM8).
"""
Build a BW→S3 write-command frame.
`offset` is the payload's [4:6] field -- the data's LENGTH; it defaults to
len(data), which is what Blastware sends on every write on record.
Write frames extend the standard 16-byte read header with a variable-length
data payload. They use a different checksum formula from read frames.
Measured 2026-10-26/27 (issue #46): all of Blastware's requests from February
to October 2026 -- 3,869 frames in the uploaded captures plus BE9441's 26
write frames tonight -- rebuild byte for byte this way, the 77 write frames
that carry data included (event index 68, compliance 71, trigger 82, waveform
data 69).
**CRITICAL: Write frames use minimal DLE stuffing.**
⚠ RETRACTED: "only BW_CMD is doubled, everything else raw" and the "DLE-aware
checksum" `(sum of payload[2:] skipping 0x10) + 0x10`. That model rebuilt the
March frames only because it was fitted to data that still held its escape
bytes; the "data length 91, offset 90" it explained was 90 bytes plus one
escape. It got 7 of every 13 frames in a config write wrong.
Unlike read frames (build_bw_frame), write frames do NOT apply full DLE
stuffing to the payload. Only the BW_CMD byte (0x10) at position [0] is
doubled to 0x10 0x10 on the wire. All other bytes — flags, sub, offset,
params, data, and checksum — are written RAW with no stuffing, even if they
contain 0x10 bytes (e.g. offset_hi=0x10 for compliance chunks, or 0x10
bytes in the write data payload).
Confirmed from 3-11-26 BW TX capture (frames 102–112): all 11 write frames
match the rule "double BW_CMD only; everything else raw." ✅ 2026-04-07.
Wire layout:
[41] ACK
[02] STX
[10 10] BW_CMD doubled (the ONLY DLE stuffing applied)
[00] flags
[sub] write command byte (0x68–0x83)
[00] always zero
[hi][lo] offset as uint16 BE (raw; NOT stuffed even if hi=0x10)
[params] 10 bytes (raw)
[data] variable-length write payload (raw; NOT stuffed)
[chk] checksum byte (raw; NOT stuffed even if 0x10)
[03] ETX
De-stuffed payload (for checksum computation):
[0] BW_CMD 0x10
[1] flags 0x00
[2] SUB write command byte
[3] 0x00 always zero
[4] offset_hi
[5] offset_lo
[6:16] params 10 bytes
[16:] data write payload
[-1] chk
**Checksum formula (confirmed 2026-03-12 from 3-11-26 BW TX capture):**
chk = (sum(b for b in payload[2:] if b != 0x10) + 0x10) % 256
where payload = destuffed content BEFORE appending chk.
This skips all 0x10 bytes in payload[2:] (sub onwards), including any
0x10 bytes in the offset, params, data, and the checksum byte itself.
The offset field [4:6] meaning per write SUB:
- SUBs 68, 69, 82 (single-chunk writes): offset = data[1] + 2, where
data[1] is an embedded length field in the write payload.
Confirmed from capture: 68→0x5A (data[1]=0x58+2), 82→0x1C
(data[1]=0x1A+2), 69→0xCA (data[1]=0xC8+2).
- SUB 71 (multi-chunk compliance): 0x1004 for full chunks, 0x002C
for the final partial chunk.
- Confirm frames (72, 73, 74, 83): offset=0, no data.
Args:
sub: Write command SUB byte.
data: Write payload (variable length; empty for confirm frames).
offset: 16-bit value placed at [4:6]. See per-SUB notes above.
params: 10 bytes placed at [6:16]. All-zero for most writes; compliance
chunk writes use chunk-specific values.
Returns:
Complete frame bytes ready to write to the transport.
"""
if len(params) != 10:
raise ValueError(f"params must be exactly 10 bytes, got {len(params)}")
length = len(data) if offset is None else offset
if not 0 <= length <= 0xFFFF:
raise ValueError(f"length must fit in 16 bits, got {length:#x}")
payload = bytes([BW_CMD, 0x00, sub, 0x00, (length >> 8) & 0xFF, length & 0xFF]) + params + data
return bytes([ACK, STX]) + s3_stuff(payload + bytes([checksum(payload)])) + bytes([ETX])
if offset > 0xFFFF:
raise ValueError(f"offset must fit in uint16, got {offset:#06x}")
offset_hi = (offset >> 8) & 0xFF
offset_lo = offset & 0xFF
# Destuffed payload (used only for checksum; not sent directly)
payload_no_chk = bytes([BW_CMD, 0x00, sub, 0x00, offset_hi, offset_lo]) + params + data
# Large-frame checksum: sum payload[2:] skipping all 0x10 bytes, add 0x10.
# Applied to the destuffed representation — confirms correctly against
# all 11 write frames in the 3-11-26/170151 BW TX capture. ✅
chk = (sum(b for b in payload_no_chk[2:] if b != 0x10) + 0x10) & 0xFF
# Wire construction: only BW_CMD is doubled; everything else is raw.
# Do NOT use dle_stuff() here — that would incorrectly double 0x10 bytes
# in the offset, params, and data sections.
wire = (
bytes([ACK, STX]) # Frame prefix (not part of payload)
+ bytes([BW_CMD, BW_CMD]) # BW_CMD doubled (only DLE stuffing applied)
+ payload_no_chk[1:] # flags, sub, offset, params, data — RAW
+ bytes([chk]) # checksum — RAW
+ bytes([ETX]) # Frame terminator
)
return wire
def waveform_key_params(key4: bytes) -> bytes:
@@ -370,9 +389,6 @@ def token_params(token: int = 0) -> bytes:
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:
@@ -418,9 +434,6 @@ def bulk_waveform_params(key4: bytes, counter: int, *, is_probe: bool = False) -
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
@@ -457,9 +470,6 @@ def bulk_waveform_term_v2(
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):
@@ -531,42 +541,8 @@ def bulk_waveform_term_v2(
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."""
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):
i += 1
continue
out.append(data[i])
i += 1
return bytes(out)
def parse_strt_end_key(a5_data: bytes) -> Optional[int]:
"""The event's FULL 32-bit end key from the STRT record in an A5 reply's
data, or None. The page byte is part of it: an event that ends in the next
64 KB page reads e.g. 0x011216C4 here, where `parse_strt_end_offset` gave
0x16C4. Read after `unescape_reply`."""
out = unescape_reply(a5_data)
pos = out.find(STRT_MARKER)
if pos < 0 or pos + 10 > len(out):
return None
return int.from_bytes(out[pos + 6:pos + 10], "big")
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.
Extract the event-end offset from the STRT record in an A5 response payload.
The first A5 response (the probe response, or the first chunk for events
+184 -134
View File
@@ -255,18 +255,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]:
@@ -291,7 +298,9 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
"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],
}
@@ -328,160 +337,201 @@ 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)
# [-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 zero word is 0000 -- what tells a 16-byte layout from a
20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24)."""
z = rec - 4
for k in range(m):
q = off + _MULTI_HEADER_LEN + rec * k
if q + rec > len(body) or body[q + z] or body[q + z + 1]:
return False
return True
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]),
"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):
if (r["meta_var"][:2] != b"\x00\x00"
or max(r["t_peak"], r["v_peak"], r["l_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
+9 -5
View File
@@ -553,6 +553,15 @@ class Event:
# shape diagnostic (rendered fit-to-box). None when absent.
sensor_check: Optional[dict] = None # {"Tran": [...], ..., "MicL": [...]}
# 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.
# Exposed by the SFM server via ?debug=true so field layouts can be verified.
@@ -660,8 +669,3 @@ class MonitorStatus:
battery_v: Optional[float] = None # Battery voltage in volts ✅
memory_total: Optional[int] = None # Total flash memory in bytes ✅
memory_free: Optional[int] = None # Free flash memory in bytes ✅
# The raw flag byte `is_monitoring` is derived from: section[1] = data[12].
# Measured: 0x00 idle, 0x10 monitoring. None when the section is too short
# to hold it. Kept raw so a caller can refuse a value never measured,
# where `is_monitoring` reads anything but 0x10 as idle.
state_flag: Optional[int] = None
+404 -335
View File
@@ -29,12 +29,14 @@ from .framing import (
S3Frame,
S3FrameParser,
build_bw_frame,
build_5a_frame,
build_bw_write_frame,
waveform_key_params,
token_params,
parse_strt_end_key,
unescape_reply,
build_5a_request,
bulk_waveform_params,
bulk_waveform_term_params,
bulk_waveform_term_v2,
parse_strt_end_offset,
POLL_PROBE,
POLL_DATA,
SESSION_RESET,
@@ -121,49 +123,23 @@ DATA_LENGTHS: dict[int, int] = {
# NOT handled here — requires specialised read logic.
}
# SUB 5A (BULK_WAVEFORM_STREAM) walk constants. A 5A request is a read of a
# LENGTH at a 32-bit ADDRESS (measured 2026-10-26 against Blastware; see
# read_bulk_waveform_stream and framing.build_5a_request).
_BULK_TERM_OFFSET = 0x005A # TERM length when the end is unknown (legacy fallback only)
_BULK_COUNTER_STEP = 0x0200 # bytes per chunk read, and the step between addresses
# A sanity bound on the size STRT claims, not a measured limit: BE units report
# 983,026 bytes of memory (SUB 1C) and the largest archived event is ~850 KB. A
# claim past this is a misread STRT, refused before walking megabytes of garbage.
_BULK_MAX_EVENT_BYTES = 0x400000 # 4 MiB
# Config writes (issue #46, measured on every Blastware write since February 2026).
_COMPLIANCE_CHUNK = 0x0200
# The two bytes after a block's N header bytes, when the read returned only N:
# Blastware's own, constant on record -- event index 02 00, trigger 00 00. The
# unit evidently does not check them (they are no CRC, and the compliance
# image's went out stale, unchanged across two different sends).
_WRITE_TAIL = {SUB_EVENT_INDEX_WRITE: b"\x02\x00", SUB_TRIGGER_CONFIG_WRITE: b"\x00\x00",
SUB_WAVEFORM_DATA_WRITE: b"\x00\x00", SUB_COMPLIANCE_WRITE: b"\x00\x00",
SUB_CALL_HOME_WRITE: b"\x00\x00"}
def write_image(sub: int, data: bytes) -> bytes:
"""The whole block a write sends: `data` unescaped, N + 2 bytes.
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
parser's kept escape bytes (10 02 / 10 03 / 10 04), which come out here.
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))
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")
if len(image) == n:
image += _WRITE_TAIL[sub]
elif len(image) != n + 2:
raise ValueError(
f"write SUB 0x{sub:02X}: {len(image)} bytes, but its header says {n} (+ 2) -- "
"not a whole block (a stray byte?); nothing sent")
return image
# SUB 5A (BULK_WAVEFORM_STREAM) protocol constants.
#
# 2026-05-01 minimal-fix: the chunk-counter walk is now bounded by the event's
# `end_offset` extracted from the STRT record at data[23:27] of the probe
# response. Without this bound the loop kept asking for chunks past the event
# end and the device responded with post-event circular-buffer garbage,
# corrupting reconstructed Blastware files for events ≥ 2 sec.
#
# We keep the OLD 0x0400 chunk step here (BW actually uses 0x0200 — see §7.8.5
# of the protocol reference for the corrected understanding) because the
# existing blastware_file.py builder relies on the 0x0400-step frame structure
# to produce valid files. Switching to BW's 0x0200 step is a separate task
# that also requires updating the file builder.
# BW-exact protocol values (v0.14.0). Verified against 4-27-26 + 5-1-26 captures.
_BULK_CHUNK_OFFSET = 0x1002 # offset_word for probe + all chunk requests
_BULK_TERM_OFFSET = 0x005A # offset_word for the legacy terminator (fallback only)
_BULK_COUNTER_STEP = 0x0200 # chunk counter increment (matches chunk payload size)
# Default timeout values (seconds).
# MiniMate Plus is a slow device — keep these generous.
@@ -236,7 +212,7 @@ class MiniMateProtocol:
ProtocolError: if either POLL step fails.
"""
log.debug("startup: draining boot string")
booting = self._drain_boot_string()
self._drain_boot_string()
# Send session-reset signal (ACK+ETX) before the first POLL probe.
# Confirmed from 4-8-26 BW TX captures: Blastware always sends this
@@ -247,17 +223,10 @@ class MiniMateProtocol:
log.debug("startup: POLL probe")
self._send(POLL_PROBE)
try:
# A banner already drained means the unit is booting: a short wait,
# then the re-poll loop, rather than the full timeout.
probe_rsp = self._await_poll_or_boot(
self._BOOT_POLL_S if booting else self._recv_timeout)
except TimeoutError:
if not booting:
raise
probe_rsp = None
if probe_rsp is None:
probe_rsp = self._poll_until_booted()
probe_rsp = self._recv_one(
expected_sub=_expected_rsp_sub(SUB_POLL),
timeout=self._recv_timeout,
)
log.debug(
"startup: POLL probe response page_key=0x%04X", probe_rsp.page_key
)
@@ -324,35 +293,6 @@ class MiniMateProtocol:
log.debug("read SUB=0x%02X: received %d data bytes", sub, len(data_rsp.data))
return data_rsp.data
def wake(self, attempt_s: float = 5.0, deadline_s: float = 60.0) -> S3Frame:
"""SESSION_RESET + POLL, re-sent every `attempt_s` until the unit answers.
A monitoring unit ignores everything until SESSION_RESET (2026-04-08), and
right after a start it runs its sensor check (~30 s, Brian, 2026-10-26).
BE9441 left a POLL sent 2 s after a start unanswered and never answered
it later, so one try with a long wait is not enough: ask again until the
unit answers or `deadline_s` passes. A read -- nothing but SESSION_RESET
and POLL is sent. Returns the POLL data frame.
"""
deadline = time.monotonic() + deadline_s
while True:
self._parser.reset()
self._send(SESSION_RESET)
self._send(POLL_PROBE)
try:
self._recv_one(expected_sub=_expected_rsp_sub(SUB_POLL), timeout=attempt_s)
break
except TimeoutError:
if time.monotonic() >= deadline:
raise TimeoutError(
f"the unit did not answer a POLL within {deadline_s:.0f} s "
f"(asked every {attempt_s:.0f} s)") from None
self._send(SESSION_RESET)
self._send(POLL_DATA)
rsp = self._recv_one(expected_sub=_expected_rsp_sub(SUB_POLL), timeout=attempt_s)
self._drain_boot_string(drain_ms=300) # a late answer to an earlier try, if any
return rsp
def poll(self) -> S3Frame:
"""
Send a single POLL (SUB 5B) probe+data cycle and return the data response.
@@ -418,9 +358,7 @@ class MiniMateProtocol:
self._send(build_bw_frame(SUB_EVENT_INDEX, length))
data_rsp = self._recv_one(expected_sub=rsp_sub)
# Unescaped first (2026-10-27): a 02/03/04 inside the block arrives as
# 10 0X and the parser keeps both, so a slice by length came up short.
raw = unescape_reply(data_rsp.data)[11 : 11 + length]
raw = data_rsp.data[11 : 11 + length]
log.debug("read_event_index: got %d bytes", len(raw))
return raw
@@ -552,7 +490,7 @@ class MiniMateProtocol:
self._send(build_bw_frame(SUB_WAVEFORM_DATA, length))
data_rsp = self._recv_one(expected_sub=rsp_sub)
raw = unescape_reply(data_rsp.data)[11:] # unescaped, as read_event_index
raw = data_rsp.data[11:]
log.debug("read_waveform_data_raw: got %d bytes", len(raw))
return raw
@@ -600,47 +538,53 @@ class MiniMateProtocol:
max_chunks: int = 256, # safety cap only; loop is bounded by end_offset
include_terminator: bool = False,
extra_chunks_after_metadata: int = 1, # DEPRECATED — no-op
strict: bool = False,
) -> list[S3Frame]:
"""
Download the SUB 5A (BULK_WAVEFORM_STREAM) A5 frames for one event using
Blastware's exact protocol. REWRITTEN 2026-05-02 (v0.14.0).
strict: the stream must arrive whole, or this raises ProtocolError -- a
missing STRT, a metadata page or chunk with no reply, a mid-stream
terminator, the chunk cap, or no TERM reply. The one-event download uses
it: a short event must never be stored (BE9441 rebooted mid-download on
2026-10-25 and its partial event was kept). Without strict the legacy
tolerance stands: an early end proceeds to TERM and returns what arrived.
Algorithm (matches BW captures across 2-sec / 3-sec / event-2):
The walk (measured 2026-10-26: Blastware downloading all 8 of BE9441's
events, four crossing a 64 KB page -- tests/test_5a_blastware_walk.py
rebuilds its requests byte for byte):
1. Probe
- For events at start_key[2:4] = 0x0000 (first event after erase
/ wrap): probe at counter=0x0000 with full key in params.
- For continuation events (start_key[2:4] != 0): first chunk at
counter = start_key[2:4] + 0x0046; acts as both probe and
first sample chunk; response carries STRT.
1. Read 0x200 bytes at the event's own 32-bit address (the key). The
reply carries STRT, whose end key is the full 32-bit address where
the event ends.
2. Read 0x200 bytes at each next address, +0x200 at a time, as plain
32-bit numbers -- crossing into the next 64 KB page needs nothing
special -- while the whole chunk fits before the end.
3. TERM: read the remainder (end - next boundary) at the next boundary.
Its reply carries the event's tail and the file footer.
2. Parse end_offset from STRT record at data[23:27] of the probe response.
The first event on a unit reads 0x0000, 0x0200, 0x0400, 0x0600, ...: the
"metadata pages at 0x1002 / 0x1004" of the earlier model were its chunks
at 0x0200 and 0x0400, escaped (`10 02 00`, `10 04 00`). That model's
16-bit counter could not leave the key's page -- the 64 KB page bug.
3. Read two fixed metadata pages at counter=0x1002 and counter=0x1004
— global session metadata (Project / Client / User Name / Seis Loc
/ Extended Notes ASCII strings). Event 1 only; continuation
events skip these (BW caches them across the session).
4. Walk sample chunks at 0x0200 increments, starting from 0x0600 for
event 1 or `start + 0x0046 + 0x0200` for continuation events.
Stop when `next_chunk + 0x0200 > end_offset`.
5. Send TERM frame with offset_word and params computed by
`bulk_waveform_term_v2(key4, end_offset, last_chunk_counter)`.
The TERM response contains the partial last chunk (residual =
end_offset - next_boundary) including the 26-byte 0e 08 file
footer.
Returns:
The A5 frames in order (first chunk, chunks, and with
`include_terminator=True` the TERM reply, which write_blastware_file
needs for the footer).
List of S3Frame objects from each A5 response (probe, metadata
pages, sample chunks, optional TERM response). Caller passes
`include_terminator=True` (e.g. write_blastware_file) to keep the
TERM response in the list — it's required to reconstruct the
file footer.
Deprecated kwargs (no-ops): stop_after_metadata, extra_chunks_after_metadata.
Deprecated kwargs:
stop_after_metadata: legacy "Project:"-string-based stop condition.
No-op under the BW-exact walk; the loop is
deterministically bounded by end_offset from
STRT. Accepted for backward compat.
extra_chunks_after_metadata: same.
Raises:
ProtocolError: on timeout / bad checksum / unexpected SUB, and in
strict mode on any early end.
ProtocolError: on timeout / bad checksum / unexpected SUB.
"""
if len(key4) != 4:
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
@@ -654,15 +598,38 @@ class MiniMateProtocol:
rsp_sub = _expected_rsp_sub(SUB_BULK_WAVEFORM) # 0xA5
frames_data: list[S3Frame] = []
start = int.from_bytes(key4, "big")
def request(address: int, length: int) -> None:
self._send(build_5a_request(address, length))
self._parser.reset()
start_offset = (key4[2] << 8) | key4[3]
is_event_1 = (start_offset == 0)
# ── Step 1: the event's first chunk; its reply carries STRT ──────────
log.debug("5A first chunk key=%s", key4.hex())
request(start, _BULK_COUNTER_STEP)
# ── Step 1: probe / first chunk ──────────────────────────────────────
if is_event_1:
probe_counter = 0
probe_params = bulk_waveform_params(key4, 0, is_probe=True)
log.debug("5A probe (event-1) key=%s counter=0x0000", key4.hex())
else:
# Continuation events: first 5A request lands at counter = key[2:4]
# (i.e. the address of the off=0x46 WAVEHDR record returned by 1F).
# The probe response carries STRT at byte 17 with end_offset.
#
# Confirmed 2026-05-04 from 5-1-26 "copy 2nd address" capture
# (BW probes counter=0x2238 with key=01112238, STRT@17 end=0x417E)
# and 5-4-26 BW captures (2-sec event probes counter=0x2238).
#
# The earlier "+0x46" formula in the doc came from calling
# start_key the BOUNDARY (off=0x2C) key, but the iteration walk
# uses 1F's off=0x46 key as cur_key, which already incorporates
# the +0x46 offset relative to the boundary. Adding it again
# caused the probe to overshoot, miss STRT, and run uncapped.
probe_counter = start_offset
probe_params = bulk_waveform_params(key4, probe_counter)
log.debug(
"5A probe (event-N) key=%s counter=0x%04X",
key4.hex(), probe_counter,
)
self._send(build_5a_frame(_BULK_CHUNK_OFFSET, probe_params))
self._parser.reset()
try:
rsp = self._recv_one(expected_sub=rsp_sub, reset_parser=False)
except TimeoutError:
@@ -671,79 +638,102 @@ class MiniMateProtocol:
key4.hex(), self._parser.bytes_fed,
)
raise
frames_data.append(rsp)
log.debug("5A A5[0] (probe) page_key=0x%04X %d bytes", rsp.page_key, len(rsp.data))
# ── Step 2: where the event ends -- STRT's full 32-bit end key ───────
end = parse_strt_end_key(rsp.data)
if end is None and strict:
raise ProtocolError(
f"5A probe for {key4.hex()} carried no STRT record, so the event's end "
"is unknown -- not downloaded")
if end is not None and end <= start:
if strict:
raise ProtocolError(
f"5A STRT for {key4.hex()} says the event ends at 0x{end:08X}, at or "
"before its start -- not downloaded")
log.warning("5A STRT end 0x%08X is not after the start 0x%08X -- ignored", end, start)
end = None
if end is not None and end - start < _BULK_COUNTER_STEP:
# The walk's first read is a whole chunk, so a smaller event cannot be
# bounded -- and no event is that small (the header alone is longer).
raise ProtocolError(
f"5A STRT for {key4.hex()} says the event is {end - start} bytes, less than "
"one 0x200 chunk -- a misread STRT; not downloaded")
if end is not None and end - start > _BULK_MAX_EVENT_BYTES:
raise ProtocolError(
f"5A STRT for {key4.hex()} says the event is {end - start:,} bytes, more than "
f"any unit holds ({_BULK_MAX_EVENT_BYTES:,}) -- a misread STRT; not downloaded")
have_end = end is not None
if not have_end:
frames_data.append(rsp)
log.debug("5A A5[0] (probe) page_key=0x%04X %d bytes",
rsp.page_key, len(rsp.data))
# ── Step 2: parse STRT end_offset from probe response ────────────────
end_offset = parse_strt_end_offset(rsp.data)
if end_offset is None:
log.warning(
"5A probe response did not contain a usable STRT record; "
"5A probe response did not contain a STRT record; "
"cannot bound chunk loop — falling back to max_chunks=%d cap",
max_chunks,
)
end = start + (max_chunks + 2) * _BULK_COUNTER_STEP # the cap bounds the loop
end_offset = 0xFFFF # impossible value → loop runs to max_chunks
else:
log.info("5A STRT start=0x%08X end=0x%08X size=0x%X", start, end, end - start)
# With the end known, STRT bounds the walk and the cap must not cut it short:
# a histogram can be several hundred KB (2,545 of 63,500 in the DL2 archive
# exceed the 128-chunk / ~66 KB a caller's cap allowed). The cap still
# bounds a walk whose end is unknown.
chunk_cap = max(max_chunks, (end - start) // _BULK_COUNTER_STEP) if have_end else max_chunks
log.info(
"5A STRT start_offset=0x%04X end_offset=0x%04X size=0x%04X",
start_offset, end_offset, end_offset - start_offset,
)
# ── Step 3: chunks at +0x200, plain 32-bit addresses ─────────────────
address = start + _BULK_COUNTER_STEP
last = start
# ── Step 3: metadata pages 0x1002 + 0x1004 (event 1 only) ────────────
# Confirmed from BW captures: BW reads these two fixed device-buffer
# pages immediately after the probe for events at start_key[2:4]=0.
# Continuation events skip them (BW caches across the session).
# Their content is global compliance-setup metadata: Project, Client,
# User Name, Seis Loc, Extended Notes.
if is_event_1:
for meta_counter in (0x1002, 0x1004):
# Metadata page params have an extra trailing 0x00 byte
# (12-byte params instead of 11) — empirical from BW captures.
# Checksum-neutral but matches BW byte-for-byte.
meta_params = bytes([
0x00,
key4[0], key4[1],
(meta_counter >> 8) & 0xFF,
meta_counter & 0xFF,
0, 0, 0, 0, 0, 0, 0,
])
log.debug("5A metadata page counter=0x%04X", meta_counter)
self._send(build_5a_frame(_BULK_CHUNK_OFFSET, meta_params))
self._parser.reset()
try:
meta_rsp = self._recv_one(
expected_sub=rsp_sub, reset_parser=False, timeout=10.0,
)
except TimeoutError:
log.warning(
"5A metadata page 0x%04X TIMED OUT — continuing",
meta_counter,
)
continue
frames_data.append(meta_rsp)
log.debug(
"5A meta@0x%04X page_key=0x%04X %d bytes",
meta_counter, meta_rsp.page_key, len(meta_rsp.data),
)
# ── Step 4: sample chunk loop, bounded by end_offset ─────────────────
# Sample chunks start at:
# event 1: counter = 0x0600
# event N (>0): counter = probe_counter + 0x0200
# (probe was the first sample chunk)
if is_event_1:
counter = 0x0600
else:
counter = probe_counter + _BULK_COUNTER_STEP
last_chunk_counter: Optional[int] = (
probe_counter if not is_event_1 else None
)
chunks_fetched = 0
while chunks_fetched < chunk_cap:
# Stop when the next chunk would straddle the event end.
if address + _BULK_COUNTER_STEP > end:
while chunks_fetched < max_chunks:
# Stop when next chunk would straddle the event end.
if counter + _BULK_COUNTER_STEP > end_offset:
log.debug(
"5A chunk loop done at 0x%08X (end=0x%08X); %d chunks fetched",
address, end, chunks_fetched,
"5A chunk loop done at counter=0x%04X (end=0x%04X); "
"%d chunks fetched",
counter, end_offset, chunks_fetched,
)
break
log.debug("5A chunk #%d address=0x%08X", chunks_fetched + 1, address)
request(address, _BULK_COUNTER_STEP)
params = bulk_waveform_params(key4, counter)
log.debug("5A chunk #%d counter=0x%04X", chunks_fetched + 1, counter)
self._send(build_5a_frame(_BULK_CHUNK_OFFSET, params))
self._parser.reset()
try:
rsp = self._recv_one(
expected_sub=rsp_sub, reset_parser=False, timeout=10.0,
)
except TimeoutError as exc:
except TimeoutError:
raw = self._parser.bytes_fed
log.warning(
"5A TIMEOUT chunk=%d address=0x%08X raw_bytes=%d",
chunks_fetched + 1, address, raw,
"5A TIMEOUT chunk=%d counter=0x%04X raw_bytes=%d",
chunks_fetched + 1, counter, raw,
)
if strict:
raise TimeoutError(
f"5A stream ended early: no reply for the chunk at 0x{address:08X}; the "
f"event ends at 0x{end:08X} ({chunks_fetched} chunk(s) received) "
"-- the event was not kept") from exc
if raw > 0 and frames_data:
log.warning(
"5A unexpected end-of-stream — proceeding to TERM",
@@ -758,53 +748,46 @@ class MiniMateProtocol:
if rsp.page_key == 0x0000:
# Device terminated mid-stream unexpectedly.
if strict:
raise ProtocolError(
f"5A stream ended early: the unit sent its terminator at 0x{address:08X}, "
f"before the event's end 0x{end:08X} -- the event was not kept")
log.warning(
"5A unexpected page_key=0x0000 mid-stream at address=0x%08X",
address,
"5A unexpected page_key=0x0000 mid-stream at counter=0x%04X",
counter,
)
if include_terminator:
frames_data.append(rsp)
return frames_data
frames_data.append(rsp)
last = address
address += _BULK_COUNTER_STEP
last_chunk_counter = counter
counter += _BULK_COUNTER_STEP
chunks_fetched += 1
else:
if strict:
raise ProtocolError(
f"5A reached the {chunk_cap}-chunk cap at 0x{address:08X} before the "
f"event's end 0x{end:08X} -- the event was not kept")
log.warning(
"5A reached max_chunks=%d at address=0x%08X (end=0x%08X)",
chunk_cap, address, end,
"5A reached max_chunks=%d at counter=0x%04X (end=0x%04X)",
max_chunks, counter, end_offset,
)
# ── Step 4: TERM -- the remainder, from the next boundary ───────────
boundary = last + _BULK_COUNTER_STEP
if have_end:
term_length = end - boundary
if not 0 <= term_length < _BULK_COUNTER_STEP:
# Only after an early end (the legacy tolerance): what is left is not a
# tail but most of the event, and a TERM for it is no TERM at all.
if strict:
raise ProtocolError(
f"5A TERM for {key4.hex()} would read 0x{term_length:X} bytes from "
f"0x{boundary:08X}, not a tail -- the event was not kept")
log.warning("5A stream ended 0x%X bytes before the event's end; no TERM sent",
term_length)
return frames_data
log.debug("5A TERM address=0x%08X length=0x%04X end=0x%08X",
boundary, term_length, end)
# ── Step 5: TERM with proper end_offset-derived formula ──────────────
if last_chunk_counter is None or end_offset == 0xFFFF:
# No STRT or no chunks fetched — fall back to legacy TERM.
log.warning(
"5A using legacy TERM (offset_word=0x005A); "
"end_offset unavailable or no chunks fetched",
)
legacy_counter = (last_chunk_counter or probe_counter) + _BULK_COUNTER_STEP
term_offset_word = _BULK_TERM_OFFSET # 0x005A
term_params = bulk_waveform_term_params(key4, legacy_counter)
else:
term_length = _BULK_TERM_OFFSET # legacy: no STRT, so no remainder known
log.warning("5A using legacy TERM (length 0x%04X); end unknown", term_length)
term_offset_word, term_params = bulk_waveform_term_v2(
key4, end_offset, last_chunk_counter,
)
log.debug(
"5A TERM offset_word=0x%04X params[2:4]=%s end=0x%04X "
"last_chunk=0x%04X",
term_offset_word, term_params[2:4].hex(),
end_offset, last_chunk_counter,
)
self._send(build_5a_request(boundary, term_length))
self._send(build_5a_frame(term_offset_word, term_params))
try:
term_rsp = self._recv_one(expected_sub=rsp_sub, timeout=10.0)
log.info(
@@ -813,11 +796,7 @@ class MiniMateProtocol:
)
if include_terminator:
frames_data.append(term_rsp)
except TimeoutError as exc:
if strict:
raise TimeoutError(
"5A stream ended early: no reply to the TERM request, which carries the "
"event's tail and footer -- the event was not kept") from exc
except TimeoutError:
log.warning("5A no TERM response (timeout)")
return frames_data
@@ -1050,66 +1029,208 @@ 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:
"""Send one config block as a write and return its ack (0xFF - sub)."""
image = write_image(sub, data)
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:
"""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)
"""
Send a SUB 68 (EVENT_INDEX_WRITE) frame and await the confirm ack (SUB 97).
Offset formula: data[1] + 2 — confirmed from 3-11-26 BW TX capture frame 102.
The write payload has a 2-byte header [0x00][length] where data[1] encodes
the length of the meaningful payload; offset = data[1] + 2.
Example from capture:
data[0:4] = 00 58 09 00 (data[1]=0x58=88 → offset=0x5A=90)
data length = 91, offset = 90
Write sequence fragment:
68 (data) → device acks with SUB 0x97
73 (confirm) → device acks with SUB 0x8C
Callers should call write_confirm(SUB_WRITE_CONFIRM_B) after this.
Args:
data: Raw event-index payload bytes to write to the device.
Must be at least 2 bytes. data[1] must contain the length field.
Returns:
The SUB 0x97 ack frame.
Raises:
ProtocolError: on timeout or wrong response SUB.
ValueError: if data is shorter than 2 bytes.
"""
if len(data) < 2:
raise ValueError(f"event index write data must be at least 2 bytes, got {len(data)}")
rsp_sub = _expected_rsp_sub(SUB_EVENT_INDEX_WRITE) # 0xFF - 0x68 = 0x97
offset = data[1] + 2
frame = build_bw_write_frame(SUB_EVENT_INDEX_WRITE, data, offset=offset)
log.debug(
"write_event_index: %d bytes data[1]=0x%02X offset=0x%04X rsp_sub=0x%02X",
len(data), data[1], offset, rsp_sub,
)
self._send(frame)
return self.recv_write_ack(expected_sub=rsp_sub)
def write_waveform_data(self, data: bytes) -> 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)
"""
Send a SUB 69 (WAVEFORM_DATA_WRITE) frame and await the confirm ack (SUB 96).
Offset formula: data[1] + 2 — same pattern as write_event_index().
Confirmed from 3-11-26 BW TX capture frame 110:
data[0:4] = 00 c8 08 00 (data[1]=0xC8=200 → offset=0xCA=202)
data length = 204, offset = 202
Write sequence fragment:
69 (data) → device acks with SUB 0x96
74 (confirm) → device acks with SUB 0x8B
72 (confirm) → device acks with SUB 0x8D
Callers should call write_confirm(SUB_WRITE_CONFIRM_C) then
write_confirm(SUB_WRITE_CONFIRM_A) after this.
Args:
data: Raw waveform-data payload bytes to write.
Must be at least 2 bytes. data[1] must contain the length field.
Returns:
The SUB 0x96 ack frame.
Raises:
ProtocolError: on timeout or wrong response SUB.
ValueError: if data is shorter than 2 bytes.
"""
if len(data) < 2:
raise ValueError(f"waveform data write payload must be at least 2 bytes, got {len(data)}")
rsp_sub = _expected_rsp_sub(SUB_WAVEFORM_DATA_WRITE) # 0xFF - 0x69 = 0x96
offset = data[1] + 2
frame = build_bw_write_frame(SUB_WAVEFORM_DATA_WRITE, data, offset=offset)
log.debug(
"write_waveform_data: %d bytes data[1]=0x%02X offset=0x%04X rsp_sub=0x%02X",
len(data), data[1], offset, rsp_sub,
)
self._send(frame)
return self.recv_write_ack(expected_sub=rsp_sub)
def write_compliance_config_raw(self, data: bytes) -> 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
512-byte chunks with the chunk's address at params[2:4] -- 0x0000, 0x0200,
0x0400, 0x0600, then the 44-byte rest at 0x0800 -- each acked 0x8E, then
SUB 72 (ack 0x8D). Blastware 10.74 on BE9441 (2026-10-26), byte for byte.
March 2026's Blastware sent 1,024-byte chunks the same way; the units took
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)
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)
frame = build_bw_write_frame(SUB_COMPLIANCE_WRITE,
image[addr:addr + _COMPLIANCE_CHUNK], params=params)
log.debug("write_compliance_config_raw: chunk at 0x%04X", addr)
Send the SUB 71 (COMPLIANCE_WRITE) 3-chunk sequence and final confirm.
The full compliance config payload (~2128 bytes) is split into exactly 3
chunks with hardcoded boundaries and params confirmed from the 3-11-26 BW
TX capture (frames 104–108):
Chunk 1 — first 1027 bytes:
offset=0x1004 params=bytes(10)
device acks SUB 0x8E
Chunk 2 — next 1055 bytes:
offset=0x1004 params=b'\\x00\\x00\\x00\\x00\\x10\\x04' + b'\\x00'*4
device acks SUB 0x8E
Chunk 3 — remaining bytes:
offset=0x002C params=b'\\x00\\x00\\x08' + b'\\x00'*7
device acks SUB 0x8E
Confirm — SUB 72 (zero data):
device acks SUB 0x8D
The total write payload should be at least 1027+1055=2082 bytes; chunk 3
carries everything after offset 2082 (typically ~46 bytes for a 2128-byte
config).
Args:
data: Raw compliance config bytes to write. Must be at least 2082 bytes.
Raises:
ValueError: if data is too short to fill chunks 1 and 2.
ProtocolError: on timeout or wrong response SUB from any chunk.
"""
_CHUNK1_SIZE = 1027
_CHUNK2_SIZE = 1055
_CHUNK1_OFFSET = 0x1004
_CHUNK2_OFFSET = 0x1004
_CHUNK3_OFFSET = 0x002C
_CHUNK1_PARAMS = bytes(10)
_CHUNK2_PARAMS = bytes([0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00])
_CHUNK3_PARAMS = bytes([0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
min_size = _CHUNK1_SIZE + _CHUNK2_SIZE
if len(data) < min_size:
raise ValueError(
f"Compliance write data too short: {len(data)} bytes, "
f"need at least {min_size} (chunk1={_CHUNK1_SIZE} + chunk2={_CHUNK2_SIZE})"
)
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE_WRITE) # 0xFF - 0x71 = 0x8E
chunk1 = data[:_CHUNK1_SIZE]
chunk2 = data[_CHUNK1_SIZE : _CHUNK1_SIZE + _CHUNK2_SIZE]
chunk3 = data[_CHUNK1_SIZE + _CHUNK2_SIZE :]
chunks = [
(1, chunk1, _CHUNK1_OFFSET, _CHUNK1_PARAMS),
(2, chunk2, _CHUNK2_OFFSET, _CHUNK2_PARAMS),
(3, chunk3, _CHUNK3_OFFSET, _CHUNK3_PARAMS),
]
for chunk_num, chunk_data, chunk_offset, chunk_params in chunks:
frame = build_bw_write_frame(
SUB_COMPLIANCE_WRITE,
chunk_data,
offset=chunk_offset,
params=chunk_params,
)
log.debug(
"write_compliance_config_raw: chunk %d %d bytes "
"offset=0x%04X params=%s",
chunk_num, len(chunk_data), chunk_offset, chunk_params.hex(),
)
self._send(frame)
self.recv_write_ack(expected_sub=rsp_sub)
log.debug("write_compliance_config_raw: chunk %d acked", chunk_num)
# Final confirm (SUB 72)
log.debug("write_compliance_config_raw: sending confirm (SUB 0x72)")
self.write_confirm(SUB_WRITE_CONFIRM_A)
log.debug("write_compliance_config_raw: done")
def write_trigger_config(self, data: bytes) -> 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)
def read_trigger_config(self) -> bytes:
"""SUB 0x2E two-step read: the 26-byte trigger block that SUB 82 writes.
Blastware reads it before writing it (BE9441, 2026-10-26). Its byte 5
differs by unit and session (01 / 03 / 04 on record) -- so a block copied
from another unit, as apply_config once wrote, changes a setting.
Returns the block unescaped (data[11:] after unescape_reply).
"""
rsp_sub = _expected_rsp_sub(SUB_UNKNOWN_2E)
length = DATA_LENGTHS[SUB_UNKNOWN_2E]
self._send(build_bw_frame(SUB_UNKNOWN_2E, 0))
self._recv_one(expected_sub=rsp_sub)
self._send(build_bw_frame(SUB_UNKNOWN_2E, length))
data_rsp = self._recv_one(expected_sub=rsp_sub)
return unescape_reply(data_rsp.data)[11:11 + length]
Send a SUB 82 (TRIGGER_CONFIG_WRITE) frame and await the confirm ack (SUB 7D).
Offset formula: data[1] + 2 — same pattern as write_event_index().
Confirmed from 3-11-26 BW TX capture frame 108:
data[0:4] = 00 1a d5 00 (data[1]=0x1A=26 → offset=0x1C=28)
data length = 29, offset = 28
Write sequence fragment:
82 (data) → device acks with SUB 0x7D
83 (confirm) → device acks with SUB 0x7C
Callers should call write_confirm(SUB_TRIGGER_CONFIRM) after this.
Args:
data: Raw trigger-config payload bytes to write.
Must be at least 2 bytes. data[1] must contain the length field.
Returns:
The SUB 0x7D ack frame.
Raises:
ProtocolError: on timeout or wrong response SUB.
ValueError: if data is shorter than 2 bytes.
"""
if len(data) < 2:
raise ValueError(f"trigger config write payload must be at least 2 bytes, got {len(data)}")
rsp_sub = _expected_rsp_sub(SUB_TRIGGER_CONFIG_WRITE) # 0xFF - 0x82 = 0x7D
offset = data[1] + 2
frame = build_bw_write_frame(SUB_TRIGGER_CONFIG_WRITE, data, offset=offset)
log.debug(
"write_trigger_config: %d bytes data[1]=0x%02X offset=0x%04X rsp_sub=0x%02X",
len(data), data[1], offset, rsp_sub,
)
self._send(frame)
return self.recv_write_ack(expected_sub=rsp_sub)
# ── Call home config (SUBs 0x2C / 0x7E / 0x7F) ──────────────────────────
@@ -1173,13 +1294,20 @@ class MiniMateProtocol:
ValueError: if data is not exactly 127 bytes or lacks expected header.
ProtocolError: on timeout or wrong response SUB.
"""
if len(data) < 2:
raise ValueError(f"call home write payload must be at least 2 bytes, got {len(data)}")
rsp_sub_write = _expected_rsp_sub(SUB_CALL_HOME_WRITE) # 0xFF - 0x7E = 0x81
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)
# Offset formula: data[1] + 2 (same pattern as other single-chunk writes)
offset = data[1] + 2 # 0x7C + 2 = 0x7E = 126
frame = build_bw_write_frame(SUB_CALL_HOME_WRITE, data, offset=offset)
log.debug(
"write_call_home_config: %d bytes data[1]=0x%02X offset=0x%04X",
len(data), data[1], offset,
)
self._send(frame)
self.recv_write_ack(expected_sub=rsp_sub_write)
log.debug("write_call_home_config: write acked; sending confirm 0x7F")
confirm_frame = build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")
@@ -1395,10 +1523,10 @@ class MiniMateProtocol:
def _validate_frame(frame: S3Frame, expected_sub: Optional[int]) -> None:
"""Validate SUB; log but do not raise on bad checksum.
A reply's checksum is SUM8 of its unescaped payload (748/748, measured
2026-10-26). `checksum_valid` is usually False only because S3FrameParser
sums its output with the `10` of each kept `10 02/03/04` pair still in it
-- the parser's doing, not the unit's. We log and continue.
S3 response checksums frequently fail SUM8 validation due to inner-frame
delimiter bytes being captured as the checksum byte. The original
s3_parser.py deliberately never validates S3 checksums for exactly this
reason. We log a warning and continue.
"""
if not frame.checksum_valid:
# S3 checksums frequently fail SUM8 due to inner-frame delimiter bytes
@@ -1409,59 +1537,7 @@ class MiniMateProtocol:
f"Expected SUB=0x{expected_sub:02X}, got 0x{frame.sub:02X}"
)
# A MiniMate whose port has just opened may boot: it sends this banner a few
# seconds later and ignores a POLL sent before it. Measured on BE9441 over a
# serial cable (2026-10-25): banner ~3 s after the port opened, twice; after a
# mid-download reboot it answered 8.8 s after the banner.
_BOOT_BANNER = b"Operating System"
_BOOT_GRACE_S = 20.0
_BOOT_POLL_S = 2.0
def _await_poll_or_boot(self, timeout: float) -> Optional[S3Frame]:
"""The first POLL probe's reply -- or None the moment the unit sends its
boot banner, because a POLL sent before the banner is never answered."""
expected = _expected_rsp_sub(SUB_POLL)
self._parser.reset() # as _recv_one(reset_parser=True) did here
self._pending_frames.clear()
deadline = time.monotonic() + timeout
tail = b""
while time.monotonic() < deadline:
chunk = self._transport.read(256)
if not chunk:
time.sleep(0.005)
continue
log.debug("RX %d bytes: %s", len(chunk), chunk.hex())
frames = self._parser.feed(chunk)
if frames:
self._pending_frames.extend(frames[1:])
self._validate_frame(frames[0], expected)
return frames[0]
tail += chunk
if self._BOOT_BANNER in tail:
return None
tail = tail[-64:] # trimmed after the check, so a long read keeps it
raise TimeoutError(
f"No S3 frame received within {timeout:.1f}s (expected SUB 0x{expected:02X})")
def _poll_until_booted(self) -> S3Frame:
"""The unit said it is booting: POLL again until it answers. A read --
nothing is ever sent but SESSION_RESET and POLL."""
log.info("startup: the unit is booting (it sent %r) -- polling again until it answers",
self._BOOT_BANNER.decode())
deadline = time.monotonic() + self._BOOT_GRACE_S
while time.monotonic() < deadline:
self._send(SESSION_RESET)
self._send(POLL_PROBE)
try:
return self._recv_one(expected_sub=_expected_rsp_sub(SUB_POLL),
timeout=self._BOOT_POLL_S)
except TimeoutError:
continue
raise TimeoutError(
f"the unit sent its boot message but did not answer a POLL within "
f"{self._BOOT_GRACE_S:.0f} s")
def _drain_boot_string(self, drain_ms: int = 200) -> bool:
def _drain_boot_string(self, drain_ms: int = 200) -> None:
"""
Read and discard any boot-string bytes ("Operating System") the device
may send before entering binary protocol mode.
@@ -1469,21 +1545,14 @@ class MiniMateProtocol:
We simply read with a short timeout and throw the bytes away. The
S3FrameParser's IDLE state already handles non-frame bytes gracefully,
but it's cleaner to drain them explicitly before the first real frame.
Returns whether the boot banner was among them (the unit is booting).
"""
deadline = time.monotonic() + (drain_ms / 1000)
discarded = 0
tail, saw_banner = b"", False
while time.monotonic() < deadline:
chunk = self._transport.read(256)
if chunk:
discarded += len(chunk)
tail += chunk
saw_banner = saw_banner or self._BOOT_BANNER in tail
tail = tail[-len(self._BOOT_BANNER):] # a banner split across reads still matches
else:
time.sleep(0.005)
if discarded:
log.debug("drain_boot_string: discarded %d bytes", discarded)
return saw_banner
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "seismo-relay"
version = "0.31.0"
version = "0.32.0"
description = "Python client and REST server for MiniMate Plus seismographs"
requires-python = ">=3.10"
dependencies = [
-98
View File
@@ -1,98 +0,0 @@
#!/usr/bin/env python3
"""Cut Micromate write-session fixtures out of THOR's captures.
bridges/captures/ is gitignored, so the reproduction tests read these instead.
Each fixture is every request (as wire bytes) and every response (as its data
section) of one captured THOR session, paired in order, with the sha256 of the
capture files it came from. Re-run to regenerate:
.venv/bin/python scratch/mm_write_fixtures.py
"""
from __future__ import annotations
import hashlib
import json
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO))
from micromate.framing import ACK, DLE, ETX, STX, MicromateFrameParser, request_sub # noqa: E402
CAP = REPO / "bridges" / "captures" / "9-24-26 - micromate2"
OUT = REPO / "tests" / "fixtures" / "micromate-writes"
SESSIONS = {
"setup-push-new-test1": "20260924_181942_send_TEST1_to_unit",
"setup-push-overwrite-test1": "overwritetest/*20260924_185113_test1_overwrite_check",
"setup-push-read-scheduler": "20260924_191835_read_scheduler",
"setup-push-pull-schedule": "20260925_003029_pull_schedule,_turn_off_repeat_daily,_push_schedule",
"setup-push-multiday": "20260925_011907_send_multiday_schedule",
"call-home-enable-disable": "20260925_011620_ACH-change_1_setting",
"monitor-start-stop": "20260924_191214_turn_on_monitormode_then_attempt_to_write_config",
}
def _find(stem: str, kind: str) -> Path:
if "/" in stem:
sub, rest = stem.split("/", 1)
hits = sorted((CAP / sub).glob(f"raw_{kind}_{rest.lstrip('*')}.bin"))
else:
hits = sorted(CAP.glob(f"raw_{kind}_{stem}.bin"))
if len(hits) != 1:
raise SystemExit(f"expected one raw_{kind} file for {stem!r}, found {hits}")
return hits[0]
def requests(blob: bytes) -> list[bytes]:
out, i = [], 0
while i < len(blob):
if not (blob[i] == ACK and i + 1 < len(blob) and blob[i + 1] == STX):
i += 1
continue
j = i + 2
while j < len(blob):
if blob[j] == DLE and j + 1 < len(blob):
j += 2
continue
if blob[j] == ETX:
break
j += 1
out.append(blob[i:j + 1])
i = j + 1
return out
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
for slug, stem in SESSIONS.items():
bw, s3 = _find(stem, "bw"), _find(stem, "s3")
reqs = requests(bw.read_bytes())
parser = MicromateFrameParser()
rsps = parser.feed(s3.read_bytes())
if len(reqs) != len(rsps):
raise SystemExit(f"{slug}: {len(reqs)} requests vs {len(rsps)} responses")
exchanges = []
lines = {rp.firmware_line for rp in rsps}
if len(lines) != 1 or lines & {"unknown"}:
raise SystemExit(f"{slug}: responses report firmware lines {sorted(lines)}")
for rq, rp in zip(reqs, rsps):
sub = request_sub(rq)
if rp.sub != 0xFF - sub or not rp.checksum_valid:
raise SystemExit(f"{slug}: response 0x{rp.sub:02X} does not answer 0x{sub:02X}")
exchanges.append({"sub": sub, "request": rq.hex(), "response_sub": rp.sub,
"response_data": rp.data.hex()})
doc = {
"source": str(bw.relative_to(REPO)),
"source_sha256": {"bw": hashlib.sha256(bw.read_bytes()).hexdigest(),
"s3": hashlib.sha256(s3.read_bytes()).hexdigest()},
"unit": "UM12947", "firmware_version": "11.0CB",
"firmware_line": lines.pop(),
"exchanges": exchanges,
}
(OUT / f"{slug}.json").write_text(json.dumps(doc, indent=1) + "\n")
print(f"{slug}: {len(exchanges)} exchanges")
if __name__ == "__main__":
main()
-90
View File
@@ -1,90 +0,0 @@
"""Ring-path bench test, Runs A/B: ask SFM for a Micromate's status on a fixed
interval and log every answer with its time. Read-only on the unit.
python scratch/ring_path_poller.py --sfm http://127.0.0.1:8299 \
--serial UM20147 --host <modem ip> --tcp-port 9034 --interval 10 \
--log <run dir>/poller.jsonl
Run A: --count 1 (one call-up; SFM then holds the line until its 5-minute idle
hang-up or a RADIO RING). Run B: the default, every --interval seconds until
Ctrl-C. Each poll asks for the raw SUB 0x49 code (run_state=true), so a
call-home in progress shows as its own code rather than as "not monitoring".
What the log is for (spec, "Open questions this design leaves for the bench"):
a 503 "call home in progress" is SFM seeing the ring and hanging up; a 503/504
on connect while THOR's watchdog holds the line is contention; THOR's own ACH
log says when the call reached THOR.
"""
from __future__ import annotations
import argparse
import datetime
import json
import time
import urllib.error
import urllib.parse
import urllib.request
def poll_once(sfm: str, serial: str, host: str, tcp_port: int, timeout: float) -> dict:
q = urllib.parse.urlencode({"serial": serial, "host": host, "tcp_port": tcp_port, "run_state": "true"})
t0 = time.monotonic()
started = datetime.datetime.now().isoformat(timespec="milliseconds")
try:
with urllib.request.urlopen(f"{sfm}/device/monitor/status?{q}", timeout=timeout) as r:
code, body = r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
code = e.code
try:
body = json.loads(e.read() or b"{}")
except ValueError:
body = {}
except (urllib.error.URLError, TimeoutError, OSError) as e:
code, body = None, {"error": f"{type(e).__name__}: {e}"}
secs = round(time.monotonic() - t0, 2)
d = body.get("detail") if isinstance(body, dict) else None
rs = d.get("run_state") if isinstance(d, dict) else None # an error's detail is a string
return {"at": started, "secs": secs, "http": code,
"monitoring": body.get("monitoring") if isinstance(body, dict) else None,
"run_state": rs, "device_time": body.get("device_time") if isinstance(body, dict) else None,
"detail": None if code == 200 else (body.get("detail") or body.get("error"))}
def line(rec: dict) -> str:
rs = rec["run_state"]
state = f"0x{rs['code']:02X} {rs['name']}" if rs else "-"
tail = f" {rec['detail']}" if rec["detail"] else ""
return f"{rec['at']} http={rec['http']} {rec['secs']:>6} s 0x49={state} monitoring={rec['monitoring']}{tail}"
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--sfm", default="http://127.0.0.1:8299")
ap.add_argument("--serial", required=True)
ap.add_argument("--host", required=True)
ap.add_argument("--tcp-port", type=int, default=9034)
ap.add_argument("--interval", type=float, default=10.0, help="seconds between polls (start to start)")
ap.add_argument("--count", type=int, default=0, help="stop after N polls (0 = until Ctrl-C)")
ap.add_argument("--timeout", type=float, default=180.0)
ap.add_argument("--log", required=True, help="JSON lines, appended")
a = ap.parse_args()
if a.sfm.rstrip("/").endswith(":8200"):
raise SystemExit("refusing :8200 -- use the bench SFM")
n = 0
with open(a.log, "a") as f:
while True:
t0 = time.monotonic()
rec = poll_once(a.sfm.rstrip("/"), a.serial, a.host, a.tcp_port, a.timeout)
f.write(json.dumps(rec) + "\n"); f.flush()
print(line(rec), flush=True)
n += 1
if a.count and n >= a.count:
return
time.sleep(max(0.0, a.interval - (time.monotonic() - t0)))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
+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)",
-16
View File
@@ -1,16 +0,0 @@
"""The SDM side of the device audit: DeviceAccess calls this sink, which writes
SeismoDb.device_commands. Kept here so sfm.device_access never imports the DB."""
from __future__ import annotations
from typing import Any, Callable
class DbAudit:
def __init__(self, get_db: Callable[[], Any]) -> None:
self._get_db = get_db
def begin(self, **fields: Any) -> str:
return self._get_db().begin_device_command(**fields)
def finish(self, command_id: str, **fields: Any) -> None:
self._get_db().finish_device_command(command_id, **fields)
+96 -122
View File
@@ -34,13 +34,13 @@ Usage
from __future__ import annotations
import datetime
import json
import logging
import sqlite3
import uuid
from pathlib import Path
from typing import Optional
from minimateplus.blastware_file import blastware_filename_time
from minimateplus.models import Event, MonitorLogEntry
log = logging.getLogger("sfm.database")
@@ -127,27 +127,6 @@ CREATE TABLE IF NOT EXISTS monitor_log (
CREATE INDEX IF NOT EXISTS idx_monitor_log_serial ON monitor_log(serial);
CREATE INDEX IF NOT EXISTS idx_monitor_log_start ON monitor_log(start_time);
CREATE INDEX IF NOT EXISTS idx_monitor_log_session ON monitor_log(session_id);
CREATE TABLE IF NOT EXISTS device_commands (
id TEXT PRIMARY KEY,
ts TEXT NOT NULL, -- when the attempt began (UTC ISO)
-- ts/finished_ts: tz-aware UTC ISO (+00:00), unlike the naive UTC of older tables
finished_ts TEXT,
serial TEXT NOT NULL,
series INTEGER NOT NULL,
address TEXT NOT NULL,
action TEXT NOT NULL, -- e.g. "start monitoring"
tier TEXT NOT NULL, -- "change" | "destructive"
request TEXT, -- JSON: parameters + the planned frames (hex)
ack TEXT, -- JSON: ack summary
verified TEXT, -- "ok" | "mismatch" | "not_checked"
outcome TEXT NOT NULL, -- "pending" | "sent" | "skipped" | "failed"
error TEXT,
caller TEXT, -- "webapp" | "terra-view" | "script" | ...
sent INTEGER, -- did a frame go out: 1 acknowledged, 0 nothing sent, NULL unknown
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
"""
@@ -304,17 +283,6 @@ class SeismoDb:
log.info("_migrate: device_family backfill complete (remaining NULL=%d)",
remaining)
# Migration 1d: device_commands gained `sent` and `states` after the
# table first shipped on feat/series4-sfm-parity. NULLable, so rows
# written before read NULL (= unknown).
existing_cols = {
r[1] for r in conn.execute("PRAGMA table_info(device_commands)").fetchall()
}
for col, ddl in (("sent", "INTEGER"), ("states", "TEXT")):
if col not in existing_cols:
log.info("_migrate: device_commands ADD COLUMN %s %s", col, ddl)
conn.execute(f"ALTER TABLE device_commands ADD COLUMN {col} {ddl}")
# Migration 2: change monitor_log UNIQUE from (serial, waveform_key) to
# (serial, start_time) — same reasoning as events.
row = conn.execute(
@@ -405,95 +373,6 @@ class SeismoDb:
).fetchall()
return [dict(r) for r in rows]
# ── Device command audit ──────────────────────────────────────────────────
def begin_device_command(
self,
*,
serial: str,
series: int,
address: str,
action: str,
tier: str,
request: dict,
caller: str,
) -> str:
"""Write a ``pending`` audit row BEFORE anything is sent. Returns its id."""
cid = self._new_id()
ts = datetime.datetime.now(datetime.timezone.utc).isoformat()
with self._connect() as conn:
conn.execute(
"""
INSERT INTO device_commands
(id, ts, serial, series, address, action, tier,
request, outcome, caller)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
""",
(cid, ts, serial, series, address, action, tier,
json.dumps(request), caller),
)
return cid
def finish_device_command(
self,
command_id: str,
*,
outcome: str,
verified: Optional[str],
ack: Optional[dict],
error: Optional[str],
sent: Optional[int] = None,
states: Optional[dict] = None,
) -> None:
"""Record the result of a command begun with begin_device_command().
`sent`: 1 a frame went out and was acknowledged, 0 nothing was sent,
None unknown (the ack was lost). `states`: what was read from the unit,
``{"before": ..., "seen": [...], "after": ...}``.
"""
ts = datetime.datetime.now(datetime.timezone.utc).isoformat()
with self._connect() as conn:
cur = conn.execute(
"UPDATE device_commands SET finished_ts=?, outcome=?, verified=?, "
"ack=?, error=?, sent=?, states=? WHERE id=? AND outcome='pending'",
(ts, outcome, verified,
json.dumps(ack) if ack is not None else None,
error, sent,
json.dumps(states) if states is not None else None,
command_id),
)
if cur.rowcount == 0:
known = conn.execute(
"SELECT 1 FROM device_commands WHERE id=?",
(command_id,)).fetchone()
raise ValueError(
f"device command {command_id} "
+ ("is already finished" if known else "is unknown"))
def query_device_commands(
self,
serial: Optional[str] = None,
limit: int = 100,
) -> list[dict]:
"""Return audit rows, newest first, with request/ack/states parsed from JSON."""
with self._connect() as conn:
if serial:
rows = conn.execute(
"SELECT * FROM device_commands WHERE serial=? "
"ORDER BY ts DESC LIMIT ?", (serial, limit)).fetchall()
else:
rows = conn.execute(
"SELECT * FROM device_commands ORDER BY ts DESC LIMIT ?",
(limit,)).fetchall()
out = []
for r in rows:
d = dict(r)
for k in ("request", "ack", "states"):
if d[k] is not None:
d[k] = json.loads(d[k])
out.append(d)
return out
# ── Events ────────────────────────────────────────────────────────────────
def insert_events(
@@ -519,6 +398,12 @@ class SeismoDb:
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,6 +432,21 @@ 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)
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) is False:
skipped += 1
continue
try:
conn.execute(
"""
@@ -704,6 +604,80 @@ class SeismoDb:
serial, inserted, skipped)
return inserted, skipped
@staticmethod
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
ts: Optional[str]) -> 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) 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 = ?",
(serial, ts)).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) -> Optional[bool]:
"""Move this file's row to `ts` when it sits under another time.
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.
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 != ?) "
"ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
(serial, filename, ts),
).fetchone()
if mine is None:
return None
holder = conn.execute(
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
(serial, ts),
).fetchone()
if holder is None:
conn.execute("UPDATE events SET timestamp = ? WHERE id = ?", (ts, 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:
-13
View File
@@ -1,13 +0,0 @@
"""One door for every device request -- see the 2026-10-20 parity spec."""
from .errors import (
AuditIncomplete, AuditUnavailable, BadRequest, CallHomeInProgress, ChangeUnconfirmed,
ConnectFailed, DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent,
UnitBusy, UnitStateUnknown, WrongUnit, translate,
)
from .models import (
ChangeResult, DownloadedEvent, EventDownload, EventList, EventRef, UnitAddress, UnitInfo,
UnitSettings, UnitStatus,
)
from .series import normalise_serial, series_for_serial
from .locks import UnitLocks
from .access import DeviceAccess
-233
View File
@@ -1,233 +0,0 @@
"""DeviceAccess -- the one door every device request passes through.
The control surface does not care which series it is talking to; this does.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Any, Callable, Dict, Optional
from .errors import 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 .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,
)
from .series import normalise_serial, series_for_serial
log = logging.getLogger("sfm.device_access")
class DeviceAccess:
def __init__(
self, *,
s3_client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory,
s4_client_factory: Callable[[UnitAddress], Any] = default_s4_client_factory,
clock: Callable[[], float] = time.monotonic,
lock_timeout: float = 20.0,
keepalive_s: float = 60.0,
idle_hangup_s: float = 300.0,
reaper_interval_s: float = 5.0,
start_reaper: bool = True,
audit: Any = None,
sleep: Callable[[float], None] = time.sleep,
verify_timeout_s: float = 60.0,
verify_interval_s: float = 2.0,
) -> None:
if verify_interval_s <= 0 or verify_timeout_s < verify_interval_s:
raise ValueError("verify_interval_s must be > 0 and verify_timeout_s >= verify_interval_s")
self._audit = audit
self._sleep = sleep
self._verify_timeout_s = verify_timeout_s
self._verify_interval_s = verify_interval_s
self._locks = UnitLocks(lock_timeout)
self._s3 = Series3Adapter(s3_client_factory)
self._s4_factory = s4_client_factory
self._clock = clock
self._keepalive_s = keepalive_s
self._idle_hangup_s = idle_hangup_s
self._reaper_interval_s = reaper_interval_s
self._start_reaper = start_reaper
self._reaper: Optional[threading.Thread] = None
self._sessions: Dict[str, Series4Session] = {}
self._sessions_guard = threading.Lock()
# ── public operations ─────────────────────────────────────────────────────
def identify(self, address: UnitAddress, serial: str) -> UnitInfo:
return self._dispatch(address, serial, self._s3.identify, s4_identify)
def status(self, address: UnitAddress, serial: str, *, run_state: bool = False) -> UnitStatus:
"""`run_state` adds Series 4's raw SUB 0x49 code to `detail` (one more
round trip); Series 3 has no 0x49 and ignores it."""
return self._dispatch(address, serial, self._s3.status,
lambda client, s: s4_status(client, s, run_state=run_state))
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
return self._dispatch(address, serial, self._s3.settings, s4_settings)
def list_events(self, address: UnitAddress, serial: str) -> EventList:
return self._dispatch(address, serial, self._s3.list_events, s4_list_events)
def download_event(self, address: UnitAddress, serial: str, event_id: str) -> DownloadedEvent:
"""Read-only on the unit. Holds the unit for the whole download, so
other requests for it wait, then get 423."""
key, stamp = parse_event_id(event_id, serial) # BadRequest before any I/O
return self._dispatch(
address, serial,
lambda a, s: self._s3.download_event(a, s, key, stamp),
lambda c, s: s4_download_event(c, s, key, stamp))
def start_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=True, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def stop_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=False, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def _change_monitoring(self, address, serial, *, start, dry_run, even_if_already, caller):
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(start=start, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, caller=caller, sleep=self._sleep,
verify_timeout_s=self._verify_timeout_s,
verify_interval_s=self._verify_interval_s)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_monitoring(a, s, **kw),
lambda c, s: s4_change_monitoring(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:
session = self._sessions.get(address.key)
if session is not None and session.is_open:
return session.serial
return None
def hang_up(self, address: UnitAddress) -> bool:
with self._locks.hold(address.key):
with self._sessions_guard:
session = self._sessions.pop(address.key, None)
if session is None:
return False
was_open = session.is_open
session.hang_up()
return was_open
# ── dispatch ──────────────────────────────────────────────────────────────
def _dispatch(self, address: UnitAddress, serial: str,
s3_op: Callable[[UnitAddress, str], Any],
s4_op: Callable[[Any, str], Any], *, change: bool = False) -> Any:
serial = normalise_serial(serial)
series = series_for_serial(serial) # raises BadRequest before any I/O
with self._locks.hold(address.key):
if series == 3:
with self._sessions_guard:
held = self._sessions.get(address.key)
if held is not None and held.is_open:
raise WrongUnit(
f"a Series-4 line to {held.serial} is held at {address.key}; "
"a Series-3 unit cannot be there -- POST /device/hangup first "
"if the modem has moved")
return s3_op(address, serial)
session = self._session_for(address, serial)
was_held = session.is_open
try:
return session.run(lambda client: s4_op(client, serial))
except DeviceError as exc:
self._forget_if_closed(address, session)
# A held line the peer dropped still reads open (the transport only
# learns at EOF), so the first request on it times out or fails.
# Call up fresh and retry ONCE. Safe only because every operation
# here is a read (identify, status, settings, list, download -- all
# idempotent). A change (`change=True`) is never retried, by
# construction: a write whose ack was lost must never be sent twice.
if was_held and not change and isinstance(exc, (NoAnswer, ConnectFailed)):
self._drop(address.key, session)
session.hang_up()
session = self._session_for(address, serial)
try:
return session.run(lambda client: s4_op(client, serial))
except DeviceError:
self._forget_if_closed(address, session)
raise
raise
def _forget_if_closed(self, address: UnitAddress, session: Series4Session) -> None:
if not session.is_open:
self._drop(address.key, session)
def _session_for(self, address: UnitAddress, serial: str) -> Series4Session:
with self._sessions_guard:
session = self._sessions.get(address.key)
if session is not None and session.serial != serial:
if session.is_open:
raise WrongUnit(
f"a Series-4 line to {session.serial} is held at {address.key}; "
f"{serial} cannot be reached there -- POST /device/hangup first "
"if the modem has moved")
session = None
if session is None:
session = Series4Session(address, serial, self._s4_factory, clock=self._clock)
self._sessions[address.key] = session
self._ensure_reaper()
return session
# ── the reaper ────────────────────────────────────────────────────────────
def tick(self, now: Optional[float] = None) -> None:
"""Per held line: hang up if idle, else keep alive, else listen for a ring."""
now = self._clock() if now is None else now
with self._sessions_guard:
items = list(self._sessions.items())
for key, session in items:
with self._locks.try_hold(key) as held:
if not held:
continue # mid-request: not idle
if not session.is_open:
self._drop(key, session)
continue
try:
if now - session.last_used >= self._idle_hangup_s:
session.hang_up()
self._drop(key, session)
elif now - session.last_traffic >= self._keepalive_s:
session.keepalive()
else:
session.listen()
except DeviceError as exc:
log.warning("held line %s closed: %s", key, exc)
self._drop(key, session)
def _drop(self, key: str, session: Series4Session) -> None:
with self._sessions_guard:
if self._sessions.get(key) is session:
del self._sessions[key]
def _ensure_reaper(self) -> None:
if not self._start_reaper or self._reaper is not None:
return
self._reaper = threading.Thread(target=self._reaper_loop, name="sfm-held-lines", daemon=True)
self._reaper.start()
def _reaper_loop(self) -> None:
while True:
time.sleep(self._reaper_interval_s)
try:
self.tick()
except Exception: # noqa: BLE001
log.exception("held-line reaper tick failed")
-237
View File
@@ -1,237 +0,0 @@
"""The series-independent core of a start/stop request.
Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once ->
read back -> audit). Each series supplies only its own pieces as callables:
how to read the serial, how to read the run-state name, how to send (returning
the ack record), how to recognise a refusal or a ring, and optionally what to
drain from the line just before sending. Nothing in here retries: `send` is
called at most once, and every path after `audit.begin` calls `audit.finish`
exactly once, through `finish` below.
Once the send has started, a failure is never reported as if nothing went out:
it is a `ChangeUnconfirmed` naming the audit row, carrying the status its cause
would have had. The row's `sent` column says whether a frame went out (1),
did not (0), or may have (NULL), and `states` keeps every state read.
The state names `calling_home` and `unknown*` are Series-4 states, except
`unknown(...)`, which Series 3 also produces for a flag byte never measured.
Series 3 never produces `calling_home` or a ring, so those branches are simply
never taken there.
"""
from __future__ import annotations
from typing import Any, Callable, Dict, List, NoReturn, Optional
from .errors import (
AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, NotSupported,
UnitStateUnknown, WrongUnit, translate,
)
from .models import ChangeResult, UnitAddress
from .series import normalise_serial
CALL_HOME_MESSAGE = ("the unit started calling home; SFM hung up so the call can "
"reach THOR -- try again in a few minutes")
_HUNG_UP = "SFM hung up so the call can reach THOR"
# The row's `sent` column.
SENT_ACKNOWLEDGED, NOTHING_SENT, SENT_UNKNOWN = 1, 0, None
def _never(exc: BaseException) -> bool:
return False
def run_change(*, serial: str, series: int, start: 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,
read_serial: Callable[[], str],
read_state: Callable[[], str],
describe_plan: Callable[[], Dict[str, Any]],
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"
reported = normalise_serial(read_serial())
if reported != serial:
raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- "
"nothing sent")
before = read_state()
if before == "calling_home":
raise CallHomeInProgress(CALL_HOME_MESSAGE)
if before.startswith("unknown") and not dry_run:
raise UnitStateUnknown(f"the unit reports run state {before}, which has never "
"been measured -- nothing sent")
planned = dict(describe_plan(), sends_nothing=dry_run)
base = dict(serial=serial, series=series, action=action, plan=planned, state_before=before)
if dry_run:
return ChangeResult(dry_run=True, sent=False, outcome="dry_run",
verified="not_checked", state_after=None, audit_id=None, **base)
if audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
request = {"plan": planned, "even_if_already": even_if_already}
try:
cid = audit.begin(serial=serial, series=series, address=address.key, action=action,
tier="change", request=request, caller=caller)
except Exception as exc: # noqa: BLE001
raise AuditUnavailable(
f"the audit log could not be written -- nothing sent: {exc}") from exc
def states(seen: List[str], after: Optional[str]) -> Dict[str, Any]:
return {"before": before, "seen": list(seen), "after": after}
def finish(unit: str, *, release_line: bool = False, **fields: Any) -> None:
"""The only way a row is finished. `unit` says what happened to the
unit, so a finish that fails still says it. `release_line` says whether
this path hangs up anyway, so a failed finish does not hold the line."""
try:
audit.finish(cid, **fields)
except Exception as exc: # noqa: BLE001
raise AuditIncomplete(
f"{unit} -- but audit record {cid} could not be finished: {exc}",
release_line=release_line) from exc
def unconfirmed(unit: str, cause: BaseException, *, went_out: str, status: int,
**fields: Any) -> NoReturn:
"""Finish the row, then say the change went out (or may have) and name it.
`went_out` is "acknowledged" or "unknown"; the row's `sent` follows it."""
finish(unit, release_line=True,
sent=SENT_ACKNOWLEDGED if went_out == "acknowledged" else SENT_UNKNOWN,
**fields)
raise ChangeUnconfirmed(f"{unit} -- audit record {cid}", audit_id=cid, sent=went_out,
http_status=status) from cause
def status_of(exc: BaseException) -> int:
return translate(exc, connecting=False).http_status
if before == want and not even_if_already:
finish(f"nothing was sent ({serial} is already {want})",
outcome="skipped", verified="not_checked", ack=None, error=f"already {want}",
sent=NOTHING_SENT, states=states([before], None))
return ChangeResult(dry_run=False, sent=False, outcome="skipped",
verified="not_checked", state_after=before,
audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base)
if pre_send is not None:
try:
pre_send() # sends nothing: drains what is already waiting
except Exception as exc: # noqa: BLE001
if is_ring(exc):
finish("nothing was sent (a call-home began before sending)", release_line=True,
outcome="failed", verified="not_checked", ack=None,
error="a call-home began before sending -- nothing sent",
sent=NOTHING_SENT, states=states([before], None))
raise CallHomeInProgress(CALL_HOME_MESSAGE) from exc
finish(f"nothing was sent (the line failed before sending: {exc})", release_line=True,
outcome="failed", verified="not_checked", ack=None,
error=f"the line failed before sending -- nothing sent: {exc}",
sent=NOTHING_SENT, states=states([before], None))
raise # the link is suspect
try:
ack = send() # the only send; nothing below can reach it again
except Exception as exc: # noqa: BLE001 -- recorded, never retried
if is_refusal(exc): # refused by the gate: nothing went out
finish(f"nothing was sent (refused before sending: {exc})", release_line=True,
outcome="failed", verified="not_checked", ack=None,
error=f"refused before sending: {exc}",
sent=NOTHING_SENT, states=states([before], None))
raise
if is_ring(exc):
unconfirmed(f"{action} was sent, but a call-home began in place of the "
f"acknowledgement -- whether it {became} is unknown; {_HUNG_UP}",
exc, went_out="unknown", status=CallHomeInProgress.http_status,
outcome="failed", verified="not_checked", ack=None,
error=f"a call-home began in place of the ack: {exc}",
states=states([before], None))
try:
after: Optional[str] = read_state()
except Exception as follow: # noqa: BLE001
if is_ring(follow):
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
f"the unit then began calling home -- whether it {became} is "
f"unknown; {_HUNG_UP}",
follow, went_out="unknown", status=CallHomeInProgress.http_status,
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; a call-home began: {follow}",
states=states([before], None))
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
f"reading the state afterwards failed ({follow}) -- whether it "
f"{became} is unknown",
exc, went_out="unknown", status=status_of(exc),
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; the follow-up read failed: {follow}",
states=states([before], None))
if after == "calling_home":
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
f"the unit then began calling home -- whether it {became} is "
f"unknown; {_HUNG_UP}",
exc, went_out="unknown", status=CallHomeInProgress.http_status,
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; the unit is now calling home",
states=states([before], after))
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))
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)
seen = [before]
def last_poll() -> Optional[str]:
return seen[-1] if len(seen) > 1 else None
polls = int(verify_timeout_s // verify_interval_s)
try:
for _ in range(polls):
sleep(verify_interval_s)
seen.append(read_state())
if seen[-1] == want or seen[-1] == "calling_home":
break
except Exception as exc: # noqa: BLE001 -- the row must not stay pending
if is_ring(exc):
unconfirmed(f"{action} was sent and acknowledged, but the unit then began "
f"calling home before its state could be read back -- whether it "
f"{became} is unknown; {_HUNG_UP}",
exc, went_out="acknowledged", status=CallHomeInProgress.http_status,
outcome="sent", verified="not_checked", ack=ack,
error=f"sent and acknowledged; a call-home began while reading the "
f"state back: {exc}",
states=states(seen, last_poll()))
unconfirmed(f"{action} was sent and acknowledged, but reading the state back "
f"failed: {exc}",
exc, went_out="acknowledged", status=status_of(exc),
outcome="sent", verified="not_checked", ack=ack,
error=f"sent and acknowledged; reading the state back failed: {exc}",
states=states(seen, last_poll()))
if seen[-1] == "calling_home":
cause = CallHomeInProgress(CALL_HOME_MESSAGE)
unconfirmed(f"{action} was sent and acknowledged, but the unit then began calling "
f"home -- whether it {became} is unknown; {_HUNG_UP}",
cause, went_out="acknowledged", status=cause.http_status,
outcome="sent", verified="not_checked", ack=ack,
error="sent and acknowledged; the unit then began calling home",
states=states(seen, last_poll()))
ok = seen[-1] == want
outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch")
error = None if ok else f"unit reads {seen[-1]}, expected {want}"
detail: Dict[str, Any] = {"states_seen": seen, "ack": ack}
if even_if_already and before == want:
note = (f"the unit was already {want} before sending; the read-back cannot show "
"that this send changed anything")
detail["note"] = note
if error is None:
error = note
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()))
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
state_after=seen[-1], audit_id=cid, detail=detail, **base)
-116
View File
@@ -1,116 +0,0 @@
"""Typed device errors, each with the HTTP status the endpoints return."""
from __future__ import annotations
import micromate.protocol as _mm_proto
import minimateplus.protocol as _mmp_proto
class DeviceError(Exception):
http_status = 500
class BadRequest(DeviceError):
http_status = 422
class NotSupported(DeviceError):
http_status = 501
class WrongUnit(DeviceError):
http_status = 409
class UnitStateUnknown(DeviceError):
"""The unit reports a run state that has never been measured."""
http_status = 409
class AuditUnavailable(DeviceError):
"""The audit row could not be written, so nothing was sent."""
http_status = 503
class AuditIncomplete(DeviceError):
"""The unit was dealt with, but its audit row could not be finished. The
message says what happened to the unit first, then names the row.
`release_line` is True when the path would have hung up had the finish
worked (a ring, a link fault, a refusal): the failed write to the audit log
must not turn that into a held line, which would block a call-home."""
http_status = 500
def __init__(self, message: str, *, release_line: bool = False) -> None:
super().__init__(message)
self.release_line = release_line
class ChangeUnconfirmed(DeviceError):
"""A change failed after its frame went out, or may have gone out.
`sent` is "acknowledged" (the ack came back; the read-back failed) or
"unknown" (the ack was lost, or a call-home took its place). The status is
the one the cause would have had, set per instance, and the message names
the audit record. It never means "nothing was sent".
"""
http_status = 500
def __init__(self, message: str, *, audit_id: str, sent: str, http_status: int) -> None:
if sent not in ("acknowledged", "unknown"):
raise ValueError(f"sent must be 'acknowledged' or 'unknown', not {sent!r}")
super().__init__(message)
self.audit_id = audit_id
self.sent = sent
self.http_status = http_status
class UnitBusy(DeviceError):
http_status = 423
class ConnectFailed(DeviceError):
http_status = 503
class CallHomeInProgress(DeviceError):
http_status = 503
class NoAnswer(DeviceError):
http_status = 504
class MalformedReply(DeviceError):
http_status = 502
class EventNotFound(DeviceError):
http_status = 404
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."""
http_status = 409
_TIMEOUTS = (_mm_proto.TimeoutError, _mmp_proto.TimeoutError)
_PROTOCOL = (_mm_proto.ProtocolError, _mmp_proto.ProtocolError)
def translate(exc: BaseException, *, connecting: bool) -> DeviceError:
"""Map a library exception to a typed error.
Order matters: each library's TimeoutError is a ProtocolError subclass, and
the builtin TimeoutError (a failed TCP connect) is an OSError.
"""
if isinstance(exc, DeviceError):
return exc
if isinstance(exc, _TIMEOUTS):
return NoAnswer(f"the unit did not answer: {exc}")
if isinstance(exc, _PROTOCOL):
return MalformedReply(f"bad reply from the unit: {exc}")
if isinstance(exc, OSError):
what = "could not connect" if connecting else "connection lost"
return ConnectFailed(f"{what}: {exc}")
return DeviceError(f"device error: {exc}")
-51
View File
@@ -1,51 +0,0 @@
"""Event identity. An `event_id` is `<serial>:<key hex>:<YYYYmmddHHMMSS>`.
The key alone is not enough: both series reuse keys (a MiniMate restarts at
01110000 after an erase; every Micromate's counter starts at the same value).
The timestamp turns a stale id into a loud StaleEvent instead of a download of
whatever now sits at that key. "-" stands in for an unknown timestamp.
"""
from __future__ import annotations
import datetime
from typing import Optional, Tuple
from .errors import BadRequest
from .series import normalise_serial
_NO_STAMP = "-"
_STAMP_FMT = "%Y%m%d%H%M%S"
def stamp_of(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.strftime(_STAMP_FMT) if dt is not None else None
def iso_of(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.isoformat() if dt is not None else None
def make_event_id(serial: str, key: bytes, stamp: Optional[str]) -> str:
return f"{normalise_serial(serial)}:{key.hex()}:{stamp or _NO_STAMP}"
def parse_event_id(event_id: str, serial: str) -> Tuple[bytes, Optional[str]]:
"""(key, stamp) for an id that belongs to `serial`; BadRequest otherwise."""
parts = (event_id or "").strip().split(":")
if len(parts) != 3:
raise BadRequest(f"not an event_id: {event_id!r} -- take it from GET /device/events")
id_serial, key_hex, stamp = parts
if normalise_serial(id_serial) != normalise_serial(serial):
raise BadRequest(f"event_id {event_id!r} belongs to {id_serial}, not {serial}")
try:
key = bytes.fromhex(key_hex)
except ValueError:
key = b""
if len(key) != 4:
raise BadRequest(f"event_id {event_id!r}: the key must be 8 hex digits")
if stamp != _NO_STAMP:
try:
datetime.datetime.strptime(stamp, _STAMP_FMT)
except ValueError:
raise BadRequest(f"event_id {event_id!r}: bad timestamp {stamp!r}") from None
return key, (None if stamp == _NO_STAMP else stamp)
-41
View File
@@ -1,41 +0,0 @@
"""One connection per unit. A modem allows a single TCP session, so two
requests must take turns instead of opening a second connection."""
from __future__ import annotations
import threading
from contextlib import contextmanager
from typing import Dict, Iterator, Optional
from .errors import UnitBusy
class UnitLocks:
def __init__(self, timeout: float = 20.0) -> None:
self._timeout = timeout
self._guard = threading.Lock()
self._locks: Dict[str, threading.Lock] = {}
def _lock_for(self, key: str) -> threading.Lock:
with self._guard:
return self._locks.setdefault(key, threading.Lock())
@contextmanager
def hold(self, key: str, timeout: Optional[float] = None) -> Iterator[None]:
lock = self._lock_for(key)
wait = self._timeout if timeout is None else timeout
if not lock.acquire(timeout=wait):
raise UnitBusy(f"the unit at {key} is busy with another request; try again shortly")
try:
yield
finally:
lock.release()
@contextmanager
def try_hold(self, key: str) -> Iterator[bool]:
lock = self._lock_for(key)
got = lock.acquire(blocking=False)
try:
yield got
finally:
if got:
lock.release()
-153
View File
@@ -1,153 +0,0 @@
"""Series-neutral models. Every operation returns the same shape for both
series; anything only one series has goes under `detail`."""
from __future__ import annotations
import datetime
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from .errors import BadRequest
@dataclass(frozen=True)
class UnitAddress:
host: Optional[str]
tcp_port: Optional[int]
port: Optional[str]
baud: Optional[int]
def __post_init__(self) -> None:
if not self.host and not self.port:
raise BadRequest(
"specify 'host' (TCP, e.g. ?host=10.0.0.5&tcp_port=9034) "
"or 'port' (serial, e.g. ?port=/dev/ttyACM0)"
)
@property
def key(self) -> str:
"""One key per physical link -- what the per-unit lock is keyed on."""
if self.host:
return f"tcp:{self.host}:{self.tcp_port}"
return f"serial:{self.port}"
@dataclass
class UnitInfo:
serial: str
series: int
model: Optional[str]
firmware: Optional[str]
monitoring: Optional[bool]
active_setup: Optional[str]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class UnitStatus:
serial: str
series: int
monitoring: bool
battery_volts: Optional[float]
memory_total_bytes: Optional[int]
memory_free_bytes: Optional[int]
device_time: Optional[str] # ISO, the unit's own local time
event_count: Optional[int] # None where it is not cheap (Series 3)
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class UnitSettings:
serial: str
series: int
setup_name: Optional[str]
record_mode: Optional[str] # the unit's own name for its mode
sample_rate: Optional[int]
record_time_s: Optional[float]
histogram_interval_s: Optional[int]
geo_trigger_ips: Optional[float]
notes: Dict[str, str] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventRef:
"""One stored event, as listed. `event_id` is opaque: pass it back to
download the event. `index` is its position in the list right now; an
erase renumbers it, so it is for display, never identity."""
event_id: str
serial: str
series: int
index: int
timestamp: Optional[str] # ISO, the unit's own local time
record_type: Optional[str] # "waveform" | "histogram"
peak_vector_sum_ips: Optional[float]
peaks_ips: Dict[str, float] # geophones only: tran / vert / long
filename: Optional[str] # the name the vendor's software gives it
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventList:
serial: str
series: int
events: List[EventRef]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventDownload:
"""What a download stored. The file and waveform are then served at
/db/events/{db_event_id}/... ."""
event_id: str
serial: str
series: int
db_event_id: Optional[str]
stored_filename: str
filesize: Optional[int] # None only for a stored row with no file recorded
sha256: Optional[str] # None when the event was already stored
inserted: bool # False: already stored; nothing was written (detail.already_stored)
verified: Optional[bool] # True: decode self-check passed; None: no check exists
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class DownloadedEvent:
"""The device side's result, before SFM stores it. Not an HTTP shape: it
carries the payload -- a Series-3 Event + its 5A frames + the compliance
config, or a Series-4 file's bytes -- to sfm.event_ingest.
`timestamp` is the event's time as the unit reported it: the store looks up
an existing row by (serial, timestamp) before writing anything. `record` is
what the unit's own event record said (Series 4's 0x0C), for the fields the
file alone does not give."""
event_id: str
serial: str
series: int
filename: str
verified: Optional[bool]
idf_bytes: Optional[bytes] = field(default=None, repr=False)
event: Any = field(default=None, repr=False)
a5_frames: Optional[list] = field(default=None, repr=False)
compliance: Any = field(default=None, repr=False)
timestamp: Optional[datetime.datetime] = None
record: Dict[str, Any] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class ChangeResult:
"""The outcome of a change request. `outcome`: "dry_run" | "skipped" | "sent" |
"failed". `verified`: "ok" | "mismatch" | "not_checked". `plan` is the exact
frames planned (dry run) or sent."""
serial: str
series: int
action: str
dry_run: bool
sent: bool
outcome: str
verified: str
state_before: Optional[str]
state_after: Optional[str]
audit_id: Optional[str]
plan: Dict[str, Any] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict)
-387
View File
@@ -1,387 +0,0 @@
"""Series-3 adapter. Connect-per-request, as SFM has always done for
MiniMates -- a held session waits for the bench test in the spec."""
from __future__ import annotations
import datetime
import logging
import struct
from typing import Any, Callable, Optional
from minimateplus import MiniMateClient
from minimateplus.blastware_file import blastware_filename
from minimateplus.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.transport import TcpTransport
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate
from .change import run_change
from .events import iso_of, make_event_id, stamp_of
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
log = logging.getLogger("sfm.device_access")
S3_DEFAULT_BAUD = 38400
S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "Histogram + Continuous"}
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
# 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.
S3_RUN_STATES = {0x00: "idle", 0x10: "monitoring", 0x0B: "monitoring"}
def s3_run_state(status: Any) -> str:
"""The change path's state name from the raw 0x1C flag -- never
`is_monitoring`, which reads every byte but 0x10 as idle. A value never
measured is `unknown(0x..)`, and the change core refuses it."""
flag = getattr(status, "state_flag", None)
if flag is None:
return "unknown(short)"
return S3_RUN_STATES.get(flag, f"unknown(0x{flag:02X})")
# A start makes the unit run its sensor check before "Recording..." -- ~30 s
# (Brian, 2026-10-26), ~40 s on BE11529 (2026-04-08). A start's read-back waits
# this long before asking, then wakes the unit with retries (S3_WAKE_*).
S3_SENSOR_CHECK_S = 30.0
S3_WAKE_ATTEMPT_S = 5.0
S3_WAKE_DEADLINE_S = 60.0
def _woken_state(client: Any) -> str:
"""The run state, read after waking the unit: SESSION_RESET + POLL first,
re-sent until it answers.
A monitoring MiniMate ignores a bare request until it is woken (measured
2026-04-08). On 2026-10-26 BE9441 acked a start, then left a bare 0x1C, and
later a single SESSION_RESET + POLL, unanswered for 120 s: both went out 2 s
after the start, inside the sensor check, and were never re-sent."""
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
return s3_run_state(client.get_monitor_status())
def default_s3_client_factory(address: UnitAddress, timeout: Optional[float] = None) -> MiniMateClient:
if address.host:
return MiniMateClient(transport=TcpTransport(address.host, port=address.tcp_port),
timeout=10.0 if timeout is None else timeout)
if timeout is None:
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD)
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD, timeout=timeout)
def _close(client: Any) -> None:
try:
client.close()
except Exception: # noqa: BLE001
log.debug("close failed", exc_info=True)
def _s3_dt(ev: Any) -> Optional[datetime.datetime]:
ts = getattr(ev, "timestamp", None)
if ts is None or ts.hour is None:
return None
try:
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
except (TypeError, ValueError):
return None
def _s3_filename(ev: Any, serial: str) -> Optional[str]:
try:
return blastware_filename(ev, serial)
except Exception: # noqa: BLE001
return None
S3_RECORD_TYPE_NOTE = "Series 3's event record does not say waveform or histogram; not decoded yet"
def _s3_ref(ev: Any, serial: str) -> EventRef:
"""record_type is always None: minimateplus's 0C decode reports "Waveform"
for every record layout, histograms included, so it cannot be trusted
here. Null rather than wrong until a histogram's 0C is captured."""
dt = _s3_dt(ev)
pv = ev.peak_values
peaks = {}
if pv is not None:
peaks = {k: v for k, v in (("tran", pv.tran), ("vert", pv.vert), ("long", pv.long))
if v is not None}
return EventRef(
event_id=make_event_id(serial, ev._waveform_key, stamp_of(dt)),
serial=serial, series=3, index=ev.index, timestamp=iso_of(dt),
record_type=None,
peak_vector_sum_ips=pv.peak_vector_sum if pv is not None else None,
peaks_ips=peaks, filename=_s3_filename(ev, serial),
detail={"mic_psi": pv.micl if pv is not None else None,
"record_type_note": S3_RECORD_TYPE_NOTE},
)
_GEO_FULL_SCALE_IPS = 10.0 # normal range; one decoder step = 0.005 in/s
_PEAK_TOLERANCE_IPS = 0.0051 # one 0.005 in/s step, plus the 0C's float32 slop
def verify_s3_download(ev: Any, compliance: Any, body: Optional[bytes] = None) -> tuple:
"""Check a downloaded event against itself and the unit's own 0C record: (verified, why).
A short or misassembled event must not reach the store -- BE9441's bench
(2026-10-25) stored two as successes before this existed. `body` is the
event's 5A body (taken from `ev._a5_frames` when not given). In order:
* No waveform decode: it must decode as a histogram (stored unverified --
its peaks are not compared yet), or it is refused. 0 of ~430 fixture
histograms decode as a waveform; a corrupted waveform decodes as neither.
* A waveform's record chain must end on its END record (0x06), as the
file reader requires; a cut-short stream does not.
* All three geophone channels must be the same length.
* Each channel's peak must be the unit's own to one 0.005 in/s step (a
clipped blast -- both at full scale -- counts as a match). Only for a
unit confirmed in normal range: a sensitive-range unit's scale is still
open (the 8x discrepancy), and an unread range is not assumed.
Raises MalformedReply ("not saved") on any failure.
"""
from minimateplus.blastware_file import extract_body_bytes
from minimateplus.histogram_codec import decode_histogram_body
from minimateplus.waveform_codec import STREAM_END_ID, walk_records
if body is None:
frames = getattr(ev, "_a5_frames", None)
body = extract_body_bytes(frames)[1] if frames else b""
samples = getattr(ev, "raw_samples", None) or {}
chans = ("Tran", "Vert", "Long")
if not all(samples.get(c) for c in chans):
if body and decode_histogram_body(body):
return None, "a histogram: stored unverified (its peaks are not compared yet)"
raise MalformedReply(
"the downloaded event decodes as neither a waveform nor a histogram -- the "
"download is incomplete or misassembled; not saved")
try:
recs = walk_records(body)
except Exception: # noqa: BLE001 -- treated as no chain
recs = []
tail = recs[-1]["end"] if recs else None
if tail is None or tail + 5 > len(body) or body[tail + 4] != STREAM_END_ID:
raise MalformedReply(
"the downloaded waveform's record chain has no end record -- the download is "
"cut short; not saved")
lengths = {c: len(samples[c]) for c in chans}
if len(set(lengths.values())) != 1:
raise MalformedReply(
f"the downloaded waveform's channels have different lengths {lengths} -- the "
"download is incomplete or misassembled; not saved")
if getattr(compliance, "geo_range", None) != 0:
return None, ("whole, but peaks not checked: the unit is not confirmed in normal "
"range (a sensitive-range scale is not settled)")
pv = ev.peak_values
unit = {"Tran": pv.tran, "Vert": pv.vert, "Long": pv.long} if pv else {}
clip = _GEO_FULL_SCALE_IPS - _PEAK_TOLERANCE_IPS
for c in chans:
if unit.get(c) is None:
return None, f"whole, but the unit's record gives no {c} peak to check against"
decoded = max(abs(x) for x in samples[c]) * _GEO_FULL_SCALE_IPS / _GEO_INT16_FS
if decoded >= clip and unit[c] >= clip:
continue # both at full scale: a clipped blast
if abs(decoded - unit[c]) > _PEAK_TOLERANCE_IPS:
raise MalformedReply(
f"the downloaded {c} peak is {decoded:.4f} in/s but the unit's own record says "
f"{unit[c]:.4f} -- the download is incomplete or misassembled; not saved")
return True, f"{lengths['Tran']} samples per channel, peaks match the unit's own"
class Series3Adapter:
def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None:
self._factory = client_factory
def change_monitoring(self, address: UnitAddress, serial: str, *, start: 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 in change.py. One attempt, never
retried: `retry=False` stops _run's cold-boot second attempt, and the
core calls the write once."""
sub = SUB_START_MONITORING if start else SUB_STOP_MONITORING
ack_sub = 0xFF - sub
def op(client: Any) -> ChangeResult:
def read_serial() -> str:
info = client.connect() # a fresh connection: connect() is the fresh 0x15 read
return info.serial or ""
def describe_plan() -> dict:
what = "start monitoring" if start else "stop monitoring"
return {"action": what, "sends_nothing": True, "warnings": [],
"steps": [{"sub": f"0x{sub:02X}", "what": what, "offset": "0x0000",
"data_len": 0, "expect_ack": f"0x{ack_sub:02X}",
"frame": build_bw_write_frame(sub, b"").hex()}]}
settle: list = []
def send() -> dict:
# The client validates the ack SUB; it returns nothing else, so none is claimed.
(client.start_monitoring if start else client.stop_monitoring)()
if start:
settle.append(S3_SENSOR_CHECK_S) # the first read waits out the check
return {"subs": [f"0x{ack_sub:02X}"]}
def read_state() -> str:
if settle:
sleep(settle.pop())
return _woken_state(client)
return run_change(
serial=serial, series=3, start=start, 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)
return self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False)
def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None,
retry: bool = True) -> Any:
def attempt() -> Any:
client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)
try:
client.open()
except Exception as exc:
_close(client)
raise translate(exc, connecting=True) from exc
try:
return fn(client)
except DeviceError:
raise
except Exception as exc:
raise translate(exc, connecting=False) from exc
finally:
_close(client)
try:
return attempt()
except NoAnswer:
# A MiniMate that has just had its serial lines asserted can take
# 5-10 s to boot, and shows it as silence; one retry covers it. TCP
# only -- on a serial cable a silence is a real fault. Narrower than
# server._run_with_retry (any protocol error): retrying a
# MalformedReply would also retry "no settings block", which a
# reconnect cannot fix.
if not retry or not address.host:
raise
log.info("Series 3 at %s: no clean answer, retrying once (unit may be cold)", address.key)
return attempt()
@staticmethod
def _check(serial_reported: str, serial: str, address: UnitAddress) -> None:
if (serial_reported or "").strip().upper() != serial:
raise WrongUnit(f"asked for {serial} but {serial_reported} answered at {address.key}")
def identify(self, address: UnitAddress, serial: str) -> UnitInfo:
def op(client: Any) -> UnitInfo:
info = client.connect()
self._check(info.serial, serial, address)
cc = info.compliance_config
return UnitInfo(
serial=info.serial, series=3, model=info.model, firmware=info.firmware_version,
monitoring=None, active_setup=cc.setup_name if cc else None,
detail={"manufacturer": info.manufacturer, "dsp_version": info.dsp_version},
)
return self._run(address, op)
def status(self, address: UnitAddress, serial: str) -> UnitStatus:
def op(client: Any) -> UnitStatus:
client.poll()
ms = client.get_monitor_status()
# The change path's reading, not a guess: an unmeasured flag is None.
monitoring = {"monitoring": True, "idle": False}.get(s3_run_state(ms))
return UnitStatus(
serial=serial, series=3, monitoring=monitoring,
battery_volts=round(ms.battery_v, 2) if ms.battery_v is not None else None,
memory_total_bytes=ms.memory_total, memory_free_bytes=ms.memory_free,
device_time=None, event_count=None,
# Series 3 status reads no serial, so the serial shown is the one requested, not one the unit reported.
detail={"serial_verified": False},
)
return self._run(address, op)
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
def op(client: Any) -> UnitSettings:
info = client.connect()
self._check(info.serial, serial, address)
cc = info.compliance_config
if cc is None:
raise MalformedReply("could not read the unit's settings (SUB 0x1A)")
mode = None
if cc.recording_mode is not None:
mode = S3_MODES.get(cc.recording_mode, f"unknown (0x{cc.recording_mode:02x})")
notes = {
label: value for label, value in (
("Project", cc.project), ("Client", cc.client), ("User Name", cc.operator),
("Seis Loc", cc.sensor_location), ("Extended Notes", cc.notes),
) if value is not None
}
return UnitSettings(
serial=info.serial, series=3, setup_name=cc.setup_name, record_mode=mode,
sample_rate=cc.sample_rate, record_time_s=cc.record_time,
histogram_interval_s=cc.histogram_interval_sec, geo_trigger_ips=cc.trigger_level_geo,
notes=notes,
detail={"record_mode_code": cc.recording_mode, "alarm_level_geo": cc.alarm_level_geo,
"geo_range": cc.geo_range},
)
return self._run(address, op)
def list_events(self, address: UnitAddress, serial: str) -> EventList:
def op(client: Any) -> EventList:
info = client.connect()
self._check(info.serial, serial, address)
return EventList(serial=serial, series=3,
events=[_s3_ref(ev, serial) for ev in client.list_event_headers()])
# The default timeout: a header walk is small replies only, so a lost
# one costs 10 s (TCP) with the unit locked, not 120 s.
return self._run(address, op)
def download_event(self, address: UnitAddress, serial: str, key: bytes,
stamp: Optional[str]) -> DownloadedEvent:
# The walk compares this with the target's 0C and, on a mismatch, sends
# no 5A: a stale id costs a header walk, not a full download of the
# wrong event.
iso = datetime.datetime.strptime(stamp, "%Y%m%d%H%M%S").isoformat() if stamp is not None else None
def op(client: Any) -> DownloadedEvent:
info = client.connect()
self._check(info.serial, serial, address)
try:
ev = client.download_event_by_key(key, expected_timestamp=iso)
except struct.error as exc:
# Defensive. This once caught the 64 KB page bug (TERM's offset driven
# negative); the walk is 32-bit linear since 2026-10-26 and no longer
# produces it, so reaching here is a new fault.
raise MalformedReply(
f"event {key.hex()}: its download could not be assembled ({exc}); not saved"
) from exc
if ev is None:
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
found = stamp_of(_s3_dt(ev))
if stamp is not None and found is None:
raise MalformedReply(
f"could not read event {key.hex()}'s record (0C) to confirm it is the one "
"listed -- not downloaded; try again")
if stamp is not None and found != stamp:
raise StaleEvent(
f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- "
"the unit was erased or wrapped since the list was read; list again")
if not ev._a5_frames:
raise MalformedReply(f"event {key.hex()}: no waveform data received (the 5A download failed)")
filename = _s3_filename(ev, serial)
if filename is None:
raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored")
verified, why = verify_s3_download(ev, info.compliance_config)
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,
compliance=info.compliance_config, timestamp=_s3_dt(ev),
detail={"a5_frames": len(ev._a5_frames), "check": why},
)
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
-371
View File
@@ -1,371 +0,0 @@
"""Series-4 sessions: call up once, stay on the line, hang up when idle.
⚠ **This module hosts a write path.** `s4_change_monitoring` is the Series-4
wrapper of the shared change core (`change.run_change`): it sends `0x96` /
`0x97` through `MicromateProtocol.execute()`, and it is the only caller of
`.protocol.execute(` in the codebase (a test pins that). Everything else here
is a read.
⚠ Imports only minimateplus.transport from the Series-3 package. Nothing
here may build or send a Series-3 frame -- SESSION_RESET (41 03) has never
been sent to a Micromate.
"""
from __future__ import annotations
import logging
import time
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 minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
from .errors import (
AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound,
MalformedReply, StaleEvent, WrongUnit, translate,
)
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 .series import normalise_serial
log = logging.getLogger("sfm.device_access")
T = TypeVar("T")
RING = b"RADIO RING"
S4_DEFAULT_BAUD = 115200
class RingDetected(Exception):
"""The unit sent RADIO RING: it is calling home up this connection."""
class RingWatchTransport(BaseTransport):
"""Passes bytes through; raises RingDetected the moment RADIO RING appears
OUTSIDE a frame, including when it is split across two reads.
Inside a frame the bytes are data: the 0x2C call-home config block's dial
string is literally "RADIO RING". A frame runs from STX to an unescaped
ETX; inside it DLE escapes the next byte.
"""
_STX, _ETX, _DLE = 0x02, 0x03, 0x10
def __init__(self, inner: BaseTransport) -> None:
self._inner = inner
self._tail = b""
self._in_frame = False
self._escaped = False
def connect(self) -> None:
self._inner.connect()
def disconnect(self) -> None:
self._inner.disconnect()
@property
def is_connected(self) -> bool:
return self._inner.is_connected
def write(self, data: bytes) -> None:
# A request starts a new exchange (MicromateProtocol resets its parser
# here too), so a stray STX on an idle line cannot hide the next ring.
self._in_frame = self._escaped = False
self._inner.write(data)
def read(self, n: int) -> bytes:
data = self._inner.read(n)
for b in data:
if self._in_frame:
if self._escaped:
self._escaped = False
elif b == self._DLE:
self._escaped = True
elif b == self._ETX:
self._in_frame = False
elif b == self._STX:
self._in_frame = True
self._tail = b""
else:
self._tail = (self._tail + bytes([b]))[-len(RING):]
if self._tail == RING:
self._tail = b""
raise RingDetected("RADIO RING")
return data
def default_s4_client_factory(address: UnitAddress, recv_timeout: float = 10.0) -> MicromateClient:
if address.host:
inner: BaseTransport = TcpTransport(address.host, port=address.tcp_port)
else:
inner = SerialTransport(address.port, address.baud or S4_DEFAULT_BAUD)
return MicromateClient(RingWatchTransport(inner), recv_timeout=recv_timeout)
def _close(client: Any) -> None:
try:
client.close()
except Exception: # noqa: BLE001
log.debug("close failed", exc_info=True)
_RING_MESSAGE = CALL_HOME_MESSAGE
class Series4Session:
"""One held line to one Micromate.
`last_used` is the last *user* request: the idle hang-up measures it.
`last_traffic` is any exchange, keep-alives included: the keep-alive
schedule measures it. If keep-alives counted as use, the line would never
go idle.
Invariant -- which errors keep the line. An operation raises a
`DeviceError` only for a verdict reached over a healthy link: the event is
not there, the id is stale, the record cannot be named. `_exchange` keeps
the line for those. Anything the library raises means the link is
suspect, and `_exchange` hangs up. `DecodeMismatch` is a library error,
so it hangs up too -- conservative, since the link may be fine. Operations
added in later phases must keep to this: never wrap a link failure in a
`DeviceError` inside an op, or the line stays open on a broken link.
The exceptions: `CallHomeInProgress` and `WrongUnit` release the line,
because the line itself is the problem; so does `ChangeUnconfirmed`, which
the change core raises only after a link fault or a ring, once the frame
has gone out. `AuditIncomplete` keeps the line unless its `release_line`
says the path would have hung up anyway (a ring, a link fault, a refusal).
"""
def __init__(self, address: UnitAddress, serial: str,
client_factory: Callable[[UnitAddress], Any],
clock: Callable[[], float] = time.monotonic) -> None:
self.address = address
self.serial = normalise_serial(serial)
self._factory = client_factory
self._clock = clock
self._client: Optional[Any] = None
self.info = None
self.last_used = clock()
self.last_traffic = self.last_used
@property
def is_open(self) -> bool:
client = self._client # one read: held_serial() calls this without the unit lock
return client is not None and client.is_open()
def call_up(self):
client = self._factory(self.address)
try:
client.open()
info = client.connect()
except RingDetected as exc:
_close(client)
log.warning("RADIO RING from %s during call-up -- released the line", self.address.key)
raise CallHomeInProgress(_RING_MESSAGE) from exc
except Exception as exc:
_close(client)
raise translate(exc, connecting=True) from exc
if normalise_serial(info.serial) != self.serial:
_close(client)
raise WrongUnit(f"asked for {self.serial} but {info.serial} answered at {self.address.key}")
self._client, self.info = client, info
self.last_used = self.last_traffic = self._clock()
log.info("call-up: %s at %s, staying on the line", self.serial, self.address.key)
return info
def _exchange(self, op: Callable[[Any], T]) -> T:
try:
return op(self._client)
except RingDetected as exc:
self.hang_up()
log.warning("RADIO RING from %s -- released the line so the call reaches THOR",
self.address.key)
raise CallHomeInProgress(_RING_MESSAGE) from exc
except (CallHomeInProgress, WrongUnit, ChangeUnconfirmed) as exc:
# The line itself is the problem: a call-home rides whatever holds the
# modem's single TCP session, and a line held for X that answers as Y
# must not stay held. ChangeUnconfirmed always follows a link fault
# or a ring (the core converts those itself, so the RingDetected
# clause above never sees them). All three are DeviceErrors, so this
# clause must stay above `except DeviceError`.
self.hang_up()
log.warning("%s at %s -- released the line: %s", type(exc).__name__,
self.address.key, exc)
raise
except AuditIncomplete as exc:
# A finish that failed on a path that hangs up anyway (ring, link
# fault, refusal) must still hang up; on a healthy path, keep the line.
if exc.release_line:
self.hang_up()
log.warning("AuditIncomplete at %s -- released the line: %s",
self.address.key, exc)
raise
except DeviceError:
# The operation's own verdict (event not found, stale id): the line
# is healthy, so keep it. Library errors still hang up below.
raise
except Exception as exc:
self.hang_up()
raise translate(exc, connecting=False) from exc
def run(self, op: Callable[[Any], T]) -> T:
"""A user request. Calls up first if the line is not open."""
if not self.is_open:
self.call_up()
result = self._exchange(op)
self.last_used = self.last_traffic = self._clock()
return result
def keepalive(self) -> None:
"""A POLL so the modem's idle timer does not drop the line. Not use."""
if not self.is_open:
return
self._exchange(lambda c: c.protocol.poll())
self.last_traffic = self._clock()
def listen(self) -> None:
"""Read anything the unit sent unprompted; send nothing. Not use."""
if not self.is_open:
return
self._exchange(lambda c: c.read_unsolicited())
def hang_up(self) -> None:
if self._client is not None:
_close(self._client)
self._client = None
log.info("hang-up: %s at %s", self.serial, self.address.key)
# ── Operations (each runs inside Series4Session.run) ──────────────────────────
def s4_identify(client: Any, serial: str) -> UnitInfo:
info = client.connect()
return UnitInfo(
serial=info.serial, series=4, model=info.model,
firmware=None, # the version string lives in 0x01, undecoded
monitoring=info.monitoring, active_setup=info.active_setup,
detail={"manufacturer": info.manufacturer, "firmware_line": info.firmware_line},
)
def s4_status(client: Any, serial: str, run_state: bool = False) -> UnitStatus:
st = client.get_state()
count = client.get_event_count()
detail = {}
if run_state: # one more round trip, so only when asked (the ring-path bench test)
rs = client.read_run_state()
detail["run_state"] = {"code": rs.code, "name": rs.name}
return UnitStatus(
serial=serial, series=4, monitoring=st.monitoring, battery_volts=st.battery_volts,
memory_total_bytes=st.memory_total_bytes, memory_free_bytes=st.memory_free_bytes,
device_time=st.device_time.isoformat() if st.device_time else None,
event_count=count, detail=detail,
)
def s4_settings(client: Any, serial: str) -> UnitSettings:
s = client.get_setup()
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,
histogram_interval_s=s.histogram_interval_s,
geo_trigger_ips=s.geo_trigger_ips[0], # the keypad writes all three the same
notes=dict(s.notes),
detail={
"pretrigger_s": s.pretrigger_s,
"auto_record_stop": s.auto_record_stop,
"auto_stop_after_s": s.auto_stop_after_s,
"geophones_active": s.geophones_active,
"mic_active": s.mic_active,
"trigger_on_geophones": s.trigger_on_geophones,
"trigger_on_mic": s.trigger_on_mic,
"geo_trigger_ips_per_channel": list(s.geo_trigger_ips),
"mic_type": s.mic_type,
"mic_trigger_psi": s.mic_trigger_psi,
"mic_trigger_db": s.mic_trigger_db,
"job_number_enabled": s.job_number_enabled,
"job_number": s.job_number,
"scaled_distance_enabled": s.scaled_distance_enabled,
"distance_ft": s.distance_ft,
"charge_weight_lb": s.charge_weight_lb,
"scaled_distance": s.scaled_distance,
},
)
def _s4_ref(ref: Any, serial: str) -> EventRef:
peaks = ref.peaks_ips or {}
return EventRef(
event_id=make_event_id(serial, ref.key, stamp_of(ref.timestamp)),
serial=serial, series=4, index=ref.index, timestamp=iso_of(ref.timestamp),
record_type=ref.record_type, peak_vector_sum_ips=ref.peak_vector_sum_ips,
peaks_ips={k.lower(): v for k, v in peaks.items() if k in ("Tran", "Vert", "Long")},
filename=ref.filename,
detail={"size_bytes": ref.size, "mic": peaks.get("Mic"), "setup": ref.setup,
"sensor_location": ref.sensor_location},
)
def s4_list_events(client: Any, serial: str) -> EventList:
return EventList(serial=serial, series=4,
events=[_s4_ref(r, serial) for r in client.list_events(with_records=True)])
def s4_download_event(client: Any, serial: str, key: bytes, stamp: Optional[str]) -> DownloadedEvent:
"""Walk to the event and download it there -- the order THOR uses, the only
one captured. Downloading at a parked cursor has never been tried."""
for ref in client.iter_events(with_records=True):
if ref.key != key:
continue
found = stamp_of(ref.timestamp)
if stamp is not None and found is None:
raise MalformedReply(
f"could not read event {key.hex()}'s record (0C) timestamp to confirm it "
"is the one listed -- not downloaded; try again")
if stamp is not None and found != stamp:
raise StaleEvent(
f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- "
"the unit was erased or wrapped since the list was read; list again")
if ref.filename is None:
raise MalformedReply(
f"event {key.hex()}: its record gave no type or timestamp, so it cannot be named or stored")
# THOR's chunk size. A 16 KB chunk takes ~7 s on cellular against the
# 10 s receive deadline; 1 KB is what THOR itself sends.
blob, result = client.fetch_event(ref, chunk_size=THOR_CHUNK_SIZE)
err = client.decode_error(ref, result)
return DownloadedEvent(
event_id=make_event_id(serial, key, found), serial=serial, series=4,
filename=ref.filename, verified=True if err is not None else None,
idf_bytes=blob, timestamp=ref.timestamp,
record={"peak_vector_sum_ips": ref.peak_vector_sum_ips,
"sensor_location": ref.sensor_location, "setup": ref.setup},
detail={"size_bytes": ref.size, "pvs_error": err},
)
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
def s4_change_monitoring(client: Any, serial: str, *, start: 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 in change.py."""
plan = plan_start_monitoring() if start else plan_stop_monitoring()
def send() -> dict:
acks = client.protocol.execute(plan)
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,
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=lambda: client.read_run_state().name,
describe_plan=plan.describe, send=send,
is_refusal=lambda e: isinstance(e, OpcodeRefused),
is_ring=lambda e: isinstance(e, RingDetected),
# A RADIO RING already buffered is caught here, before 0x96/0x97 goes
# 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())
-20
View File
@@ -1,20 +0,0 @@
"""Which series a unit is, from its serial prefix (decided with Brian, 2026-10-20)."""
from __future__ import annotations
from .errors import BadRequest
SERIES_BY_PREFIX = {"UM": 4, "BE": 3, "BA": 3}
def normalise_serial(serial: str) -> str:
return (serial or "").strip().upper()
def series_for_serial(serial: str) -> int:
s = normalise_serial(serial)
for prefix, series in SERIES_BY_PREFIX.items():
if s.startswith(prefix) and len(s) > len(prefix):
return series
raise BadRequest(
f"unknown serial {serial!r}: expected UM... (Series 4) or BE.../BA... (Series 3)"
)
+16 -3
View File
@@ -139,17 +139,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(
@@ -179,10 +185,15 @@ def write_event_hdf5(
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_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}
"""
@@ -199,7 +210,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.
-128
View File
@@ -1,128 +0,0 @@
"""Store an event SFM downloaded from a unit -- the SDM side of
POST /device/events/download.
Both series end in the two writes every other ingest path makes: the waveform
store (file + sidecar + .h5) and SeismoDb.insert_events().
An event already stored -- by an earlier download, or by THOR's watcher or
Blastware's ACH -- is returned as it is and NOTHING is written. The watcher's
copy is the richer one (its paired report carries PVS, project strings and ZC
frequencies a bare download does not), so a download never merges into it or
replaces it.
"""
from __future__ import annotations
import datetime
from pathlib import Path
from typing import Any, Optional
from sfm.device_access.models import DownloadedEvent, EventDownload
class IngestError(Exception):
"""Downloaded from the unit, but could not be stored."""
def backfill_series3_event(ev: Any, cc: Any) -> None:
"""Compliance-config values that supersede what the 5A stream decoded.
Some STRT fields have ambiguous semantics (STRT[20] is rectime, but
STRT[8:10] / STRT[16:18] are device-specific scratch, not reliable sample or
pre-trigger counts). Shared with GET /device/event/{i}/blastware_file.
"""
if not cc:
return
if ev.sample_rate is None and cc.sample_rate:
ev.sample_rate = cc.sample_rate
if cc.record_time:
# Authoritative: the user-set value the unit followed when recording.
ev.rectime_seconds = cc.record_time
# Derive total_samples from sample_rate x rectime when we can; the
# STRT-derived value can land at a buffer offset rather than a count.
if ev.sample_rate and ev.rectime_seconds:
derived = int(round(ev.sample_rate * ev.rectime_seconds))
if (ev.total_samples is None
or ev.total_samples > derived * 2
or ev.total_samples < derived // 4):
ev.total_samples = derived
def _event_dt(ev: Any) -> Optional[datetime.datetime]:
ts = getattr(ev, "timestamp", None)
try:
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
except Exception: # noqa: BLE001
return None
def _already_stored(dl: DownloadedEvent, row: dict) -> EventDownload:
return EventDownload(
event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row["id"],
stored_filename=row.get("blastware_filename") or "",
filesize=row.get("blastware_filesize"),
sha256=None, # the events table does not keep one
inserted=False, verified=dl.verified,
detail={**dl.detail, "already_stored": True},
)
def _overlay_s4_record(ev: Any, record: dict) -> None:
"""Fill, where the file left them empty, what the unit's 0x0C said.
Without Thor's TXT report the IDF file gives only the three PPVs. The
vector sum matters beyond display: find_twins matches on it. Not the mic:
its 0x0C decode reads a denormal (parked).
"""
from minimateplus.models import PeakValues, ProjectInfo
pvs = record.get("peak_vector_sum_ips")
if pvs is not None:
if ev.peak_values is None:
ev.peak_values = PeakValues()
if ev.peak_values.peak_vector_sum is None:
ev.peak_values.peak_vector_sum = pvs
location = record.get("sensor_location")
if location is not None:
if ev.project_info is None:
ev.project_info = ProjectInfo()
if ev.project_info.sensor_location is None:
ev.project_info.sensor_location = location
def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload:
# Never merge: a row for (serial, timestamp) means the event is stored, and
# whoever stored it first keeps it. No store call, no insert, no sidecar.
if dl.timestamp is not None:
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1)
if rows:
return _already_stored(dl, rows[0])
if dl.series == 4:
ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename),
serial_hint=dl.serial)
if ev is not None:
_overlay_s4_record(ev, dl.record)
family = "series4"
else:
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")
family = "series3"
if ev is None or ev._waveform_key is None:
raise IngestError(f"{dl.filename}: stored the file but could not build a database row")
inserted, _skipped = db.insert_events(
[ev], serial=dl.serial,
waveform_records={ev._waveform_key.hex(): rec}, device_family=family)
row_id = None
dt = _event_dt(ev)
if dt is not None:
rows = db.query_events(serial=dl.serial, from_dt=dt, to_dt=dt, limit=1)
row_id = rows[0]["id"] if rows else None
return EventDownload(
event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row_id,
stored_filename=rec["filename"], filesize=rec["filesize"], sha256=rec.get("sha256"),
inserted=inserted > 0, verified=dl.verified, detail=dict(dl.detail),
)
+35 -342
View File
@@ -13,14 +13,6 @@ GET /device/info POLL + serial number + full config read
GET /device/events Download all stored events (headers + peak values)
POST /device/connect Explicit connect/identify (same as /device/info)
GET /device/event/{idx} Single event by index (header + waveform record)
GET /device/settings Recording settings (requires serial)
POST /device/hangup Hang up a held Series-4 line
`serial` on /device/info, /device/connect, /device/monitor/status and
/device/settings names the unit (UM... = Series 4, BE.../BA... = Series 3) and
returns the shared model. Without it, the legacy Series-3 behaviour is
unchanged. Series-4 lines are held open between requests and hung up after
5 idle minutes, on POST /device/hangup, or the moment the unit calls home.
Transport query params (supply one set):
Serial (direct RS-232 cable):
@@ -50,7 +42,7 @@ import tempfile
import threading
import time
from pathlib import Path
from typing import Mapping, Optional
from typing import Optional
# FastAPI / Pydantic
try:
@@ -82,12 +74,6 @@ from sfm.database import SeismoDb
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
import dataclasses
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
from sfm.device_access.errors import BadRequest
from sfm.device_access.series import normalise_serial, series_for_serial
from sfm.audit import DbAudit
logging.basicConfig(
level=logging.INFO,
@@ -354,119 +340,6 @@ def _run_with_retry(fn, *, is_tcp: bool):
return fn() # let any second failure propagate normally
# ── Device access (serial-named requests) ─────────────────────────────────────
# A request that names the unit by `serial` goes through sfm.device_access:
# same contract for Series 3 and 4. Without `serial`, handlers run their
# legacy Series-3 path unchanged (spec 2026-10-20).
# Constructing it does no I/O and starts no thread until a Series-4 session exists.
# The audit sink is mandatory for live changes: without one they are refused.
_device_access_instance: DeviceAccess = DeviceAccess(audit=DbAudit(_get_db))
def _device_access() -> DeviceAccess:
return _device_access_instance
def _unit_address(port: Optional[str], baud: Optional[int], host: Optional[str],
tcp_port: int) -> UnitAddress:
return UnitAddress(host=host, tcp_port=tcp_port if host else None,
port=None if host else port, baud=baud)
def _via_device_access(fn) -> dict:
try:
result = fn()
except DeviceError as exc:
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
return dataclasses.asdict(result) if dataclasses.is_dataclass(result) else result
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.
"""
body = _via_device_access(fn)
# 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"))
status = 200 if ok else (409 if body["verified"] == "mismatch" else 502)
return JSONResponse(status_code=status, content=body)
_SERIAL_AWARE_PATHS = frozenset({
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
"/device/events", "/device/events/download",
"/device/monitor/start", "/device/monitor/stop",
})
def _device_guard(path: str, query: Mapping[str, str]) -> Optional[tuple]:
"""Refuse a /device/* request that would reach the wrong series' code.
FastAPI drops query params a route does not declare, so `?serial=UM...` on
a Series-3 route would silently run Series-3 bytes against a Micromate
(0xA2 is CONFIRM ERASE there). Returns (status, detail) to refuse, or None.
/device/hangup is always allowed: it must always be able to release a line.
"""
if not path.startswith("/device/") or path == "/device/hangup":
return None
serial = normalise_serial(query.get("serial") or "")
if serial and path in _SERIAL_AWARE_PATHS:
return None # DeviceAccess routes by series and checks held lines itself
if serial.startswith("UM"):
return 501, f"not supported for Series 4 yet: {path}"
# Everything else runs the legacy Series-3 handler -- whatever serial it
# carried, FastAPI drops it -- so it must not reach a held Series-4 line.
if not (query.get("host") or query.get("port")):
return None
try:
tcp_port = int(query.get("tcp_port") or DEFAULT_TCP_PORT)
# baud is not part of the address key, so it is not parsed here.
addr = _unit_address(query.get("port") or None, None, query.get("host") or None, tcp_port)
except (BadRequest, ValueError):
return None
held = _device_access().held_serial(addr)
if held is not None:
return 409, (f"a Series-4 line to {held} is held at {addr.key}; "
"POST /device/hangup first")
return None
@app.middleware("http")
async def _device_guard_middleware(request, call_next):
refusal = _device_guard(request.url.path, request.query_params)
if refusal is not None:
return JSONResponse(status_code=refusal[0], content={"detail": refusal[1]})
return await call_next(request)
_SERIAL_DOC = "Unit serial -- UM... (Series 4) or BE.../BA... (Series 3). Returns the shared model."
_SERIAL_CHECK_DOC = ("Expected unit serial (BE.../BA...). The unit's own serial is read before "
"any write; a different unit, or one that is not Series 3, is refused (409).")
def _require_series3(unit_serial: Optional[str], expected: Optional[str]) -> None:
"""Refuse (409) a legacy Series-3 write or erase unless the unit at the address
answers as Series 3 -- and as `expected`, when one was named.
0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate, and
these routes had no identity check (phase 1c, 2026-10-29). The serial comes
from connect() where a route already makes it, else one SUB 0x15 read.
"""
try:
series = series_for_serial(unit_serial or "")
except BadRequest:
series = None
if series != 3:
raise HTTPException(status_code=409, detail=(
f"the unit at this address answers as {unit_serial!r}, not a Series-3 unit -- nothing sent"))
if expected and normalise_serial(expected) != normalise_serial(unit_serial):
raise HTTPException(status_code=409, detail=(
f"the unit at this address is {unit_serial}, not {expected} -- nothing sent"))
# ── Helpers ────────────────────────────────────────────────────────────────────
def _backfill_events(events: list, info: "DeviceInfo") -> None:
@@ -531,11 +404,10 @@ def event_browser():
@app.get("/device/info")
def device_info(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5, /dev/ttyUSB0)"),
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
baud: int = Query(38400, description="Serial baud rate (default 38400)"),
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay (e.g. 203.0.113.5)"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
force: bool = Query(False, description="Bypass cache and re-read from device"),
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
) -> dict:
"""
Connect to the device, perform the POLL startup handshake, and return
@@ -549,10 +421,6 @@ def device_info(
and re-read directly from the device (e.g. after a config push).
The cache is also automatically invalidated after POST /device/config.
"""
if serial:
return _via_device_access(
lambda: _device_access().identify(_unit_address(port, baud, host, tcp_port), serial))
baud = 38400 if baud is None else baud
log.info("GET /device/info port=%s host=%s tcp_port=%d force=%s", port, host, tcp_port, force)
cache = get_cache()
@@ -591,39 +459,27 @@ def device_info(
@app.post("/device/connect")
def device_connect(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
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_DOC),
) -> dict:
"""
Connect to the device and return identity. POST variant for terra-view
compatibility with the SLMM proxy pattern.
"""
# force=True PRESERVES today's behaviour: the old call omitted `force`, so it
# received FastAPI's Query(False) object, which is truthy -- /device/connect
# has always bypassed the cache. Passing False here would quietly change that.
return device_info(port=port, baud=baud, host=host, tcp_port=tcp_port,
force=True, serial=serial)
return device_info(port=port, baud=baud, host=host, tcp_port=tcp_port)
@app.get("/device/events")
def device_events(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
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})"),
debug: bool = Query(False, description="Include raw record hex for field-layout inspection"),
force: bool = Query(False, description="Bypass cache and re-download all events from device"),
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
) -> dict:
"""
**With `serial`** (UM... or BE.../BA...): the unit's events in the shared
shape for either series, read from headers only -- no event is downloaded
to list it -- and not cached. Each carries an `event_id` for
POST /device/events/download. Without `serial`, the legacy Series-3
behaviour below.
Connect to the device, read the event index, and download all stored
events (event headers + full waveform records with peak values).
@@ -646,10 +502,6 @@ def device_events(
If new events exist on the device, only the new ones are downloaded and merged.
Pass *force=true* to bypass the cache entirely and re-download everything.
"""
if serial:
return _via_device_access(
lambda: _device_access().list_events(_unit_address(port, baud, host, tcp_port), serial))
baud = 38400 if baud is None else baud
log.info("GET /device/events port=%s host=%s debug=%s force=%s", port, host, debug, force)
cache = get_cache()
@@ -1051,7 +903,28 @@ def device_event_blastware_file(
if serial != "UNKNOWN" and ev._waveform_key is not None:
try:
cc = info.compliance_config
backfill_series3_event(ev, cc)
# Backfill authoritative compliance-config values onto the
# Event before persisting. These supersede whatever
# _decode_a5_waveform read from the STRT bytes (some of which
# have ambiguous semantics — e.g. STRT[20] is rectime but
# STRT[8:10] / STRT[16:18] are device-specific scratch fields
# that aren't reliable sample/pretrig counts).
if cc:
if ev.sample_rate is None and cc.sample_rate:
ev.sample_rate = cc.sample_rate
if cc.record_time:
# record_time from compliance is authoritative — the
# user-set value the device followed when recording.
ev.rectime_seconds = cc.record_time
# Derive total_samples from sample_rate × rectime when
# we can; the STRT-derived value can land at a buffer-
# offset rather than a sample count.
if ev.sample_rate and ev.rectime_seconds:
derived = int(round(ev.sample_rate * ev.rectime_seconds))
if (ev.total_samples is None
or ev.total_samples > derived * 2
or ev.total_samples < derived // 4):
ev.total_samples = derived
geo_range = getattr(cc, "geo_range", None) if cc else None
rec = _get_store().save(
ev, serial=serial, a5_frames=a5_frames,
@@ -1133,7 +1006,6 @@ def device_config(
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
@@ -1172,8 +1044,7 @@ def device_config(
try:
def _do():
with _build_client(port, baud, host, tcp_port) as client:
info = client.connect()
_require_series3(info.serial, serial)
client.connect()
client.apply_config(
recording_mode=body.recording_mode,
sample_rate=body.sample_rate,
@@ -1218,10 +1089,9 @@ def device_config_project(
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:
"""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)
return device_config(body=body, port=port, baud=baud, host=host, tcp_port=tcp_port)
# ── Monitoring endpoints ───────────────────────────────────────────────────────
@@ -1229,13 +1099,10 @@ def device_config_project(
@app.get("/device/monitor/status")
def device_monitor_status(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),
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})"),
force: bool = Query(False, description="Bypass cache and re-read from device"),
serial: Optional[str] = Query(None, description=_SERIAL_DOC),
run_state: bool = Query(False, description="With a UM serial: also read SUB 0x49 "
"(one more round trip) and return its raw code in detail.run_state"),
) -> dict:
"""
Read monitoring status from the device.
@@ -1251,11 +1118,6 @@ def device_monitor_status(
**Caching**: status is cached for 30 seconds to reduce cellular polling overhead.
Pass *force=true* to bypass the cache for an immediate fresh read.
"""
if serial:
return _via_device_access(
lambda: _device_access().status(_unit_address(port, baud, host, tcp_port), serial,
run_state=run_state))
baud = 38400 if baud is None else baud
cache = get_cache()
conn_key = SFMCache.make_conn_key(host, tcp_port, port, baud)
@@ -1298,64 +1160,6 @@ def device_monitor_status(
return result
@app.get("/device/settings")
def device_settings(
serial: str = Query(..., description=_SERIAL_DOC),
port: Optional[str] = Query(None, description="Serial port (e.g. /dev/ttyACM0)"),
baud: Optional[int] = Query(None, description="Serial baud (default by series)"),
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})"),
) -> dict:
"""The unit's recording settings, in the shared shape for either series."""
return _via_device_access(
lambda: _device_access().settings(_unit_address(port, baud, host, tcp_port), serial))
@app.post("/device/events/download")
def device_events_download(
serial: str = Query(..., description=_SERIAL_DOC),
event_id: str = Query(..., description="From GET /device/events?serial=..."),
port: Optional[str] = Query(None, description="Serial port (e.g. /dev/ttyACM0)"),
baud: Optional[int] = Query(None, description="Serial baud (default by series)"),
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})"),
) -> dict:
"""Download one event, check it, and store it in SFM's database.
Read-only on the unit. The stored file and waveform are then at
/db/events/{db_event_id}/... . An event already stored -- by an earlier
download, or by THOR's watcher -- comes back as its existing row and
nothing is written (`inserted: false`, `detail.already_stored: true`).
The unit is busy for the whole download: other requests for it wait,
then get 423.
"""
try:
dl = _device_access().download_event(_unit_address(port, baud, host, tcp_port), serial, event_id)
except DeviceError as exc:
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
try:
out = persist_download(dl, store=_get_store(), db=_get_db())
except Exception as exc:
log.error("events/download: %s downloaded but not stored: %s", dl.event_id, exc, exc_info=True)
raise HTTPException(
status_code=500,
detail=f"downloaded {dl.filename} from the unit but could not store it: {exc}") from exc
return dataclasses.asdict(out)
@app.post("/device/hangup")
def device_hangup(
port: Optional[str] = Query(None, description="Serial port"),
baud: Optional[int] = Query(None, description="Serial baud"),
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})"),
) -> dict:
"""Hang up a held line now instead of waiting for the idle timeout.
`hung_up` is false if nothing was being held."""
return _via_device_access(
lambda: {"hung_up": _device_access().hang_up(_unit_address(port, baud, host, tcp_port))})
@app.get("/device/events/storage_range")
def device_events_storage_range(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
@@ -1458,7 +1262,6 @@ def device_events_erase(
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:
"""
Erase ALL stored events from the device memory.
@@ -1478,8 +1281,7 @@ def device_events_erase(
try:
def _do():
with _build_client(port, baud, host, tcp_port) as client:
info = client.connect()
_require_series3(info.serial, serial)
client.connect()
client.delete_all_events()
_run_with_retry(_do, is_tcp=_is_tcp(host))
except HTTPException:
@@ -1528,7 +1330,6 @@ def device_stop_monitoring_blind(
Returns the number of bytes sent. A 503 means the TCP connect failed
(device busy in another session — caller should retry).
"""
# Not identity-checked (phase 1c): it sends only 0x97/0x96, which mean the same on both series (measured 2026-10-25/27), and it must reach a unit too wedged to answer.
log.info(
"POST /device/stop_monitoring_blind host=%s tcp_port=%s connect_timeout=%.1fs repeat=%d",
host, tcp_port, connect_timeout, repeat,
@@ -1601,7 +1402,6 @@ def device_stop_monitoring_slow_drip(
Compared to spam mode: ~40× fewer bytes/sec on the wire, but each
byte has a much higher chance of actually being parsed.
"""
# Not identity-checked (phase 1c): it sends only 0x97/0x96, which mean the same on both series (measured 2026-10-25/27), and it must reach a unit too wedged to answer.
log.info(
"POST /device/stop_monitoring_slow_drip host=%s tcp_port=%s duration=%.1fs interval=%.2fs connect_timeout=%.1fs",
host, tcp_port, duration_s, interval_s, connect_timeout,
@@ -1731,7 +1531,6 @@ def device_stop_monitoring_spam(
when it finishes. No streaming; if you want live progress, watch
SFM logs.
"""
# Not identity-checked (phase 1c): it sends only 0x97/0x96, which mean the same on both series (measured 2026-10-25/27), and it must reach a unit too wedged to answer.
log.info(
"POST /device/stop_monitoring_spam host=%s tcp_port=%s duration=%.1fs connect_timeout=%.3fs repeat=%d",
host, tcp_port, duration_s, connect_timeout, repeat,
@@ -1803,7 +1602,6 @@ def device_rescue(
recv_timeout: float = Query(5.0, description="Per-frame S3 recv timeout in seconds (default 5)"),
disable_ach: bool = Query(True, description="Disable Auto Call Home on the device before erasing"),
erase: bool = Query(True, description="Erase all stored events after disabling ACH"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""
Rescue an uncooperative unit by squeezing all maintenance work into a
@@ -1854,11 +1652,6 @@ def device_rescue(
client.poll()
steps.append({"step": "poll", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
if disable_ach or erase:
# One SUB 0x15 read: this route writes call-home and erases.
_require_series3(client.read_serial(), serial)
steps.append({"step": "identify", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
if disable_ach:
client.set_call_home_config(auto_call_home_enabled=False)
steps.append({"step": "disable_ach", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
@@ -1867,8 +1660,6 @@ def device_rescue(
client.delete_all_events()
steps.append({"step": "erase", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
except HTTPException:
raise
except ProtocolError as exc:
steps.append({"step": "error", "ok": False, "detail": f"protocol: {exc}"})
raise HTTPException(status_code=502, detail={"message": f"Protocol error: {exc}", "steps": steps}) from exc
@@ -1895,56 +1686,16 @@ def device_rescue(
@app.post("/device/monitor/start")
def device_monitor_start(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
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_DOC),
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
even_if_already: bool = Query(False, description="Send even if the unit is already in the target state"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
) -> dict:
"""
Command the device to start monitoring (recording triggered events).
Sends SUB 0x96 and waits for ack SUB 0x69.
With `serial`: the unit's identity is read first (a different unit is a 409,
nothing sent), then its state; `dry_run` returns the planned frames and sends
nothing; a live change is audited (`GET /db/device_commands`), verified by
reading the state back, and never retried. `even_if_already` sends even
when the unit is already in the target state.
Statuses with `serial`:
200 the ChangeResult: a dry run, a skip (already in the state), or a send
read back as made
409 ChangeResult: sent and acknowledged, but the unit never reached the
state (`verified: mismatch`, every state seen kept); or, as an
error, a different unit answered or its state was never measured
(nothing sent either way)
502 ChangeResult: the ack was lost but the unit could be read afterwards
422 a malformed serial or address; 423 the unit is busy;
501 no audit log is configured (nothing sent)
503 the unit is calling home, or a call-home was already waiting before
sending (nothing sent); or the audit log could not be written
(nothing sent)
500 the audit row could not be finished -- the detail says first what
happened to the unit (sent and verified, nothing sent, ...)
504 / 502 / 503 a link failure before anything was sent
A failure AFTER the frame went out (or may have) -- the read-back failed,
the ack was lost and the unit could not be read, or a call-home began --
takes the status its cause would have had (503 for a call-home, 504 for
silence, 502 for a bad reply, 503 for a lost connection), and its detail
says the frame was sent and names the audit record.
Without `serial`: the legacy behaviour above, unchanged.
"""
if serial:
return _change_response(lambda: _device_access().start_monitoring(
_unit_address(port, baud, host, tcp_port), serial, dry_run=dry_run,
even_if_already=even_if_already, caller=caller or "api"))
baud = 38400 if baud is None else baud
conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud)
# Legacy branch, not identity-checked: 0x96/0x97 mean the same on both series (measured).
with _build_client(port=port, baud=baud, host=host, tcp_port=tcp_port) as client:
try:
client.poll()
@@ -1961,56 +1712,16 @@ def device_monitor_start(
@app.post("/device/monitor/stop")
def device_monitor_stop(
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
baud: Optional[int] = Query(None, description="Serial baud rate"),
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_DOC),
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
even_if_already: bool = Query(False, description="Send even if the unit is already in the target state"),
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
):
) -> dict:
"""
Command the device to stop monitoring.
Sends SUB 0x97 and waits for ack SUB 0x68.
With `serial`: the unit's identity is read first (a different unit is a 409,
nothing sent), then its state; `dry_run` returns the planned frames and sends
nothing; a live change is audited (`GET /db/device_commands`), verified by
reading the state back, and never retried. `even_if_already` sends even
when the unit is already in the target state.
Statuses with `serial`:
200 the ChangeResult: a dry run, a skip (already in the state), or a send
read back as made
409 ChangeResult: sent and acknowledged, but the unit never reached the
state (`verified: mismatch`, every state seen kept); or, as an
error, a different unit answered or its state was never measured
(nothing sent either way)
502 ChangeResult: the ack was lost but the unit could be read afterwards
422 a malformed serial or address; 423 the unit is busy;
501 no audit log is configured (nothing sent)
503 the unit is calling home, or a call-home was already waiting before
sending (nothing sent); or the audit log could not be written
(nothing sent)
500 the audit row could not be finished -- the detail says first what
happened to the unit (sent and verified, nothing sent, ...)
504 / 502 / 503 a link failure before anything was sent
A failure AFTER the frame went out (or may have) -- the read-back failed,
the ack was lost and the unit could not be read, or a call-home began --
takes the status its cause would have had (503 for a call-home, 504 for
silence, 502 for a bad reply, 503 for a lost connection), and its detail
says the frame was sent and names the audit record.
Without `serial`: the legacy behaviour above, unchanged.
"""
if serial:
return _change_response(lambda: _device_access().stop_monitoring(
_unit_address(port, baud, host, tcp_port), serial, dry_run=dry_run,
even_if_already=even_if_already, caller=caller or "api"))
baud = 38400 if baud is None else baud
conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud)
# Legacy branch, not identity-checked: 0x96/0x97 mean the same on both series (measured).
with _build_client(port=port, baud=baud, host=host, tcp_port=tcp_port) as client:
try:
client.poll()
@@ -2113,7 +1824,6 @@ def device_call_home_set(
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 call home config, apply supplied changes, and write back.
@@ -2137,7 +1847,6 @@ def device_call_home_set(
def _do():
with _build_client(port, baud, host, tcp_port) as client:
client.poll()
_require_series3(client.read_serial(), serial) # one SUB 0x15 read
client.set_call_home_config(
auto_call_home_enabled=body.auto_call_home_enabled,
after_event_recorded=body.after_event_recorded,
@@ -3219,22 +2928,6 @@ def db_sessions(
return {"count": len(rows), "sessions": rows}
@app.get("/db/device_commands")
def db_device_commands(
serial: Optional[str] = Query(None, description="Filter by unit serial"),
limit: int = Query(100, ge=1, le=1000, description="Max rows to return"),
) -> dict:
"""
The audit trail of changes SFM attempted on units, newest first.
Each row's `sent` says whether a frame went out (1 acknowledged, 0 nothing
sent, null unknown) and `states` holds every state read (before / seen /
after). `serial` is matched case-insensitively.
"""
serial = normalise_serial(serial) if serial else None
return {"commands": _get_db().query_device_commands(serial or None, limit)}
# ── Entry point ────────────────────────────────────────────────────────────────
if __name__ == "__main__":
+92 -491
View File
@@ -147,15 +147,6 @@
}
#monitor-panel.monitoring { border-left: 3px solid var(--green); }
#monitor-panel.idle { border-left: 3px solid var(--text-mute); }
.series-badge {
font-size: 12px;
font-weight: 700;
padding: 2px 10px;
border-radius: 10px;
border: 1px solid var(--accent, #58a6ff);
color: var(--accent, #58a6ff);
align-self: center;
}
.mon-status-badge {
font-size: 12px;
font-weight: 700;
@@ -852,13 +843,7 @@
<input type="text" id="dev-host" placeholder="e.g. 63.43.212.232" />
<label class="hdr">Port</label>
<input type="number" id="dev-port" value="9034" />
<label class="hdr">Serial</label>
<input type="text" id="dev-serial" placeholder="BE…/BA… or UM… (optional)"
title="With a serial, SFM talks to the unit through the serial-based endpoints (both series)" />
<button class="btn" id="connect-btn" onclick="connectUnit()">Connect</button>
<span class="series-badge" id="series-badge" hidden></span>
<button class="btn" id="hangup-btn" onclick="hangUp()" hidden
title="Release the line SFM holds open to this Micromate">Hang up</button>
</div>
<!-- ── Device info bar ─────────────────────────────────────────────── -->
@@ -916,14 +901,6 @@
<span class="mon-label">Memory free</span>
<span class="mon-value" id="mon-mem-free">—</span>
</div>
<div class="mon-field" style="display:none" title="The unit's own clock">
<span class="mon-label">Unit time</span>
<span class="mon-value" id="mon-time">—</span>
</div>
<div class="mon-field" style="display:none" title="Read only where it is cheap (Series 4)">
<span class="mon-label">Events</span>
<span class="mon-value" id="mon-events">—</span>
</div>
<div class="mon-spacer"></div>
<button class="btn" id="mon-refresh-btn" onclick="refreshMonitorStatus()" title="Refresh monitoring status">↻ Status</button>
<button class="btn" id="mon-start-btn" onclick="startMonitoring()" title="Start monitoring">▶ Start</button>
@@ -995,12 +972,6 @@
</div>
<div id="waveform-area" style="flex:1; overflow-y:auto;">
<div class="db-table-wrap" id="serial-events-wrap" style="display:none; margin:12px;">
<table class="db-table">
<thead><tr><th>#</th><th>Time</th><th>Type</th><th>PVS</th><th>Tran</th><th>Vert</th><th>Long</th><th></th></tr></thead>
<tbody id="serial-events-tbody"></tbody>
</table>
</div>
<div id="empty-state">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
@@ -1016,12 +987,7 @@
═══════════════════════════════════════════════════════════════════ -->
<div id="tab-config" class="tab-pane">
<div id="cfg-settings" style="display:none; margin-bottom:12px">
<div class="cfg-section-title">On the unit (read by serial)</div>
<div class="dev-table" id="cfg-settings-table"></div>
</div>
<div class="cfg-grid" id="cfg-form">
<div class="cfg-grid">
<!-- Recording parameters -->
<div class="cfg-section">
@@ -1246,7 +1212,6 @@
<button class="btn btn-success" id="ch-write-btn" onclick="writeCallHome()" disabled>Write to Device</button>
<button class="btn btn-ghost" onclick="clearCallHomeForm()">Clear Form</button>
<span id="ch-status"></span>
<span id="ch-series-note" style="color:var(--text-dim)"></span>
</div>
</div><!-- end #tab-call-home -->
@@ -1473,173 +1438,13 @@
<!-- ── Script ─────────────────────────────────────────────────────── -->
<script>
/* <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],
config_write: ['POST', '/device/config', false],
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,
callHomeRead: series === 3,
configWrite: false,
callHomeWrite: false,
reasons: { configWrite: 'Coming in phase 5 (#46)', callHomeWrite: 'Coming in phase 4' },
};
}
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.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}`;
}
/* </device-routing> */
</script>
<script>
'use strict';
// ── State ──────────────────────────────────────────────────────────────────────
let unitInfo = null;
let eventList = [];
let storageInfo = null; // /device/events/storage_range — cheap, read on connect
let eventsLoaded = false;
let eventsBySerial = false; // the list came from the serial-based /device/events (EventRef shape) // the event chain walk is opt-in; see loadEventList()
let eventsLoaded = false; // the event chain walk is opt-in; see loadEventList()
let currentEvent = 0;
let charts = {};
let geoAdcScale = 6.206;
@@ -1683,68 +1488,9 @@ function onForceToggle() {
document.getElementById('force-toggle').classList.toggle('active', forceRefresh);
}
// The unit as named in the bar. `confirmed` is the unit's own /device/info
// answer ({serial, series}); it is cleared whenever the serial, host or port is
// edited, so a series-specific control never outlives the identify behind it.
let unitConfirmed = null;
function currentUnit() {
return { serial: document.getElementById('dev-serial').value,
host: devHost(), tcpPort: devPort(), confirmed: unitConfirmed };
}
function serialMode() { return Boolean(normSerial(currentUnit().serial)); }
// Every device request goes through deviceUrl (the device-routing block).
async function deviceRequest(action, params = {}, opts = {}) {
const extra = forceRefresh && (DEVICE_ROUTES[action] || [])[0] === 'GET' ? { ...params, force: 'true' } : params;
const u = deviceUrl(action, currentUnit(), extra);
if (!u) throw new Error(`${action} needs a serial`);
return fetch(`${api()}${u.path}`, { method: u.method, ...opts });
}
async function deviceFetch(action, params = {}, opts = {}) {
const r = await deviceRequest(action, params, opts);
const body = await r.json().catch(() => ({}));
if (!r.ok) {
const d = body.detail;
const err = new Error(body.outcome ? changeSummary(body)
: typeof d === 'string' ? d : d ? (d.message || JSON.stringify(d)) : r.statusText);
err.status = r.status; err.body = body;
throw err;
}
return body;
}
// Every series-specific control, from controlsFor (the device-routing block).
function applyControls() {
const unit = currentUnit();
const c = controlsFor(unit);
const series = confirmedSeries(unit);
const badge = document.getElementById('series-badge');
badge.hidden = series == null;
badge.textContent = series ? `Series ${series}` : '';
document.getElementById('hangup-btn').hidden = !c.hangup;
setDiagButtonsEnabled(c.diagnostics);
const cw = document.getElementById('cfg-write-btn');
cw.disabled = !c.configWrite; cw.title = c.reasons.configWrite;
const hw = document.getElementById('ch-write-btn');
hw.disabled = !c.callHomeWrite; hw.title = c.reasons.callHomeWrite;
const chr = document.getElementById('ch-read-btn');
chr.disabled = !c.callHomeRead;
const s4 = series === 4 ? 'Not yet available for Series 4' : '';
chr.title = s4;
document.getElementById('ch-series-note').textContent = s4;
setMonitorButtons();
}
async function hangUp() {
try {
const r = await deviceFetch('hangup');
setStatus(r.hung_up ? 'Line released.' : 'No line was being held.', 'ok');
} catch (e) {
setStatus(`Hang up failed: ${e.message}`, 'error');
}
function deviceParams() {
const base = `host=${encodeURIComponent(devHost())}&tcp_port=${devPort()}`;
return forceRefresh ? `${base}&force=true` : base;
}
// ── Section switching ─────────────────────────────────────────────────────────
@@ -1802,9 +1548,6 @@ function switchTab(name) {
// ── Connect ────────────────────────────────────────────────────────────────────
async function connectUnit() {
if (!devHost()) { setStatus('Enter a device host first.', 'error'); return; }
// Whatever answered last time no longer counts: only this identify confirms.
unitConfirmed = null;
applyControls();
const btn = document.getElementById('connect-btn');
btn.disabled = true;
@@ -1812,15 +1555,13 @@ async function connectUnit() {
setStatus('Connecting — reading device info…', 'loading');
try {
unitInfo = await deviceFetch('info');
const r = await fetch(`${api()}/device/info?${deviceParams()}`);
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
unitInfo = await r.json();
} catch (e) {
setStatus(`Connection failed: ${e.message}`, 'error');
btn.disabled = false; btn.textContent = 'Connect'; return;
}
// The unit's own answer confirms its series; a legacy identify (no serial
// typed) answers with its serial alone.
unitConfirmed = { serial: unitInfo.serial,
series: unitInfo.series ?? seriesFromSerial(unitInfo.serial) };
// Connecting deliberately does NOT walk the event chain. That walk reads
// every event header over the cellular link and can take minutes — or fail
@@ -1828,9 +1569,7 @@ async function connectUnit() {
// probes instead; the event list is opt-in via loadEventList().
eventList = []; eventsLoaded = false;
setStatus('Reading device state…', 'loading');
// A legacy MiniMate read: skipped in serial mode (one connection fewer, and a
// Micromate has no such route).
storageInfo = serialMode() ? null : await deviceFetch('storage_range').catch(() => null);
storageInfo = await fetchJson(`/device/events/storage_range`).catch(() => null);
populateDeviceBar();
populateDeviceTab();
@@ -1841,8 +1580,11 @@ async function connectUnit() {
document.getElementById('monitor-panel').style.display = 'flex';
setEventButtonsEnabled();
document.getElementById('load-events-btn').disabled = false;
setDiagButtonsEnabled(true);
document.getElementById('cfg-read-btn').disabled = false;
applyControls();
document.getElementById('cfg-write-btn').disabled = false;
document.getElementById('ch-read-btn').disabled = false;
document.getElementById('ch-write-btn').disabled = false;
btn.disabled = false; btn.textContent = 'Reconnect';
@@ -1861,21 +1603,21 @@ async function connectUnit() {
}
// ── Shared fetch helper ────────────────────────────────────────────────────────
async function fetchJson(path, opts) {
const sep = path.includes('?') ? '&' : '?';
const r = await fetch(`${api()}${path}${sep}${deviceParams()}`, opts);
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.detail || r.statusText);
return body;
}
function setEventButtonsEnabled() {
const n = eventList.length;
// A list loaded by serial is downloaded row by row (by event_id); these
// per-index buttons belong to the legacy list.
const bySerial = eventsBySerial;
const live = perIndexLive({ bySerial, count: n });
for (const id of ['load-btn', 'save-btn', 'download-btn']) {
const el = document.getElementById(id);
if (el.dataset.legacyTitle === undefined) el.dataset.legacyTitle = el.title;
el.disabled = !live;
el.title = bySerial ? 'For a list loaded without a serial — use a row\'s Download' : el.dataset.legacyTitle;
}
document.getElementById('load-btn').disabled = n === 0;
document.getElementById('save-btn').disabled = n === 0;
document.getElementById('download-btn').disabled = n === 0;
document.getElementById('prev-btn').disabled = true;
document.getElementById('next-btn').disabled = !live || n <= 1;
document.getElementById('next-btn').disabled = n <= 1;
}
// ── Event list (opt-in — this is the slow chain walk) ──────────────────────────
@@ -1883,12 +1625,11 @@ async function loadEventList() {
if (!devHost()) { setStatus('Connect to a device first.', 'error'); return; }
const btn = document.getElementById('load-events-btn');
btn.disabled = true;
setStatus(serialMode() ? 'Listing events…' : 'Walking the event chain — this can take a while…', 'loading');
setStatus('Walking the event chain — this can take a while…', 'loading');
try {
const evData = await deviceFetch('events');
const evData = await fetchJson('/device/events');
eventList = evData.events || [];
eventsLoaded = true;
eventsBySerial = serialMode();
// /device/events re-reads compliance; fold it in.
if (evData.device) unitInfo = { ...unitInfo, ...evData.device };
} catch (e) {
@@ -1906,7 +1647,7 @@ async function loadEventList() {
// ── Device bar ─────────────────────────────────────────────────────────────────
function populateDeviceBar() {
qs('di-serial').textContent = unitInfo.serial || '—';
qs('di-fw').textContent = unitInfo.firmware_version || unitInfo.firmware || '—';
qs('di-fw').textContent = unitInfo.firmware_version || '—';
const cc = unitInfo.compliance_config || {};
qs('di-sr').textContent = cc.sample_rate ? `${cc.sample_rate} sps` : '—';
qs('di-rt').textContent = cc.record_time != null ? `${cc.record_time.toFixed(1)} s` : '—';
@@ -1922,7 +1663,9 @@ function populateDeviceBar() {
async function refreshMonitorStatus() {
if (!devHost()) return null;
try {
const s = await deviceFetch('status');
const r = await fetch(`${api()}/device/monitor/status?${deviceParams()}`);
if (!r.ok) return null;
const s = await r.json();
updateMonitorPanel(s);
return s;
} catch (_) { return null; }
@@ -1934,58 +1677,37 @@ function updateMonitorPanel(s) {
const batEl = document.getElementById('mon-battery');
const memTEl = document.getElementById('mon-mem-total');
const memFEl = document.getElementById('mon-mem-free');
// Two shapes: the shared model (serial mode) and the legacy one.
const monitoring = s.monitoring ?? s.is_monitoring;
lastMonitoring = monitoring;
if (monitoring) {
const startB = document.getElementById('mon-start-btn');
const stopB = document.getElementById('mon-stop-btn');
if (s.is_monitoring) {
badge.textContent = 'MONITORING';
badge.className = 'mon-status-badge monitoring';
panel.className = 'monitoring';
startB.disabled = true;
stopB.disabled = false;
} else {
badge.textContent = 'IDLE';
badge.className = 'mon-status-badge idle';
panel.className = 'idle';
startB.disabled = false;
stopB.disabled = true;
}
setMonitorButtons();
// Battery and memory are available in both states — update if present,
// keep previous value if this was an optimistic update with no real data.
const volts = s.battery_volts ?? s.battery_v;
const kb = (bytes, k) => bytes != null ? Math.round(bytes / 1024) : k;
const totalKb = kb(s.memory_total_bytes, s.memory_total_kb);
const freeKb = kb(s.memory_free_bytes, s.memory_free_kb);
// The unit's clock and event count come only in the shared shape (serial
// mode); Series 3 reports both as null.
const shared = 'monitoring' in s;
for (const [id, v] of [['mon-time', s.device_time ? s.device_time.replace('T', ' ') : '—'],
['mon-events', s.event_count ?? '—']]) {
const el = document.getElementById(id);
if (shared) el.textContent = v;
el.parentElement.style.display = shared ? '' : 'none';
}
if (volts != null) batEl.textContent = `${volts.toFixed(2)} V`;
if (totalKb != null) memTEl.textContent = `${totalKb} KB`;
if (freeKb != null) memFEl.textContent = `${freeKb} KB`;
}
// Start/stop: in serial mode only for a unit whose series its own answer
// confirmed; without a serial, as before (0x96/0x97 mean the same on both).
let lastMonitoring = null;
let changeInFlight = false; // one start/stop at a time: a double click must not send twice
function setMonitorButtons() {
const allowed = !changeInFlight
&& (serialMode() ? controlsFor(currentUnit()).startStop : Boolean(devHost()));
document.getElementById('mon-start-btn').disabled = !allowed || lastMonitoring === true;
document.getElementById('mon-stop-btn').disabled = !allowed || lastMonitoring === false;
if (s.battery_v != null) batEl.textContent = `${s.battery_v.toFixed(2)} V`;
if (s.memory_total_kb != null) memTEl.textContent = `${s.memory_total_kb} KB`;
if (s.memory_free_kb != null) memFEl.textContent = `${s.memory_free_kb} KB`;
}
async function startMonitoring() {
if (!devHost()) return;
if (serialMode()) { await changeMonitoring('start'); return; }
const btn = document.getElementById('mon-start-btn');
btn.disabled = true; btn.textContent = '…';
setStatus('Starting monitoring…', 'loading');
try {
await deviceFetch('start');
const r = await fetch(`${api()}/device/monitor/start?${deviceParams()}`, { method: 'POST' });
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
// Optimistically show MONITORING immediately. The unit may run a ~40s on-device
// sensor check before fully entering monitor mode. We poll status every 5s for
@@ -2031,12 +1753,12 @@ async function _pollMonitorConfirm(attempt) {
async function stopMonitoring() {
if (!devHost()) return;
if (serialMode()) { await changeMonitoring('stop'); return; }
const btn = document.getElementById('mon-stop-btn');
btn.disabled = true; btn.textContent = '…';
setStatus('Stopping monitoring…', 'loading');
try {
await deviceFetch('stop');
const r = await fetch(`${api()}/device/monitor/stop?${deviceParams()}`, { method: 'POST' });
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
setStatus('Monitoring stopped.', 'ok');
await refreshMonitorStatus();
} catch (e) {
@@ -2046,37 +1768,6 @@ async function stopMonitoring() {
btn.textContent = '■ Stop';
}
// Serial mode: SFM's audited change -- identity and state read first, one send,
// never retried, then read back. The result body says what the unit did, on a
// 409/502 too; only the read that follows decides the panel.
async function changeMonitoring(action) {
const serial = normSerial(currentUnit().serial);
const verb = action === 'start' ? 'Start' : 'Stop';
if (!confirm(`${verb} monitoring on ${serial}?`)) return;
const btn = document.getElementById(action === 'start' ? 'mon-start-btn' : 'mon-stop-btn');
const label = btn.textContent;
changeInFlight = true; setMonitorButtons(); btn.textContent = '…';
setStatus(action === 'start' ? 'Starting — the unit runs its sensor check first (about 35 s)'
: 'Stopping…', 'loading');
try {
const r = await deviceRequest(action);
const body = await r.json().catch(() => ({}));
if (body.outcome) {
setStatus(changeSummary(body), r.ok ? 'ok' : 'error');
} else {
const d = body.detail;
setStatus(`${verb} monitoring failed: ${typeof d === 'string' ? d : d ? JSON.stringify(d) : r.statusText}`, 'error');
}
} catch (e) {
// No reply is not "nothing sent": the request may have reached the unit.
setStatus(`${verb} monitoring: no reply from SFM (${e.message}) — it may have been sent; `
+ `check the unit's state and GET /db/device_commands`, 'error');
}
changeInFlight = false; btn.textContent = label;
await refreshMonitorStatus();
setMonitorButtons();
}
// ── Device tab ─────────────────────────────────────────────────────────────────
function populateDeviceTab() {
document.getElementById('no-device-msg').style.display = 'none';
@@ -2087,21 +1778,17 @@ function populateDeviceTab() {
cards.innerHTML = '';
const cardData = [
{ label:'Serial Number', value: unitInfo.serial || '—' },
{ label:'Series', value: confirmedSeries(currentUnit()) ?? '—' },
{ label:'Firmware', value: unitInfo.firmware_version || unitInfo.firmware || '—' },
{ label:'DSP', value: unitInfo.dsp_version || (unitInfo.detail || {}).dsp_version || '—' },
{ label:'Firmware', value: unitInfo.firmware_version || '—' },
{ label:'DSP', value: unitInfo.dsp_version || '—' },
{ label:'Model', value: unitInfo.model || '—' },
{ label:'Manufacturer', value: unitInfo.manufacturer || (unitInfo.detail || {}).manufacturer || '—' },
{ label:'Active Setup', value: unitInfo.active_setup || '—' },
{ label:'Manufacturer', value: unitInfo.manufacturer || '—' },
{ label:'Stored Events', value: eventsLoaded ? eventList.length : 'not loaded' },
{ label:'Storage Used', value: storageUsedLabel() },
];
for (const {label, value} of cardData) {
const c = document.createElement('div');
c.className = 'dev-card';
const l = document.createElement('div'); l.className = 'dev-card-label'; l.textContent = label;
const v = document.createElement('div'); v.className = 'dev-card-value'; v.textContent = value;
c.append(l, v);
c.innerHTML = `<div class="dev-card-label">${label}</div><div class="dev-card-value">${value}</div>`;
cards.appendChild(c);
}
@@ -2119,7 +1806,7 @@ function populateDeviceTab() {
['ADC Scale Factor (geo)', cc.geo_adc_scale != null ? `${cc.geo_adc_scale.toFixed(4)} in/s` : '—'],
['Setup Name', cc.setup_name || '—'],
];
renderTextTable('compliance-table', complianceRows);
renderTable('compliance-table', complianceRows);
// Project table
const projectRows = [
@@ -2129,20 +1816,7 @@ function populateDeviceTab() {
['Sensor Location', cc.sensor_location || '—'],
['Notes', cc.notes || '—'],
];
renderTextTable('project-table', projectRows);
}
function renderTextTable(id, rows) {
const el = document.getElementById(id);
el.innerHTML = '';
for (const [label, value] of rows) {
const row = document.createElement('div');
row.className = 'dev-table-row';
const l = document.createElement('div'); l.className = 'dtr-label'; l.textContent = label;
const v = document.createElement('div'); v.className = 'dtr-value'; v.textContent = value;
row.append(l, v);
el.appendChild(row);
}
renderTable('project-table', projectRows);
}
function renderTable(id, rows) {
@@ -2182,8 +1856,7 @@ function diagCheckEraseConfirm() {
const btn = document.getElementById('diag-erase-btn');
if (!box || !btn) return;
const serial = (unitInfo && unitInfo.serial) || '';
btn.disabled = !serial || box.value.trim().toUpperCase() !== serial.toUpperCase()
|| !controlsFor(currentUnit()).diagnostics;
btn.disabled = !serial || box.value.trim().toUpperCase() !== serial.toUpperCase();
}
function diagResult(id, text, cls) {
@@ -2196,28 +1869,23 @@ function diagResult(id, text, cls) {
async function refreshDiagnostics() {
if (!devHost()) return;
const st = document.getElementById('diag-status');
if (!controlsFor(currentUnit()).diagnostics) {
if (st) { st.textContent = 'Diagnostics are MiniMate tools: connect to a Series-3 unit first.'; st.className = ''; }
return;
}
if (st) { st.textContent = 'Reading…'; st.className = 'loading'; }
const [mon, store, idx] = await Promise.all([
deviceFetch('status', { force: 'true' }).catch(e => ({ _err: e.message })),
deviceFetch('storage_range').catch(e => ({ _err: e.message })),
deviceFetch('index').catch(e => ({ _err: e.message })),
fetchJson('/device/monitor/status?force=true').catch(e => ({ _err: e.message })),
fetchJson('/device/events/storage_range').catch(e => ({ _err: e.message })),
fetchJson('/device/events/index').catch(e => ({ _err: e.message })),
]);
if (!store._err) storageInfo = store;
const err = v => `<span style="color:var(--red)">${escapeHtml(v)}</span>`;
const err = v => `<span style="color:var(--red)">${v}</span>`;
const rows = [];
rows.push(['Monitoring', mon._err ? err(mon._err)
: ((mon.monitoring ?? mon.is_monitoring) ? '<b>MONITORING</b>' : 'idle')]);
: (mon.is_monitoring ? '<b>MONITORING</b>' : 'idle')]);
if (!mon._err) {
const volts = mon.battery_volts ?? mon.battery_v;
rows.push(['Battery', volts != null ? `${volts.toFixed(2)} V` : '—']);
rows.push(['Battery', mon.battery_v != null ? `${mon.battery_v.toFixed(2)} V` : '—']);
if (mon.memory_total_bytes) {
const used = mon.memory_total_bytes - (mon.memory_free_bytes ?? 0);
const pct = (used / mon.memory_total_bytes * 100).toFixed(1);
@@ -2242,8 +1910,8 @@ async function diagStopMonitoring() {
const btn = document.getElementById('diag-stop-btn');
btn.disabled = true; diagResult('diag-stop-result', 'Sending…');
try {
const r = await deviceFetch('stop');
diagResult('diag-stop-result', r.outcome ? changeSummary(r) : 'Stop acknowledged — recording halted.', 'ok');
await fetchJson('/device/monitor/stop', { method: 'POST' });
diagResult('diag-stop-result', 'Stop acknowledged — recording halted.', 'ok');
refreshDiagnostics();
} catch (e) {
diagResult('diag-stop-result', `Failed: ${e.message}`, 'error');
@@ -2255,7 +1923,7 @@ async function diagDisableAch() {
const btn = document.getElementById('diag-ach-btn');
btn.disabled = true; diagResult('diag-ach-result', 'Writing call-home config…');
try {
const r = await deviceFetch('rescue', { erase: 'false' });
const r = await fetchJson('/device/rescue?erase=false', { method: 'POST' });
const steps = (r.steps || []).map(s => s.step).join(' → ') || 'done';
diagResult('diag-ach-result', `ACH disabled (${steps}). Events untouched.`, 'ok');
} catch (e) {
@@ -2270,7 +1938,7 @@ async function diagEraseEvents() {
const btn = document.getElementById('diag-erase-btn');
btn.disabled = true; diagResult('diag-erase-result', 'Erasing…');
try {
await deviceFetch('erase');
await fetchJson('/device/events/erase', { method: 'POST' });
diagResult('diag-erase-result', 'Events erased — chain reset to 0x01110000.', 'ok');
document.getElementById('diag-erase-confirm').value = '';
eventList = []; eventsLoaded = false;
@@ -2287,7 +1955,8 @@ async function diagSlowDrip() {
btn.disabled = true;
diagResult('diag-drip-result', 'Holding a session for 120 s…');
try {
const r = await deviceFetch('slow_drip', { duration_s: 120, interval_s: 3 });
const r = await fetchJson('/device/stop_monitoring_slow_drip?duration_s=120&interval_s=3',
{ method: 'POST' });
const good = (r.bytes_received || 0) > 0;
diagResult('diag-drip-result',
`drips ${r.drips_sent} · held ${r.duration_s}s · bytes back ${r.bytes_received}` +
@@ -2304,7 +1973,7 @@ async function diagBlindStop() {
const btn = document.getElementById('diag-blind-btn');
btn.disabled = true; diagResult('diag-blind-result', 'Sending…');
try {
const r = await deviceFetch('blind_stop');
const r = await fetchJson('/device/stop_monitoring_blind', { method: 'POST' });
diagResult('diag-blind-result',
`Sent ${r.bytes_sent ?? '?'} bytes, no response read (fire-and-forget).`, 'ok');
} catch (e) {
@@ -2339,33 +2008,14 @@ function clearConfigForm() {
setCfgStatus('');
}
// Serial mode: the shared UnitSettings, read-only (writes wait for phase 5).
async function readSettingsBySerial() {
const btn = document.getElementById('cfg-read-btn');
btn.disabled = true;
setCfgStatus('Reading settings from the unit…');
try {
const st = await deviceFetch('settings');
renderTextTable('cfg-settings-table', settingsRows(st));
document.getElementById('cfg-settings').style.display = 'block';
document.getElementById('cfg-form').style.display = 'none';
setCfgStatus(`Settings read from ${st.serial}.`, 'ok');
} catch (e) {
setCfgStatus(`Read failed: ${e.message}`, 'error');
} finally {
btn.disabled = false;
}
}
async function readConfig() {
if (!devHost()) { setCfgStatus('Not connected.', 'error'); return; }
if (serialMode()) { await readSettingsBySerial(); return; }
document.getElementById('cfg-settings').style.display = 'none';
document.getElementById('cfg-form').style.display = '';
setCfgStatus('Reading config from device…');
document.getElementById('cfg-read-btn').disabled = true;
try {
unitInfo = await deviceFetch('info');
const r = await fetch(`${api()}/device/info?${deviceParams()}`);
if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); }
unitInfo = await r.json();
populateConfigFromDeviceInfo();
populateDeviceBar();
populateDeviceTab();
@@ -2417,10 +2067,13 @@ async function writeConfig() {
document.getElementById('cfg-write-btn').disabled = true;
try {
await deviceFetch('config_write', {}, {
const r = await fetch(`${api()}/device/config?${deviceParams()}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); }
const result = await r.json();
setCfgStatus(`Written: ${fieldsStr}`, 'ok');
// Re-read device info so Device tab and bar refresh
await readConfig();
@@ -2480,7 +2133,9 @@ async function readCallHome() {
setChStatus('Reading call home config from device…');
document.getElementById('ch-read-btn').disabled = true;
try {
const ch = await deviceFetch('call_home_read');
const r = await fetch(`${api()}/device/call_home?${deviceParams()}`);
if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); }
const ch = await r.json();
populateCallHomeForm(ch);
setChStatus('Call home config loaded from device.', 'ok');
} catch(e) {
@@ -2541,10 +2196,12 @@ async function writeCallHome() {
document.getElementById('ch-write-btn').disabled = true;
try {
await deviceFetch('call_home_write', {}, {
const r = await fetch(`${api()}/device/call_home?${deviceParams()}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); }
setChStatus(`Written: ${fieldsStr}`, 'ok');
// Re-read to confirm changes
await readCallHome();
@@ -2559,20 +2216,11 @@ async function writeCallHome() {
function populateEventChips() {
const el = document.getElementById('event-chips');
el.innerHTML = '';
const wrap = document.getElementById('serial-events-wrap');
wrap.style.display = eventsBySerial && eventList.length ? 'block' : 'none';
if (eventsBySerial) {
populateSerialEventTable();
document.getElementById('empty-state').style.display = eventList.length ? 'none' : 'flex';
updatePeaksBar(null);
return;
}
eventList.forEach((ev, i) => {
const chip = document.createElement('button');
chip.className = 'event-chip' + (i === 0 ? ' active' : '');
const view = eventView(ev);
chip.textContent = view.label;
chip.title = view.title;
chip.textContent = ev.timestamp?.display ?? `Event ${ev.index}`;
chip.title = ev.record_type || '';
chip.onclick = () => selectEvent(i);
el.appendChild(chip);
});
@@ -2581,34 +2229,7 @@ function populateEventChips() {
if (eventList.length > 0) updatePeaksBar(eventList[0]);
}
function populateSerialEventTable() {
const tbody = document.getElementById('serial-events-tbody');
tbody.innerHTML = '';
const ips = v => v != null ? v.toFixed(5) : '—';
eventList.forEach((ev, i) => {
const view = eventView(ev);
const pk = view.peaks || {};
const tr = document.createElement('tr');
for (const text of [ev.index, view.label, view.title || '—', ips(pk.pvs), ips(pk.tran), ips(pk.vert), ips(pk.long)]) {
const td = document.createElement('td');
td.textContent = text;
tr.appendChild(td);
}
const td = document.createElement('td');
const btn = document.createElement('button');
btn.className = 'btn btn-ghost';
btn.textContent = '⬇ Download';
btn.title = 'Download this event from the unit, check it and store it; then open it';
btn.onclick = () => downloadEventBySerial(i, btn);
td.appendChild(btn);
tr.appendChild(td);
tbody.appendChild(tr);
});
}
function selectEvent(idx) {
// The arrow keys reach here too: they obey the same rule as the buttons.
if (!perIndexLive({ bySerial: eventsBySerial, count: eventList.length })) return;
currentEvent = idx;
document.querySelectorAll('.event-chip').forEach((c, i) => c.classList.toggle('active', i === idx));
document.getElementById('prev-btn').disabled = idx <= 0;
@@ -2623,17 +2244,16 @@ function stepEvent(delta) {
}
function updatePeaksBar(ev) {
const pk = ev ? eventView(ev).peaks : null;
const pv = ev?.peak_values;
const bar = document.getElementById('peaks-bar');
if (!pk) { bar.classList.remove('visible'); return; }
if (!pv) { bar.classList.remove('visible'); return; }
bar.classList.add('visible');
const ips = v => v != null ? `${v.toFixed(5)} in/s` : '—';
qs('pk-tran').textContent = ips(pk.tran);
qs('pk-vert').textContent = ips(pk.vert);
qs('pk-long').textContent = ips(pk.long);
const micDbl = pk.micPsi != null && pk.micPsi > 0 ? 20 * Math.log10(pk.micPsi / DBL_REF) : null;
qs('pk-tran').textContent = pv.tran_in_s != null ? `${pv.tran_in_s.toFixed(5)} in/s` : '—';
qs('pk-vert').textContent = pv.vert_in_s != null ? `${pv.vert_in_s.toFixed(5)} in/s` : '—';
qs('pk-long').textContent = pv.long_in_s != null ? `${pv.long_in_s.toFixed(5)} in/s` : '—';
const micDbl = pv.micl_psi != null && pv.micl_psi > 0 ? 20 * Math.log10(pv.micl_psi / DBL_REF) : null;
qs('pk-mic').textContent = micDbl != null ? `${micDbl.toFixed(1)} dBL` : '—';
qs('pk-pvs').textContent = ips(pk.pvs);
qs('pk-pvs').textContent = pv.peak_vector_sum != null ? `${pv.peak_vector_sum.toFixed(5)} in/s` : '—';
}
async function loadWaveform() {
@@ -2644,7 +2264,9 @@ async function loadWaveform() {
let data;
try {
data = await deviceFetch('event_waveform', { index: idx });
const r = await fetch(`${api()}/device/event/${idx}/waveform?${deviceParams()}`);
if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); }
data = await r.json();
} catch(e) {
setStatus(`Waveform error: ${e.message}`, 'error');
document.getElementById('load-btn').disabled = false;
@@ -2675,7 +2297,7 @@ async function saveEventToDb() {
setStatus(`Downloading event #${idx} and saving to DB…`, 'loading');
try {
const r = await deviceRequest('event_file', { index: idx });
const r = await fetch(`${api()}/device/event/${idx}/blastware_file?${deviceParams()}`);
if (!r.ok) {
const e = await r.json().catch(() => ({}));
throw new Error(e.detail || r.statusText);
@@ -2694,23 +2316,6 @@ async function saveEventToDb() {
}
}
// A list loaded by serial: download one event by its event_id -- SFM checks it
// and stores it -- then open it from the store. An event already stored says so.
async function downloadEventBySerial(i, btn) {
const ev = eventList[i];
btn.disabled = true;
setStatus(`Downloading event #${ev.index} (${eventView(ev).label})…`, 'loading');
try {
const body = await deviceFetch('download', { event_id: ev.event_id });
setStatus(downloadSummary(body), 'ok');
if (body.db_event_id) openSidecarModal(body.db_event_id);
} catch (e) {
setStatus(`Download failed: ${e.message}`, 'error');
} finally {
btn.disabled = false;
}
}
// ── Download the event file to the user's computer ──────────────────────────
//
// Uses a transient anchor + click trick so the browser surfaces its native
@@ -2719,7 +2324,7 @@ async function downloadEventBySerial(i, btn) {
function downloadEventFile() {
if (!devHost()) { setStatus('Enter device host first.', 'error'); return; }
const idx = currentEvent;
const url = `${api()}${deviceUrl('event_file', currentUnit(), { index: idx }).path}`;
const url = `${api()}/device/event/${idx}/blastware_file?${deviceParams()}`;
setStatus(`Downloading event #${idx}…`, 'loading');
// Hidden iframe avoids navigating away from the SPA. FastAPI's FileResponse
// sets Content-Disposition: attachment so the browser saves rather than displays.
@@ -3887,10 +3492,6 @@ document.addEventListener('keydown', e => {
// Default API base to wherever this page was served from — works whether you
// hit localhost:8200, 10.0.0.44:8200, or anything else.
document.getElementById('api-base').value = window.location.origin;
for (const id of ['dev-serial', 'dev-host', 'dev-port']) {
document.getElementById(id).addEventListener('input', () => { unitConfirmed = null; applyControls(); });
}
applyControls();
// Reflect any persisted mic-unit preference in the header pill on load
_refreshMicUnitToggleLabel();
+9 -29
View File
@@ -323,29 +323,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
@@ -653,11 +633,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 +651,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 +670,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:
-290
View File
@@ -1,290 +0,0 @@
"""Fakes of both device clients for sfm.device_access tests.
They return the libraries' real dataclasses, and FakeMicromateClient's setup
is decoded from a real UM20147 read. `fail` is a queue of exceptions; each
call pops one, if any, and raises it.
"""
from __future__ import annotations
import copy
import datetime
from pathlib import Path
from micromate.models import MicromateDeviceInfo, MicromateEventRef, MicromateState
from micromate.setup_block import decode_setup
from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
class _Base:
def __init__(self, fail=None, open_error=None):
self.fail = list(fail or [])
self.open_error = open_error
self.calls: list[str] = []
self.opened = 0
self.closed = 0
self._open = False
def _step(self, name):
self.calls.append(name)
if self.fail:
raise self.fail.pop(0)
def open(self):
self.opened += 1
if self.open_error is not None:
raise self.open_error
self._open = True
def close(self):
self.closed += 1
self._open = False
def s3_event(index, key_hex, when, *, record_type="Waveform", pvs=0.12, frames=True):
ev = Event(index=index)
ev._waveform_key = bytes.fromhex(key_hex)
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=when.year, unknown_byte=0,
month=when.month, day=when.day, hour=when.hour,
minute=when.minute, second=when.second)
ev.record_type = record_type
ev.peak_values = PeakValues(tran=0.05, vert=0.08, long=0.03, micl=0.0001,
peak_vector_sum=pvs)
if frames:
ev._a5_frames = ["frame"]
return ev
def _iso(ev):
"""minimateplus.client._event_timestamp_iso's format; "" with no timestamp."""
ts = ev.timestamp
if ts is None:
return ""
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour or 0, ts.minute or 0,
ts.second or 0).isoformat()
def default_s3_events():
return [
s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)),
s3_event(1, "0111245a", datetime.datetime(2026, 10, 2, 9, 30, 15)),
]
class FakeMiniMateClient(_Base):
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
monitor_states=None, write_error=None, **kw):
super().__init__(**kw)
self.serial = serial
self.monitoring = monitoring
self.monitor_states = list(monitor_states) if monitor_states else [monitoring]
self.write_error = write_error
self.writes: list = []
if compliance == "default":
compliance = ComplianceConfig(
recording_mode=0x01, sample_rate=1024, histogram_interval_sec=300,
record_time=3.0, trigger_level_geo=0.5, alarm_level_geo=1.0, geo_range=0,
setup_name="BRIDGE-A", project="Bridge job", client="Acme",
operator="BH", sensor_location="Loc 1", notes=None,
)
self.compliance = compliance
self.events = default_s3_events() if events is None else events
self.download_requests: list = [] # (key4, expected_timestamp) per download
self.last_download = None
def connect(self) -> DeviceInfo:
self._step("connect")
return DeviceInfo(
serial=self.serial, firmware_minor=17, firmware_version="S338.17",
dsp_version="10.72", manufacturer="Instantel", model="MiniMate Plus",
compliance_config=self.compliance,
)
def poll(self) -> None:
self._step("poll")
def wake(self, **kw) -> None:
self._step("wake")
def get_monitor_status(self) -> MonitorStatus:
self._step("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
return MonitorStatus(
is_monitoring=flag == 0x10, battery_v=6.8,
memory_total=983026, memory_free=900000, state_flag=flag,
)
def _write(self, name):
self._step(name)
self.writes.append(name)
if self.write_error is not None:
raise self.write_error
def start_monitoring(self) -> None:
self._write("start_monitoring")
def stop_monitoring(self) -> None:
self._write("stop_monitoring")
def list_event_headers(self):
self._step("list_event_headers")
out = []
for ev in self.events:
h = copy.copy(ev)
h._a5_frames = None
out.append(h)
return out
def download_event_by_key(self, key4, *, expected_timestamp=None):
"""As the real walk: an event whose 0C time is not the expected one comes
back without its 5A."""
self._step("download_event_by_key")
self.download_requests.append((key4, expected_timestamp))
self.last_download = None
for ev in self.events:
if ev._waveform_key == key4:
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)
self.last_download = ev
return ev
return None
_REAL = {}
def _as_downloaded(ev):
"""Give a fake event what a real one-event download carries: BE9441 event 1's
recorded A5 frames, their decoded waveform, and the unit's own 0C peaks for it
-- so the download check sees a whole, matching event."""
if not _REAL:
from minimateplus.framing import S3FrameParser
from minimateplus.waveform_codec import decode_a5_frames
raw = (Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26"
/ "BE9441_event1_0111646a_rx.bin").read_bytes()
_REAL["frames"] = [f for f in S3FrameParser().feed(raw) if f.sub == 0xA5]
_REAL["samples"] = decode_a5_frames(_REAL["frames"])
ev._a5_frames = _REAL["frames"]
ev.raw_samples = _REAL["samples"]
pv = ev.peak_values
ev.peak_values = PeakValues(tran=0.030, vert=0.095, long=0.020, micl=pv.micl if pv else None,
peak_vector_sum=pv.peak_vector_sum if pv else None)
def s4_ref(index, key_hex, when, record_type, *, pvs=0.2):
"""Fixture-backed: the filename it produces names a real file in thor-idf/."""
ref = MicromateEventRef(index=index, key=bytes.fromhex(key_hex), size=0, serial="UM20147",
record_type=record_type, timestamp=when, peak_vector_sum_ips=pvs,
peaks_ips={"Tran": 0.1, "Vert": 0.15, "Long": 0.05, "Mic": 0.0002})
ref.size = (THOR_IDF / ref.filename).stat().st_size
return ref
def default_s4_refs():
return [
s4_ref(0, "055d4a81", datetime.datetime(2025, 5, 31, 13, 59, 1), "waveform"),
s4_ref(1, "055d4a83", datetime.datetime(2025, 3, 30, 7, 1, 10), "histogram"),
]
class _FakeProtocol:
def __init__(self, owner):
self._owner = owner
def poll(self):
self._owner._step("poll")
def execute(self, plan):
self._owner._step("execute")
self._owner.executed.append(plan)
if self._owner.execute_error is not None:
raise self._owner.execute_error
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
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):
super().__init__(**kw)
self.unit_serial = serial # not `serial`: that is the client's method
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
self.executed = []
self.monitoring = monitoring
self.events = events
self.unsolicited = unsolicited
self.protocol = _FakeProtocol(self)
self.event_refs = default_s4_refs() if event_refs is None else event_refs
self.cursor = None
self.fetched: list = []
def is_open(self) -> bool:
return self._open
def connect(self) -> MicromateDeviceInfo:
self._step("connect")
return MicromateDeviceInfo(
serial=self.unit_serial, manufacturer="Instantel", model="MM/ISEE/S",
firmware_line="thor", monitoring=self.monitoring, active_setup="test2.MMB",
)
def serial(self, *, refresh=False):
self._step("serial")
return self.serial_reported if refresh else self.unit_serial
def read_run_state(self):
from micromate.models import MicromateRunState
self._step("read_run_state")
code = self.run_states.pop(0) if len(self.run_states) > 1 else self.run_states[0]
names = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
return MicromateRunState(code, names.get(code, f"unknown(0x{code:02X})"))
def get_state(self) -> MicromateState:
self._step("get_state")
return MicromateState(
monitoring=self.monitoring,
device_time=datetime.datetime(2026, 10, 20, 18, 7, 58),
battery_volts=3.8, memory_total_bytes=15_000_000, memory_free_bytes=14_799_296,
)
def get_event_count(self) -> int:
self._step("get_event_count")
return self.events
def get_setup(self):
self._step("get_setup")
return decode_setup(SETUP_FIXTURE.read_bytes()[11:])
def read_unsolicited(self) -> bytes:
self._step("read_unsolicited")
data, self.unsolicited = self.unsolicited, b""
return data
def list_events(self, *, with_records=True):
self._step("list_events")
return list(self.event_refs)
def iter_events(self, *, with_records=True):
self._step("iter_events")
for ref in self.event_refs:
self.cursor = ref.index
yield ref
def fetch_event(self, ref, *, verify=True, tolerance=0.01, chunk_size=None):
self._step("fetch_event")
self.fetched.append((ref.key_hex, chunk_size))
return (THOR_IDF / ref.filename).read_bytes(), object()
@staticmethod
def decode_error(ref, result):
return None if ref.record_type == "histogram" else 0.0
@@ -1,96 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/raw_bw_20260925_011620_ACH-change_1_setting.bin",
"source_sha256": {
"bw": "e44ce87a1e8638a9346386d5182a97ea142c8486fb17b7de2d1c67d1266be9df",
"s3": "5b15f219ff58a64e61c8b2123034dfcc766465534479a61c1447ea6d66ffd878"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 21,
"request": "41021010001500000a000000000000000000002f03",
"response_sub": 234,
"response_data": "0a00000000000000000000554d3132393437003100"
},
{
"sub": 73,
"request": "41021010004900ffff000000000000000000005703",
"response_sub": 182,
"response_data": "050000000000000000000000e8000b00"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 44,
"request": "41021010002c00ffff000000000000000000003a03",
"response_sub": 211,
"response_data": "7e00000000000000000000007cdc000004524144494f2052494e470000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000034323003c00000000"
},
{
"sub": 126,
"request": "41021010007e00007e00000000000000000000007cdc000005524144494f2052494e47000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000010034323003c00000000ce03",
"response_sub": 129,
"response_data": "0000000000000000000000"
},
{
"sub": 127,
"request": "41021010007f00ffff000000000000000000008d03",
"response_sub": 128,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 21,
"request": "41021010001500000a000000000000000000002f03",
"response_sub": 234,
"response_data": "0a00000000000000000000554d3132393437003100"
},
{
"sub": 73,
"request": "41021010004900ffff000000000000000000005703",
"response_sub": 182,
"response_data": "050000000000000000000000e8000b00"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 44,
"request": "41021010002c00ffff000000000000000000003a03",
"response_sub": 211,
"response_data": "7e00000000000000000000007cdc000005524144494f2052494e470000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000032e5e003c00000000"
},
{
"sub": 126,
"request": "41021010007e00007e00000000000000000000007cdc00001004524144494f2052494e47000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000010032e5e003c00000000f303",
"response_sub": 129,
"response_data": "0000000000000000000000"
},
{
"sub": 127,
"request": "41021010007f00ffff000000000000000000008d03",
"response_sub": 128,
"response_data": "0000000000000000000000"
}
]
}
-252
View File
@@ -1,252 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/raw_bw_20260924_191214_turn_on_monitormode_then_attempt_to_write_config.bin",
"source_sha256": {
"bw": "f65dd3b3260eb1fe034169a276e29f631e73fff69c65861d7281718fdbc2d999",
"s3": "dd78a64ac15d1d93492d0db7e3bafceddc1533ad0b6e7f8a5d19bffd83ecce66"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 21,
"request": "41021010001500000a000000000000000000002f03",
"response_sub": 234,
"response_data": "0a00000000000000000000554d3132393437003100"
},
{
"sub": 73,
"request": "41021010004900ffff000000000000000000005703",
"response_sub": 182,
"response_data": "050000000000000000000000e8000b00"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 150,
"request": "41021010009600ffff00000000000000000000a403",
"response_sub": 105,
"response_data": "0000000000000000000000"
},
{
"sub": 28,
"request": "41021010001c00ffff000000000000000000002a03",
"response_sub": 227,
"response_data": "2c00000000000000000000000e180907ea20130c19000000000001000000000000000000000000000000000000017c00e4e1c000e3f1c0"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 21,
"request": "41021010001500000a000000000000000000002f03",
"response_sub": 234,
"response_data": "0a00000000000000000000554d3132393437003100"
},
{
"sub": 73,
"request": "41021010004900ffff000000000000000000005703",
"response_sub": 182,
"response_data": "050000000000000000000002e8000b00"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 151,
"request": "41021010009700ffff00000000000000000000a503",
"response_sub": 104,
"response_data": "0000000000000000000000"
},
{
"sub": 28,
"request": "41021010001c00ffff000000000000000000002a03",
"response_sub": 227,
"response_data": "2c000000000000000000000000180907ea64130d22000000000001000000000000000000000000000000000000017c00e4e1c000e3e1c0"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 21,
"request": "41021010001500000a000000000000000000002f03",
"response_sub": 234,
"response_data": "0a00000000000000000000554d3132393437003100"
},
{
"sub": 73,
"request": "41021010004900ffff000000000000000000005703",
"response_sub": 182,
"response_data": "050000000000000000000000e8000b00"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 63,
"request": "41021010003f00ffff000000000000000000004d03",
"response_sub": 192,
"response_data": "ff00000000000000000000666163746f72792e4d4d4200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff00000000000000000000544553542e4d4d4200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000042555320544553542e4d4d42000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000057616c7368204a56203234312e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000057616c7368204a56203030382e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000048617762616b6572203332322e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000048617762616b65722033323220626c617374696e672e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000006d696e2e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff00000000000000000000506c6179686f757365204c6f6320312e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000056616c6c657920526f636b20536f6c7574696f6e2e4d4d42000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000005265636f7264696e6753657475702e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000055504d432e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000055504d43204c6f6320332e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000005265736964656e636520496e6e2e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000004d6963726f6d6174652065787420747269676765722e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000004d6963726f6d6174652072656d6f727420616c61726d2e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000054726565206f66204c696665202d204c6f632031202d203538363120536f6c7761792e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000004d656c652d505753412d436172726f6c6c202d4c6f6320342e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff000000000000000000004d6963726f6d617465206d696e2074726967676572206d6d622e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff00000000000000000000466179202d204c6179746f6e204272696467652050726f6a6563742e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000044656661756c74204d6963726f6d61746520495345452e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 64,
"request": "41021010004000ffff000000000000000000004e03",
"response_sub": 191,
"response_data": "ff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
]
}
-156
View File
@@ -1,156 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/raw_bw_20260925_011907_send_multiday_schedule.bin",
"source_sha256": {
"bw": "1884a47bc25ac20f44b5aef4a0f92da6625ce1c809a8794aa2bb5da483ae4bf5",
"s3": "f26370a1bc880dfb08afdf1f3199f9f2811f49bc43ca9d4c9d3dc2b3cabfdbef"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 8,
"request": "41021010000800ffff000000000000000000001603",
"response_sub": 247,
"response_data": "5a0000000000000000000000580900000000000000000000000000000000000000000000000000000000000000000000000000000100010001000100000000000000010001000000000000000000000000000000000002000000000000000200000000b42f"
},
{
"sub": 46,
"request": "41021010002e00ffff000000000000000000003c03",
"response_sub": 209,
"response_data": "1c00000000000000000000001ad50000010000000000000000000000000000000000000000141a"
},
{
"sub": 26,
"request": "41021010001a00ffff000000000000000000002803",
"response_sub": 229,
"response_data": "2c00000000000000000000082a64000004040000020000bf8000000000404000000003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000004d6963000000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d69630000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c000242920000000042480000644200004270000028412900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000bbdf"
},
{
"sub": 218,
"request": "4102101000da0001000000000000000000000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c603",
"response_sub": 37,
"response_data": "0000000000000000000000"
},
{
"sub": 104,
"request": "41021010006800005a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000100010001000000000000000100010000000000000000000000000000000000100200000000000000100200000000dc03",
"response_sub": 151,
"response_data": "0000000000000000000000"
},
{
"sub": 115,
"request": "41021010007300ffff000000000000000000008103",
"response_sub": 140,
"response_data": "0000000000000000000000"
},
{
"sub": 130,
"request": "41021010008200001c0000000000000000000000000000000100000000000000000000000000000000000000000000af03",
"response_sub": 125,
"response_data": "0000000000000000000000"
},
{
"sub": 131,
"request": "41021010008300ffff000000000000000000009103",
"response_sub": 124,
"response_data": "0000000000000000000000"
},
{
"sub": 113,
"request": "41021010007100082c00000000000000000000000000000010041004000010020000bf800000000040400000001003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000004d696300000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d6963000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c001002429200000000424800006442000042700000284129000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005f03",
"response_sub": 142,
"response_data": "0000000000000000000000"
},
{
"sub": 114,
"request": "41021010007200ffff000000000000000000008003",
"response_sub": 141,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 141,
"request": "41021010008d000018000000000000000000005c73797374656d5c7365747570735c74657374322e6d6d626e03",
"response_sub": 114,
"response_data": "0000000000000000000000"
},
{
"sub": 142,
"request": "41021010008e0008900000000000000000000000011004000010020000bf800000000040400000001003000f053e000f00000000000000000001000074657374322e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e0000000000000000000000000000746573743200000000000000000000000000000000000000000000000000000000000000000000000000436c69656e7400000000000000000000000000000000746573743200000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000074657374320000000000000000000000000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000746573743200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000004d696300000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d6963000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c00100242920000000042480000644200004270000028412900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100010000000100000000000000010001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000008d03",
"response_sub": 113,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 141,
"request": "41021010008d00001d000000000000000000005c73797374656d5c7363686564756c655c7363686564756c652e6461747403",
"response_sub": 114,
"response_data": "0000000000000000000000"
},
{
"sub": 142,
"request": "41021010008e0010040000000000000000000000100400000010100010020954455354312e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010100110020974657374322e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001010100210020954455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001010100310020974657374322e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008603",
"response_sub": 113,
"response_data": "0000000000000000000000"
},
{
"sub": 142,
"request": "41021010008e001003200000000000000000000000000000000000000000000000000000000000001010100410020954455354312e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010100510020974657374322e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010100610020954455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003303",
"response_sub": 113,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 71,
"request": "41021010004700ffff000000000000000100005603",
"response_sub": 184,
"response_data": "040000000000000001000000000001"
},
{
"sub": 71,
"request": "41021010004700ffff00000000000000100300005803",
"response_sub": 184,
"response_data": "040000000000000003000000000001"
}
]
}
@@ -1,84 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/raw_bw_20260924_181942_send_TEST1_to_unit.bin",
"source_sha256": {
"bw": "ad6d47ab8602e1435360fa979d1b4aaf9bbf3bd37ada2f64bafe8c19b7317e18",
"s3": "0fc85cd78df4002d97d9e9a1e6e94d9c1d99bc22935e3b2d1e72a552032c1b84"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff00000000000000000000556e6976206f6620506974742d3173742059722e20486f7573696e672d4c6f6331205275736b696e2e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 8,
"request": "41021010000800ffff000000000000000000001603",
"response_sub": 247,
"response_data": "5a0000000000000000000000580900000000000000000000000000000000000000000000000000000000000000000000000000000100010001000100000000000000010001000000000000000000000000000000000002000000000000000200000000b42f"
},
{
"sub": 46,
"request": "41021010002e00ffff000000000000000000003c03",
"response_sub": 209,
"response_data": "1c00000000000000000000001ad50000010000000000000000000000000000000000000000141a"
},
{
"sub": 26,
"request": "41021010001a00ffff000000000000000000002803",
"response_sub": 229,
"response_data": "2c00000000000000000000082a640000040400003c0000bf8000000000400000000003000f053e0007000000000000000000010000556e6976206f6620506974742d3173742059722e20486f7573696e672d4c6f6331205275736b696e2e6d6d620000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e0000000000000000000000000000556e6976206f6620506974742d31737420597220486f7573696e672d4c6f6331205275736b696e000000436c69656e7400000000000000000000000000000000504a204469636b20496e632e000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000054657272612d4d656368616e6963732c20496e632e202d204861727269736f6e0000000000000000000047656e6572616c204e6f7465730000000000000000004c6f6323312d556e6976206f6620506974742e202d205275736b696e2048616c6c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f6320310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a0028001504fb020d00030000404698dd00003e999999696e2e003f8000002f732e0000015665727400000001004a000a0028001504fb020d00030000404698dd00003e999999696e2e003f8000002f732e0000014c6f6e6700000001004a000a0028001504fb020d00030000404698dd00003e999999696e2e003f8000002f732e0000004d6963000000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d69630000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c0002429200000000424800006442000042700000284129000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003cfd"
},
{
"sub": 218,
"request": "4102101000da0001000000000000000000000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c603",
"response_sub": 37,
"response_data": "0000000000000000000000"
},
{
"sub": 104,
"request": "41021010006800005a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000100010001000000000000000100010000000000000000000000000000000000100200000000000000100200000000dc03",
"response_sub": 151,
"response_data": "0000000000000000000000"
},
{
"sub": 115,
"request": "41021010007300ffff000000000000000000008103",
"response_sub": 140,
"response_data": "0000000000000000000000"
},
{
"sub": 130,
"request": "41021010008200001c0000000000000000000000000000000100000000000000000000000000000000000000000000af03",
"response_sub": 125,
"response_data": "0000000000000000000000"
},
{
"sub": 131,
"request": "41021010008300ffff000000000000000000009103",
"response_sub": 124,
"response_data": "0000000000000000000000"
},
{
"sub": 113,
"request": "41021010007100082c00000000000000000000000000000010041004000010020000bf800000000040400000001003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000004d696300000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d6963000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c00100242920000000042480000644200004270000028412900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000cb03",
"response_sub": 142,
"response_data": "0000000000000000000000"
},
{
"sub": 114,
"request": "41021010007200ffff000000000000000000008003",
"response_sub": 141,
"response_data": "0000000000000000000000"
}
]
}
@@ -1,84 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/overwritetest/raw_bw_20260924_185113_test1_overwrite_check.bin",
"source_sha256": {
"bw": "7008231ce9ffadd0f56dfda00cfe030b8721ef928911b72ee58ce11f4ea9146e",
"s3": "d35497ca0ccf554e7bacd464723f3db1c052e2768785ef00b3689784b6e346bd"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 8,
"request": "41021010000800ffff000000000000000000001603",
"response_sub": 247,
"response_data": "5a0000000000000000000000580900000000000000000000000000000000000000000000000000000000000000000000000000000100010001000100000000000000010001000000000000000000000000000000000002000000000000000200000000b42f"
},
{
"sub": 46,
"request": "41021010002e00ffff000000000000000000003c03",
"response_sub": 209,
"response_data": "1c00000000000000000000001ad50000010000000000000000000000000000000000000000141a"
},
{
"sub": 26,
"request": "41021010001a00ffff000000000000000000002803",
"response_sub": 229,
"response_data": "2c00000000000000000000082a64000004040000020000bf8000000000404000000003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000004d6963000000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d69630000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c000242920000000042480000644200004270000028412900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d621"
},
{
"sub": 218,
"request": "4102101000da0001000000000000000000000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c603",
"response_sub": 37,
"response_data": "0000000000000000000000"
},
{
"sub": 104,
"request": "41021010006800005a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000100010001000000000000000100010000000000000000000000000000000000100200000000000000100200000000dc03",
"response_sub": 151,
"response_data": "0000000000000000000000"
},
{
"sub": 115,
"request": "41021010007300ffff000000000000000000008103",
"response_sub": 140,
"response_data": "0000000000000000000000"
},
{
"sub": 130,
"request": "41021010008200001c0000000000000000000000000000000100000000000000000000000000000000000000000000af03",
"response_sub": 125,
"response_data": "0000000000000000000000"
},
{
"sub": 131,
"request": "41021010008300ffff000000000000000000009103",
"response_sub": 124,
"response_data": "0000000000000000000000"
},
{
"sub": 113,
"request": "41021010007100082c00000000000000000000000000000010041004000010020000bf800000000040400000001003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000004d696300000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d6963000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c001002429200000000424800006442000042700000284129000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005f03",
"response_sub": 142,
"response_data": "0000000000000000000000"
},
{
"sub": 114,
"request": "41021010007200ffff000000000000000000008003",
"response_sub": 141,
"response_data": "0000000000000000000000"
}
]
}
@@ -1,162 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/raw_bw_20260925_003029_pull_schedule,_turn_off_repeat_daily,_push_schedule.bin",
"source_sha256": {
"bw": "a6a455fda2702708f4cb36e40eee4d12b7b6cab6b41aa5532210ae205bce735a",
"s3": "d49a4fd199f5a32df2fc2ccdaaf27aaff9a11804dd54a2250efbc0a9e636d786"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 148,
"request": "41021010009400001d000000010000000000005c73797374656d5c7363686564756c655c7363686564756c652e6461747c03",
"response_sub": 107,
"response_data": "0000000000000000000000"
},
{
"sub": 72,
"request": "41021010004800ffff000000000000000100005703",
"response_sub": 183,
"response_data": "040000000000000001000000000001"
},
{
"sub": 72,
"request": "41021010004800ffff000000000000000000005603",
"response_sub": 183,
"response_data": "0c00000000000000000000030000000f03020954455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002703100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 72,
"request": "41021010004800ffff000000000000000000005603",
"response_sub": 183,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 8,
"request": "41021010000800ffff000000000000000000001603",
"response_sub": 247,
"response_data": "5a0000000000000000000000580900000000000000000000000000000000000000000000000000000000000000000000000000000100010001000100000000000000010001000000000000000000000000000000000002000000000000000200000000b42f"
},
{
"sub": 46,
"request": "41021010002e00ffff000000000000000000003c03",
"response_sub": 209,
"response_data": "1c00000000000000000000001ad50000010000000000000000000000000000000000000000141a"
},
{
"sub": 26,
"request": "41021010001a00ffff000000000000000000002803",
"response_sub": 229,
"response_data": "2c00000000000000000000082a64000004040000020000bf8000000000404000000003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000004d6963000000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d69630000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c000242920000000042480000644200004270000028412900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000bbdf"
},
{
"sub": 218,
"request": "4102101000da0001000000000000000000000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c603",
"response_sub": 37,
"response_data": "0000000000000000000000"
},
{
"sub": 104,
"request": "41021010006800005a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000100010001000000000000000100010000000000000000000000000000000000100200000000000000100200000000dc03",
"response_sub": 151,
"response_data": "0000000000000000000000"
},
{
"sub": 115,
"request": "41021010007300ffff000000000000000000008103",
"response_sub": 140,
"response_data": "0000000000000000000000"
},
{
"sub": 130,
"request": "41021010008200001c0000000000000000000000000000000100000000000000000000000000000000000000000000af03",
"response_sub": 125,
"response_data": "0000000000000000000000"
},
{
"sub": 131,
"request": "41021010008300ffff000000000000000000009103",
"response_sub": 124,
"response_data": "0000000000000000000000"
},
{
"sub": 113,
"request": "41021010007100082c00000000000000000000000000000010041004000010020000bf800000000040400000001003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000004d696300000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d6963000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c001002429200000000424800006442000042700000284129000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005f03",
"response_sub": 142,
"response_data": "0000000000000000000000"
},
{
"sub": 114,
"request": "41021010007200ffff000000000000000000008003",
"response_sub": 141,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 141,
"request": "41021010008d00001d000000000000000000005c73797374656d5c7363686564756c655c7363686564756c652e6461747403",
"response_sub": 114,
"response_data": "0000000000000000000000"
},
{
"sub": 142,
"request": "41021010008e0010020c0000000000000000000010020000000f100310020954455354312e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000027100310100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e003",
"response_sub": 113,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 71,
"request": "41021010004700ffff000000000000000100005603",
"response_sub": 184,
"response_data": "040000000000000001000000000001"
},
{
"sub": 71,
"request": "41021010004700ffff00000000000000100300005803",
"response_sub": 184,
"response_data": "040000000000000003000000000001"
}
]
}
@@ -1,162 +0,0 @@
{
"source": "bridges/captures/9-24-26 - micromate2/raw_bw_20260924_191835_read_scheduler.bin",
"source_sha256": {
"bw": "8e9f773f97bc43a0e3ab312e2c5ee072c86ca391b07a01ea7fa71c2d0110ff16",
"s3": "4ef5db0c8b804ac646c61151366e52df3bda1d96a492d4b420cb8fe6934dcedb"
},
"unit": "UM12947",
"firmware_version": "11.0CB",
"firmware_line": "blastware",
"exchanges": [
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 148,
"request": "41021010009400001d000000010000000000005c73797374656d5c7363686564756c655c7363686564756c652e6461747c03",
"response_sub": 107,
"response_data": "0000000000000000000000"
},
{
"sub": 72,
"request": "41021010004800ffff000000000000000100005703",
"response_sub": 183,
"response_data": "040000000000000001000000000001"
},
{
"sub": 72,
"request": "41021010004800ffff000000000000000000005603",
"response_sub": 183,
"response_data": "0c00000000000000000000030000000f030228556e6976206f6620506974742d3173742059722e20486f7573696e672d4c6f6331205275736b696e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002703100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 72,
"request": "41021010004800ffff000000000000000000005603",
"response_sub": 183,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 65,
"request": "41021010004100ffff000000000000000000004f03",
"response_sub": 190,
"response_data": "ff0000000000000000000054455354312e6d6d62000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
},
{
"sub": 8,
"request": "41021010000800ffff000000000000000000001603",
"response_sub": 247,
"response_data": "5a0000000000000000000000580900000000000000000000000000000000000000000000000000000000000000000000000000000100010001000100000000000000010001000000000000000000000000000000000002000000000000000200000000b42f"
},
{
"sub": 46,
"request": "41021010002e00ffff000000000000000000003c03",
"response_sub": 209,
"response_data": "1c00000000000000000000001ad50000010000000000000000000000000000000000000000141a"
},
{
"sub": 26,
"request": "41021010001a00ffff000000000000000000002803",
"response_sub": 229,
"response_data": "2c00000000000000000000082a64000004040000020000bf8000000000404000000003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a0028001504fb020d00030000404698dd00003f000000696e2e003f8000002f732e0000004d6963000000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d69630000000200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c000242920000000042480000644200004270000028412900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000bbdf"
},
{
"sub": 218,
"request": "4102101000da0001000000000000000000000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c603",
"response_sub": 37,
"response_data": "0000000000000000000000"
},
{
"sub": 104,
"request": "41021010006800005a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000100010001000000000000000100010000000000000000000000000000000000100200000000000000100200000000dc03",
"response_sub": 151,
"response_data": "0000000000000000000000"
},
{
"sub": 115,
"request": "41021010007300ffff000000000000000000008103",
"response_sub": 140,
"response_data": "0000000000000000000000"
},
{
"sub": 130,
"request": "41021010008200001c0000000000000000000000000000000100000000000000000000000000000000000000000000af03",
"response_sub": 125,
"response_data": "0000000000000000000000"
},
{
"sub": 131,
"request": "41021010008300ffff000000000000000000009103",
"response_sub": 124,
"response_data": "0000000000000000000000"
},
{
"sub": 113,
"request": "41021010007100082c00000000000000000000000000000010041004000010020000bf800000000040400000001003000f053e000700000000000000000001000054455354312e6d6d6200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6f636174696f6e000000000000000000000000000054657374204c6f636174696f6e2031202d203132333420656c65637472696320626f6f67616c6f6f0000436c69656e7400000000000000000000000000000000544d49000000000000000000000000000000000000000000000000000000000000000000000000000000436f6d70616e7900000000000000000000000000000053657276657273446f776e4c61627300000000000000000000000000000000000000000000000000000047656e6572616c204e6f746573000000000000000000486f706566756c6c79207468697320776f726b732120646964206974206f76657277726974653f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005465737420436f6e6669672053656e64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015472616e00000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000015665727400000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000014c6f6e6700000001004a000a002800151004fb10020d0010030000404698dd00003f000000696e2e003f8000002f732e0000004d696300000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c290000004c4d6963000000100200c80032000a000a05dc01f4000500003cb8583600003c289d8f707369003ca8b5e4284c29000000534d69630000000900014e4c000a005a0055012c000c001002429200000000424800006442000042700000284129000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005f03",
"response_sub": 142,
"response_data": "0000000000000000000000"
},
{
"sub": 114,
"request": "41021010007200ffff000000000000000000008003",
"response_sub": 141,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 141,
"request": "41021010008d00001d000000000000000000005c73797374656d5c7363686564756c655c7363686564756c652e6461747403",
"response_sub": 114,
"response_data": "0000000000000000000000"
},
{
"sub": 142,
"request": "41021010008e0010020c0000000000000000000010030000000f100310020954455354312e6d6d620000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000027100310100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e103",
"response_sub": 113,
"response_data": "0000000000000000000000"
},
{
"sub": 91,
"request": "41021010005b000030000000000000000000009b03",
"response_sub": 164,
"response_data": "300000000000000000000000000050496e7374616e74656c000600c3f04a00e4194f0074024d4d2f495345452f532f494f00001f603e7657603e76"
},
{
"sub": 71,
"request": "41021010004700ffff000000000000000100005603",
"response_sub": 184,
"response_data": "040000000000000001000000000001"
},
{
"sub": 71,
"request": "41021010004700ffff00000000000000100300005803",
"response_sub": 184,
"response_data": "040000000000000003000000000001"
}
]
}
-31
View File
@@ -1,31 +0,0 @@
# MiniMate bench, 2026-10-25 — BE9441 (S338.17, mic disabled), serial cable
Raw unit-to-SFM bytes of two one-event downloads by serial (`POST /device/events/download`),
taken from the bench frame log in the order received: the whole session (POLL, serial,
config, the event walk, then the `0x5A` bulk stream). Parse with `S3FrameParser` and keep
the `0xA5` frames.
| file | event | key | 0x5A pattern | unit's own 0C peaks (in/s) T / V / L |
|---|---|---|---|---|
| `BE9441_event0_01110000_rx.bin` | 0 (first) | `01110000` | probe, metadata pages `0x1002` `0x1004`, samples, TERM | 0.020 / 0.060 / 0.015 |
| `BE9441_event1_0111646a_rx.bin` | 1 | `0111646a` | probe, samples, TERM — no metadata pages | 0.030 / 0.095 / 0.020 |
Both events: single shot, 4096 sps, 5 s record + 0.25 s pre-trigger = 5.25 s = 21,504 samples per channel.
Event 1 is the case that showed the body builder skipping 13 bytes on its second and third
frames as if they were metadata pages (2 bytes lost, decode truncated at 1,024 / 2,782 / 512).
## `blastware/`: Blastware's own downloads of the same events (Brian, 2026-10-25)
| file | event | key | note |
|---|---|---|---|
| `K441LTMK.P00` | 0 | `01110000` | byte-identical to SFM's build (sha `589073a0…`) |
| `K441LTMK.Q10` | 1 | `0111646a` | byte-identical to SFM's build after the metadata-page fix (sha `e74c664d…`) |
| `K441LTMK.QZ0` | 2 | `0111c92c` | **crosses the 64 KB page boundary**: STRT end key `01122f06` |
| `K441LTML.T80` | 19 | `0118a4ca` | **crosses the 64 KB page boundary**: STRT end key `01190824` |
On the 2026-10-26 re-run, SFM's own downloads of events 0, 1, 3, 4 and 10 were byte-identical to
Blastware's files, all five. QZ0 and T80 are the byte-exact target for a fix of the
page bug. Carrying the page byte is enough to address the first chunk in the next page
(0x0112012C answered). The second chunk (0x0112032C) puts a raw 0x03 in the request's
params, and the unit does not answer. How Blastware encodes 02/03/04 inside params is
unknown; it needs a wire capture of Blastware downloading one of these two events.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,52 +0,0 @@
# Blastware downloading all 8 events from BE9441, recorded (2026-10-26)
BE9441 (S338.17, single shot, 4096 sps) on the dev box's serial port, shared on TCP by
`bridges/mm_link.py`; Blastware connected over TCP, listed the events and copied all 8
to disk. Both directions, raw:
| file | direction | size |
|---|---|---|
| `blastware_requests.bin` | Blastware → unit (748 requests, each after a `41 03` SESSION_RESET) | 17,757 B |
| `unit_replies.bin` | unit → Blastware | 364,972 B |
Events (key → end), from Blastware's 5A walks. Four cross a 64 KB page (1, 3, 5, 7):
| event | start key | end (STRT) | 5A requests |
|---|---|---|---|
| 0 | 01110000 | 01118a2c | 70 |
| 1 | 01118a2c | 011216c4 | 71 (crosses into page 0x12) |
| 2 | 011216c4 | 0112a0b6 | 69 |
| 3 | 0112a0b6 | 011329d2 | 69 (crosses into 0x13) |
| 4 | 011329d2 | 0113b072 | 68 |
| 5 | 0113b072 | 01143046 | 64 (crosses into 0x14) |
| 6 | 01143046 | 0114b0b2 | 65 |
| 7 | 0114b0b2 | 01152f0e | 64 (crosses into 0x15) |
What it settled (measured): every request is the standard 16-byte payload, SUM8 checksum,
and every 02 / 03 / 04 / 10 byte DLE-escaped (748/748 re-encode byte-identically). The 5A
"offset" is a length (0x0200 per chunk, the remainder for TERM), followed by a 4-byte linear
address; a walk is start, start+0x200, ... carrying into the page byte, then TERM at the next
boundary for exactly the remainder. The first event's "metadata pages at 0x1002/0x1004" are
its chunks at 0x0200 and 0x0400, escaped (`10 02 00`, `10 04 00`).
## `blastware/`: the files Blastware wrote in that session (Brian)
| file | event | crosses a page |
|---|---|---|
| `K441LTOF.ZI0` | 0 (`01110000`) | no |
| `K441LTOF.ZQ0` | 1 (`01118a2c`) | yes, into 0x12 |
| `K441LTOF.ZV0` | 2 (`011216c4`) | no |
| `K441LTOG.000` | 3 (`0112a0b6`) | yes, into 0x13 |
| `K441LTOG.050` | 4 (`011329d2`) | no |
| `K441LTOG.0A0` | 5 (`0113b072`) | yes, into 0x14 |
| `K441LTOG.0L0` | 6 (`01143046`) | no |
| `K441LTOG.0S0` | 7 (`0114b0b2`) | yes, into 0x15 |
After the fix (887e75d), SFM's own live downloads of all 8 events were byte-identical to
Blastware's files (sha256), the 4 crossings included.
The unit's replies (measured on all 748): every 02/03/04/10 is escaped with a `10`, exactly as
in requests, and the checksum is SUM8 of the **unescaped** payload, 748/748. `S3FrameParser`
keeps the escape bytes of `10 02/03/04` in its output and sums those too, which is why its
`checksum_valid` is False on 502 of the 540 A5 replies. The "S3 checksums frequently fail"
note in `protocol._validate_frame` describes the parser, not the unit.
Binary file not shown.
@@ -1,34 +0,0 @@
# BE9441 through the recording bridge, 16:08–19:06 on 2026-10-26
BE9441 (S338.17) on the dev box's serial port, shared on TCP by `bridges/mm_link.py`.
Both Blastware and SFM connected through it, so `requests.bin` holds both clients'
requests in order and `unit_replies.bin` everything the unit sent: 1,596 requests,
722 of them 5A, matched by 722 A5 replies.
What happened, in order:
| time | who | what |
|---|---|---|
| 16:10–16:15 | Blastware | listed and downloaded events 0 and 1 (below); a cancelled re-read of event 1 |
| 16:26:10 | Blastware | **config write**: Histogram mode, 15-minute interval, mic enabled (13 frames) |
| 16:27:21 | Blastware | **config write**: interval back to 2 s (13 frames; 2 image bytes differ) |
| 17:00 | keypad | histogram monitoring started |
| 18:47–18:53 | SFM | status reads; the flag read 0x0B (monitoring, histogram) |
| 18:53:53 | SFM | **stop** (0x97): acked 0x68, read back idle; audit c9c17128 |
| 18:55–19:00 | Blastware | downloaded event 2 (a cancelled partial walk, then the full one) |
| 19:03–19:06 | SFM | downloaded events 1 and 2 by serial, byte-identical to `blastware/` |
Events (Blastware's files in `blastware/`):
| event | key → end | what | file |
|---|---|---|---|
| 0 | `01110000` → `011106A0` | histogram, 2 s, **mic off**, 22 intervals (1,696 B) | `K441LTOK.QZ0` (+ ASCII) |
| 1 | `011106A0` → `0111F210` | waveform, 60,272 B | `K441LTOK.R10` |
| 2 | `0111F210` → `011307C0` | histogram, 2 s, mic on, 4,096 sps, 3,398 intervals, **71,088 B: 139 requests, two 64 KB crossings** | `K441LTON.900` (+ ASCII) |
Measured from this recording:
- every request, write frames included, follows the uniform escape model (#46);
- the config image's layout matches Series 4's `0x1A` (#48);
- the mic-off histogram format (#47);
- the old histogram reader misreads 87/3,398 of event 2's intervals at 4,096 sps (#49);
- the 0x1C flag 0x0B and the escaped-memory-field decode (`d990466`).
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-85
View File
@@ -1,85 +0,0 @@
"""BE9441's recorded bench session (2026-10-25), replayed reply for reply.
Shared by the MiniMate download tests. See
tests/fixtures/minimate-bench-10-25-26/README.md for the provenance.
"""
from __future__ import annotations
from pathlib import Path
import minimateplus.protocol as mp
from minimateplus.framing import S3FrameParser
_DIR = Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26"
FIX = _DIR / "BE9441_event1_0111646a_rx.bin" # event 1 (non-first)
FIX_EVENT0 = _DIR / "BE9441_event0_01110000_rx.bin" # event 0 (its chunks at 0x0200 / 0x0400 were
# once read as "metadata pages 0x1002 / 0x1004")
KEY = bytes.fromhex("0111646a")
STAMP = "2026-10-25T14:10:49"
UNIT_PEAKS = {"Tran": 0.030, "Vert": 0.095, "Long": 0.020} # the unit's own 0C peaks, in/s
SESSION_RESET = b"\x41\x03"
def recorded_replies(path=None):
"""[(sub, raw_bytes)] for every frame of the session, in order."""
raw, out, start, p = (path or FIX).read_bytes(), [], 0, S3FrameParser()
for i in range(len(raw)):
for f in p.feed(raw[i:i + 1]):
out.append((f.sub, raw[start:i + 1]))
start = i + 1
return out
class SessionReplay:
"""Answers each request with the next recorded reply of its own SUB (reply =
0xFF - request). `quiet_5a_from`: from that 5A request on, the 5A stream gets
one stray 0x41 and then nothing, while every other request is still answered
-- BE9441 dropped out of the stream as it rebooted, then answered the walk."""
def __init__(self, replies, quiet_5a_from=None):
self.queues = {}
for sub, raw in replies:
self.queues.setdefault(sub, []).append(raw)
self.quiet_5a_from, self.n5a, self._buf, self.open_ = quiet_5a_from, 0, b"", False
def connect(self):
self.open_ = True
def disconnect(self):
self.open_ = False
def is_connected(self):
return self.open_
def write(self, data):
data = bytes(data)
if data == SESSION_RESET:
return
req = data[5] # 41 02 10 10 00 <SUB>
if req == 0x5A:
n, self.n5a = self.n5a, self.n5a + 1
if self.quiet_5a_from is not None and n >= self.quiet_5a_from:
if n == self.quiet_5a_from:
self._buf += b"\x41"
return
self._buf += self.queues[0xFF - req].pop(0)
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def read_until_idle(self, *a, **kw):
out, self._buf = self._buf, b""
return out
def fast_clock(monkeypatch):
"""Make the protocol's 10 s receive deadlines pass in a few loop turns."""
t = [0.0]
def tick():
t[0] += 0.5
return t[0]
monkeypatch.setattr(mp.time, "monotonic", tick)
monkeypatch.setattr(mp.time, "sleep", lambda s: None)
-287
View File
@@ -1,287 +0,0 @@
"""SFM's MiniMate requests and 5A walk, against Blastware's own (recorded 2026-10-26).
Blastware downloaded all 8 of BE9441's events -- four of which cross a 64 KB page
-- while a bridge recorded both directions (fixture README). Every one of its 748
requests is the standard 16-byte payload with a SUM8 checksum and every 02 / 03 /
04 / 10 byte DLE-escaped; a 5A request carries a length (0x0200, or the remainder
for TERM) and a 4-byte linear address. The walk is the event's start, then
+0x200 at a time carrying into the page byte, then TERM at the next boundary for
exactly the remainder. SFM must send exactly those requests.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import minimateplus.protocol as mp # noqa: E402
from minimate_replay import fast_clock # noqa: E402
from minimateplus.blastware_file import extract_body_bytes, write_blastware_file # noqa: E402
from minimateplus.models import Event # noqa: E402
from minimateplus.framing import (S3FrameParser, build_5a_request, build_bw_frame, # noqa: E402
parse_strt_end_key, parse_strt_end_offset, waveform_key_params)
from minimateplus.waveform_codec import STREAM_END_ID, decode_waveform_v2, walk_records # noqa: E402
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-blastware"
def _unstuff(b: bytes) -> bytes:
out, k = bytearray(), 0
while k < len(b):
if b[k] == 0x10 and k + 1 < len(b):
out.append(b[k + 1]); k += 2
else:
out.append(b[k]); k += 1
return bytes(out)
def bw_requests() -> list:
"""Blastware's requests, each as wire bytes; the SESSION_RESETs dropped."""
raw, out, i = (FIX / "blastware_requests.bin").read_bytes(), [], 0
while i < len(raw):
if raw[i:i + 2] == b"\x41\x03":
i += 2
continue
j = i + 2
while raw[j] != 0x03: # the first ETX not escaped by a DLE
j += 2 if raw[j] == 0x10 else 1
out.append(raw[i:j + 1])
i = j + 1
return out
def logical(frame: bytes) -> bytes:
return _unstuff(frame[2:-1])[:-1] # the 16-byte payload, checksum dropped
def unit_a5_replies() -> list:
raw, out, start, p = (FIX / "unit_replies.bin").read_bytes(), [], 0, S3FrameParser()
for i in range(len(raw)):
for f in p.feed(raw[i:i + 1]):
if f.sub == 0xA5:
out.append(raw[start:i + 1])
start = i + 1
return out
REQS = bw_requests()
FIVE_A = [f for f in REQS if logical(f)[2] == 0x5A]
def addr_len(frame: bytes) -> tuple:
p = logical(frame)
return int.from_bytes(p[6:10], "big"), int.from_bytes(p[4:6], "big")
def test_the_recording_is_what_the_readme_says():
assert (len(REQS), len(FIVE_A)) == (748, 540)
def test_every_blastware_5a_request_is_rebuilt_byte_for_byte():
assert [build_5a_request(*addr_len(f)) for f in FIVE_A] == FIVE_A
def test_every_other_blastware_request_is_rebuilt_byte_for_byte():
others = [f for f in REQS if logical(f)[2] != 0x5A]
assert len(others) == 208
for f in others:
p = logical(f)
assert build_bw_frame(p[2], p[5], p[6:16]) == f
def test_a_standard_request_escapes_02_03_04_in_its_params_and_checksum():
frame = build_bw_frame(0x0A, 0x46, waveform_key_params(bytes.fromhex("01120203")))
assert b"\x10\x02\x10\x03" in frame # the key's 02 and 03
for low in range(256): # a checksum of 0x03
f = build_bw_frame(0x0A, 0x46, waveform_key_params(bytes([0x01, 0x11, 0x50, low])))
if sum(_unstuff(f[2:-1])[:-1]) & 0xFF == 0x03:
assert f.endswith(b"\x10\x03\x03")
break
else:
pytest.fail("no key gave a checksum of 0x03")
# -- the walk ------------------------------------------------------------------
class ByAddress:
"""Answers each 5A request with Blastware's recorded reply for the same
(address, length); records what SFM sent."""
def __init__(self):
self.replies = {addr_len(q): r for q, r in zip(FIVE_A, unit_a5_replies())}
self.sent, self._buf = [], b""
def write(self, data):
data = bytes(data)
self.sent.append(data)
self._buf += self.replies.get(addr_len(data), b"")
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def blastware_walk(start: int) -> list:
"""Blastware's requests for the event that starts at `start`."""
i = next(k for k, f in enumerate(FIVE_A) if addr_len(f) == (start, 0x200))
walk = [FIVE_A[i]]
while addr_len(walk[-1])[1] == 0x200: # until TERM (a short read)
i += 1
walk.append(FIVE_A[i])
return walk
@pytest.fixture(autouse=True)
def _fast(monkeypatch):
fast_clock(monkeypatch)
# BE9441's 8 events; 1, 3, 5 and 7 cross into the next 64 KB page.
EVENTS = [("01110000", "K441LTOF.ZI0"), ("01118a2c", "K441LTOF.ZQ0"), ("011216c4", "K441LTOF.ZV0"),
("0112a0b6", "K441LTOG.000"), ("011329d2", "K441LTOG.050"), ("0113b072", "K441LTOG.0A0"),
("01143046", "K441LTOG.0L0"), ("0114b0b2", "K441LTOG.0S0")]
def test_the_crossing_events_are_the_ones_named():
ends = {k: addr_len(blastware_walk(int(k, 16))[-1]) for k, _ in EVENTS}
crossing = [k for k, (a, n) in ends.items() if (a + n) >> 16 != int(k, 16) >> 16]
assert crossing == ["01118a2c", "0112a0b6", "0113b072", "0114b0b2"]
@pytest.mark.parametrize("key", [k for k, _ in EVENTS])
def test_the_walk_sends_exactly_blastwares_requests_and_the_event_is_whole(key):
t = ByAddress()
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, strict=True)
want = blastware_walk(int(key, 16))
assert t.sent == want
assert len(frames) == len(want)
_s, body, _f = extract_body_bytes(frames)
recs = walk_records(body)
assert body[recs[-1]["end"] + 4] == STREAM_END_ID
dec = decode_waveform_v2(body)
assert len({len(dec[c]) for c in ("Tran", "Vert", "Long")}) == 1
@pytest.mark.parametrize("key,bw", EVENTS)
def test_the_file_built_from_the_walk_is_blastwares_own(key, bw, tmp_path):
frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream(
bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, strict=True)
ev = Event(index=0)
ev.timestamp = None # the builder takes the footer from the TERM frame
path = tmp_path / bw
write_blastware_file(ev, frames, path)
assert path.read_bytes() == (FIX / "blastware" / bw).read_bytes()
# -- the requests BE9441 answered after the escape fix ---------------------------
def test_the_compliance_reads_be9441_answered_with_the_escaped_0x04():
# SUB 1A frames B and C are the only fixed requests whose bytes the fix changed
# (their 0x0400 length went out bare). These exact frames got full replies,
# 2,125 bytes, decoded correctly (bench 2026-10-26 14:38:43).
assert build_bw_frame(0x1A, 0x0400, bytes(7) + b"\x64\x00\x00").hex() == \
"41021010001a00100400000000000000006400009203"
assert build_bw_frame(0x1A, 0x0400, bytes([0, 0, 4, 0, 0, 0, 0, 0x64, 0, 0])).hex() == \
"41021010001a0010040000001004000000006400009603"
# -- synthetic replies: the unit's own encoding, with a chosen STRT end ----------
def _escape(b: bytes) -> bytes:
"""The unit's encoding (measured on 748 replies): 10 before 02, 03, 04 and 10."""
return b"".join(bytes([0x10, x]) if x in (0x02, 0x03, 0x04, 0x10) else bytes([x]) for x in b)
def _parse(wire: bytes):
frames = S3FrameParser().feed(wire)
assert len(frames) == 1
return frames[0]
def _logical(reply: bytes) -> bytes:
"""A recorded reply's payload, unescaped and without its checksum. Each
recorded reply opens with the unit's `41 03 41` before its `10 02`."""
return _unstuff(reply[reply.index(b"\x10\x02") + 2:-1])[:-1]
def first_reply_ending_at(end: int, event: int = 1) -> bytes:
"""A recorded first-chunk reply with STRT's end key set to `end`, re-encoded."""
q = FIVE_A.index(blastware_walk(int(EVENTS[event][0], 16))[0])
payload = bytearray(_logical(unit_a5_replies()[q]))
i = payload.find(b"STRT")
payload[i + 6:i + 10] = end.to_bytes(4, "big")
return b"\x10\x02" + _escape(bytes(payload) + bytes([sum(payload) & 0xFF])) + b"\x03"
def test_the_reply_encoder_is_the_units():
q = FIVE_A.index(blastware_walk(0x01118a2c)[0])
recorded = unit_a5_replies()[q]
payload = _logical(recorded)
i = payload.find(b"STRT")
end = int.from_bytes(payload[i + 6:i + 10], "big")
assert _parse(first_reply_ending_at(end)).data == _parse(recorded).data
def test_an_end_key_holding_escaped_bytes_reads_whole():
# None of the 8 recorded end keys holds a 02/03/04/10; this one holds 03 and 10.
data = _parse(first_reply_ending_at(0x01120310)).data
assert parse_strt_end_key(data) == 0x01120310
assert parse_strt_end_offset(data) != 0x0310 # the old reader's misread
class Synthetic:
"""Answers the first 5A request with `first`, each chunk with a recorded chunk
reply and the TERM with a recorded TERM reply; records (address, length)."""
def __init__(self, first: bytes):
replies = unit_a5_replies()
walk = blastware_walk(0x01118a2c)
self.first, self.sent, self._buf = first, [], b""
self.chunk = replies[FIVE_A.index(walk[1])]
self.term = replies[FIVE_A.index(walk[-1])]
def write(self, data):
a, n = addr_len(bytes(data))
self.sent.append((a, n))
self._buf += self.first if len(self.sent) == 1 else (self.chunk if n == 0x200 else self.term)
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def walk(first: bytes, start: int = 0x01118a2c, **kw):
t = Synthetic(first)
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
start.to_bytes(4, "big"), stop_after_metadata=False, include_terminator=True, **kw)
return t.sent, frames
def test_the_walk_ends_on_an_escaped_end_key():
sent, _ = walk(first_reply_ending_at(0x01120310), strict=True)
# chunks step from the start (...8a2c), so the TERM is at 0x0112022C for 0xE4
assert sent[-1] == (0x0112022C, 0x01120310 - 0x0112022C) # TERM: the tail, exactly
def test_a_large_event_walks_whole_past_the_callers_cap():
# 2,545 of 63,500 archived histograms exceed the ~66 KB a 128-chunk cap allowed.
start, end = 0x01118a2c, 0x01118a2c + 300_000
sent, frames = walk(first_reply_ending_at(end), start, strict=True, max_chunks=128)
n = (end - start) // 0x200
assert sent[:-1] == [(start + 0x200 * k, 0x200) for k in range(n)]
assert sent[-1] == (start + 0x200 * n, (end - start) % 0x200)
assert len(frames) == len(sent)
@pytest.mark.parametrize("strict", [True, False])
@pytest.mark.parametrize("size,why", [(0x100, "less than one 0x200 chunk"),
(0x500000, "more than any unit holds")])
def test_a_misread_strt_is_refused_in_both_modes(size, why, strict):
with pytest.raises(mp.ProtocolError, match=why):
walk(first_reply_ending_at(0x01118a2c + size), strict=strict)
-124
View File
@@ -1,124 +0,0 @@
"""SFM's 5A walk past the old 128-chunk cap, against Blastware (BE9441, 2026-10-26).
Event 2 of tests/fixtures/minimate-bench-10-26-26-histogram/ is a 71,088-byte
histogram: 139 requests, crossing two 64 KB pages. Before the walk was sized from
STRT, a caller's max_chunks=128 cut it short. Fed the unit's recorded replies,
SFM's walk must send exactly Blastware's requests and rebuild Blastware's file.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import minimateplus.protocol as mp # noqa: E402
from minimate_replay import fast_clock # noqa: E402
from minimateplus.blastware_file import write_blastware_file # noqa: E402
from minimateplus.framing import S3FrameParser # noqa: E402
from minimateplus.models import Event # noqa: E402
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
def _unstuff(b: bytes) -> bytes:
out, k = bytearray(), 0
while k < len(b):
if b[k] == 0x10 and k + 1 < len(b):
out.append(b[k + 1]); k += 2
else:
out.append(b[k]); k += 1
return bytes(out)
def _requests() -> list:
raw, out, i = (FIX / "requests.bin").read_bytes(), [], 0
while i < len(raw):
if raw[i:i + 2] == b"\x41\x03":
i += 2
continue
if raw[i:i + 2] != b"\x41\x02":
i += 1
continue
j = i + 2
while raw[j] != 0x03:
j += 2 if raw[j] == 0x10 else 1
out.append(raw[i:j + 1])
i = j + 1
return out
def _addr_len(frame: bytes) -> tuple:
p = _unstuff(frame[2:-1])
return int.from_bytes(p[6:10], "big"), int.from_bytes(p[4:6], "big")
def _a5_replies() -> list:
raw, out, start, p = (FIX / "unit_replies.bin").read_bytes(), [], 0, S3FrameParser()
for i in range(len(raw)):
for f in p.feed(raw[i:i + 1]):
if f.sub == 0xA5:
out.append(raw[start:i + 1])
start = i + 1
return out
FIVE_A = [f for f in _requests() if _unstuff(f[2:-1])[2] == 0x5A]
REPLIES = {}
for _q, _r in zip(FIVE_A, _a5_replies()):
REPLIES.setdefault(_addr_len(_q), _r)
class ByAddress:
def __init__(self):
self.sent, self._buf = [], b""
def write(self, data):
data = bytes(data)
self.sent.append(data)
self._buf += REPLIES.get(_addr_len(data), b"")
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def _blastware_walk(start: int) -> list:
"""Blastware's last complete walk for the event at `start` (it also cancelled one)."""
starts = [k for k, f in enumerate(FIVE_A) if _addr_len(f) == (start, 0x200)]
for i in reversed(starts):
walk = [FIVE_A[i]]
while i + 1 < len(FIVE_A) and _addr_len(walk[-1])[1] == 0x200:
i += 1
walk.append(FIVE_A[i])
if _addr_len(walk[-1])[1] != 0x200:
return walk
raise AssertionError("no complete walk")
@pytest.fixture(autouse=True)
def _fast(monkeypatch):
fast_clock(monkeypatch)
def test_the_recording_pairs_up():
assert len(FIVE_A) == len(_a5_replies()) == 722
@pytest.mark.parametrize("key,bw,n", [("0111f210", "K441LTON.900", 139),
("011106a0", "K441LTOK.R10", 118)])
def test_the_walk_is_blastwares_and_rebuilds_its_file(key, bw, n, tmp_path):
t = ByAddress()
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
bytes.fromhex(key), stop_after_metadata=False, include_terminator=True,
strict=True, max_chunks=128)
want = _blastware_walk(int(key, 16))
assert len(want) == n and t.sent == want
ev = Event(index=0)
ev.timestamp = None
write_blastware_file(ev, frames, tmp_path / bw)
assert (tmp_path / bw).read_bytes() == (FIX / "blastware" / bw).read_bytes()
-37
View File
@@ -1,37 +0,0 @@
"""A 5A request's checksum is DLE-escaped when it lands on 02 / 03 / 04 / 10.
BE9441 (bench, 2026-10-25/26) never answered the request for chunk 0x7D06 of
event 01122f06 -- twice, each time rebooting ~11 s later -- because the frame
ended `... 02 03`: a bare 0x02 checksum, the STX byte, before ETX. Sent with
the checksum escaped (`10 02 03`) it answered in 28 ms, as did chunks 0x7F06
(checksum 0x04) and 0x8B06 (0x10), and the event downloaded whole and verified.
The escape set is the one a Micromate uses for every byte (measured on 251/251
THOR requests); the MiniMate's own de-stuffing keeps `10 02/03/04` literal.
"""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.framing import build_5a_request # noqa: E402
def chunk(counter: int) -> str:
# Event 01122f06's chunk reads, length 0x0200 (once read as an "offset 0x1002")
return build_5a_request(0x01120000 + counter, 0x0200).hex()
@pytest.mark.parametrize("counter,wire", [
# the wire bytes BE9441 answered, checksum escaped
(0x7D06, "41021010005a0010020001127d06000000000000100203"), # checksum 0x02
(0x7F06, "41021010005a0010020001127f06000000000000100403"), # checksum 0x04
(0x8B06, "41021010005a0010020001128b06000000000000101003"), # checksum 0x10
# an ordinary checksum is untouched
(0x7B06, "41021010005a0010020001127b060000000000000003"),
])
def test_the_checksum_is_escaped_only_when_it_is_a_framing_byte(counter, wire):
assert chunk(counter) == wire
+194
View File
@@ -0,0 +1,194 @@
"""A Series-3 waveform's time comes from the instrument's own event record, not a filename.
A Blastware waveform file carries a copy of the unit's event record:
`00 28 05 00 ?? ?? | fe 80 | trigger | stop`, each time `dd mm yyyy(BE) 00 hh mm ss`.
Measured 2026-10-26:
* it is the instrument's data: in all 8 of BE9441's events Blastware downloaded,
the record occurs exactly once in the unit's own 5A replies, and the trigger
equals the unit's separate 0C record; SFM-only downloads carry it too;
* on 7,935 waveforms (DL2 + prod store) exactly one candidate validates, its
trigger equals Blastware's report (1,320/1,320) and filename (7,935/7,935);
* the footer-only estimate (stop minus record time) is a second off on ~19%.
A filename is never a time source -- an event SFM receives itself has none --
only a cross-check, logged when it disagrees.
"""
from __future__ import annotations
import datetime
import logging
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.blastware_file import blastware_filename_time # noqa: E402
from minimateplus.bw_ascii_report import BwAsciiReport # noqa: E402
from minimateplus.event_file_io import (apply_report_to_event, # noqa: E402
decode_blastware_bytes, read_blastware_file)
FIX = Path(__file__).parent / "fixtures"
ZI0 = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOF.ZI0"
ORACLE = sorted((FIX / "fft-oracle-2026-09-14").glob("N844*W"))
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H"
TRIGGER = datetime.datetime(2026, 10, 26, 14, 23, 42) # the unit's 0C record; the record
ESTIMATE = datetime.datetime(2026, 10, 26, 14, 23, 43) # footer stop minus record time
def _dt(ts):
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
def _record_at(raw: bytes) -> int:
return raw.rfind(b"\xfe\x80")
def _decode(raw: bytes, **kw):
ev = decode_blastware_bytes(bytes(raw), **kw)
return _dt(ev.timestamp), ev.timestamp_source, ev.decode_problems
# -- no filename at all --------------------------------------------------------
def test_raw_bytes_with_no_name_give_the_instruments_trigger():
assert _decode(ZI0.read_bytes()) == (TRIGGER, "event_record", [])
def test_the_name_changes_nothing():
assert _dt(read_blastware_file(ZI0).timestamp) == TRIGGER
assert _decode(ZI0.read_bytes(), name="upload.bw")[:2] == (TRIGGER, "event_record")
@pytest.mark.parametrize("path", ORACLE, ids=lambda p: p.name)
def test_every_oracle_waveform_decodes_from_bytes_alone_to_blastwares_time(path):
# BE12844's seven, Blastware's exact times (the fft-oracle reports)
t, source, problems = _decode(path.read_bytes())
assert (t, source, problems) == (blastware_filename_time(path.name), "event_record", [])
# -- the filename is a cross-check ---------------------------------------------
def test_a_disagreeing_filename_is_logged_and_the_record_wins(caplog):
# K441LTOF.ZJ0 is a valid Blastware name one second later
with caplog.at_level(logging.WARNING):
t, source, _ = _decode(ZI0.read_bytes(), name="K441LTOF.ZJ0")
assert (t, source) == (TRIGGER, "event_record")
assert any("14:23:42" in r.message and "14:23:43" in r.message for r in caplog.records)
def test_an_agreeing_filename_logs_nothing(caplog):
with caplog.at_level(logging.WARNING):
_decode(ZI0.read_bytes(), name=ZI0.name)
assert not [r for r in caplog.records if "filename" in r.message]
# -- validation: anything less than one clean candidate is a decode problem ---
def _session_starts_after_trigger(raw: bytearray, i: int) -> None:
# only this rule breaks: the footer's ts1 becomes the record's trigger + 1 s
f = len(raw) - 26
raw[f + 2:f + 10] = raw[i + 2:i + 10]
raw[f + 9] += 1
def _broken(edit) -> bytearray:
raw = bytearray(ZI0.read_bytes())
edit(raw, _record_at(raw))
return raw
@pytest.mark.parametrize("why,edit", [
("lead bytes", lambda r, i: r.__setitem__(i - 5, 0x29)), # 00 28 05 00 -> 00 29 ..
("marker", lambda r, i: r.__setitem__(i + 1, 0x81)),
("trigger zero byte", lambda r, i: r.__setitem__(i + 6, 0x01)),
("impossible date", lambda r, i: r.__setitem__(i + 3, 13)), # month 13
("stop far from the footer's", lambda r, i: r.__setitem__(i + 17, r[i + 17] - 5)),
("trigger before the session start", lambda r, i: _session_starts_after_trigger(r, i)),
], ids=lambda x: x if isinstance(x, str) else "")
def test_a_record_that_fails_validation_is_a_decode_problem_not_a_filename(why, edit, caplog):
with caplog.at_level(logging.WARNING):
t, source, problems = _decode(_broken(edit), name=ZI0.name) # a valid name is right there
assert (t, source) == (ESTIMATE, "estimate") # never the name's time
assert problems and "event record" in problems[0]
assert any("event record" in r.message for r in caplog.records)
def test_two_records_that_both_validate_are_not_guessed_between():
def dup(raw, i):
footer = len(raw) - 26
raw[footer - 24:footer] = raw[i - 6:i + 18] # a second, identical candidate
t, source, problems = _decode(_broken(dup))
assert source == "estimate" and "2 candidates" in problems[0]
# -- reports and histograms ----------------------------------------------------
def test_a_report_does_not_override_the_instruments_record(caplog):
ev = decode_blastware_bytes(ZI0.read_bytes())
with caplog.at_level(logging.WARNING):
apply_report_to_event(ev, BwAsciiReport(event_datetime=datetime.datetime(2026, 10, 26, 14, 23, 40)))
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "event_record")
assert any("14:23:40" in r.message for r in caplog.records)
def test_a_report_fills_in_when_the_record_is_missing():
ev = decode_blastware_bytes(bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))))
apply_report_to_event(ev, BwAsciiReport(event_datetime=TRIGGER))
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report")
def test_a_histogram_keeps_its_footer_start_for_now():
# Its record (marker fe f5) also holds Blastware's start -- that change is #51.
ev = read_blastware_file(HISTOGRAM)
assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 50), "footer")
def test_the_sidecar_keeps_the_instruments_time_and_says_where_it_came_from():
from minimateplus.event_file_io import event_to_sidecar_dict
ev = decode_blastware_bytes(ZI0.read_bytes())
car = event_to_sidecar_dict(ev, serial="BE9441", blastware_filename="K441LTOF.ZI0",
blastware_filesize=0, blastware_sha256="", source_kind="bw-import",
bw_report=BwAsciiReport(event_datetime=datetime.datetime(2026, 10, 26, 14, 23, 40)))
assert (car["event"]["timestamp"], car["event"]["timestamp_source"]) == \
("2026-10-26T14:23:42", "event_record")
assert "decode_problems" not in car["event"]
def test_a_sidecar_carries_the_decode_problem():
from minimateplus.event_file_io import event_to_sidecar_dict
ev = decode_blastware_bytes(bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))))
car = event_to_sidecar_dict(ev, serial="BE9441", blastware_filename="K441LTOF.ZI0",
blastware_filesize=0, blastware_sha256="", source_kind="bw-import")
assert car["event"]["timestamp_source"] == "estimate"
assert "event record" in car["event"]["decode_problems"][0]
def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbour(tmp_path, caplog):
import sqlite3
from minimateplus.models import Event, PeakValues, Timestamp
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
other = Event(index=0) # a different event at 14:23:43
other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
hour=14, minute=23, second=43)
other._waveform_key = bytes.fromhex("01110000")
other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
db.insert_events([other], serial="BE9441", device_family="series3",
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
assert (_dt(ev.timestamp), ev.timestamp_source) == (ESTIMATE, "estimate")
with caplog.at_level(logging.WARNING):
assert db.insert_events([ev], serial="BE9441", device_family="series3",
waveform_records={ev._waveform_key.hex(): rec}) == (0, 1)
with sqlite3.connect(str(db.db_path)) as c:
assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \
[("K441LTOF.ZJ0H", 0.04)]
assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept
assert any("not merged" in r.message for r in caplog.records)
+109
View File
@@ -0,0 +1,109 @@
"""The Blastware filename's time: a cross-check on the decoded time, never its source.
A Blastware name encodes the event time to the second (stem + AB, see
`blastware_filename`) -- Blastware's own copy of the unit's trigger. The decoder
reads the time from the instrument's embedded event record instead (see
test_bw_event_record_time.py); an event SFM receives itself has no name.
Measured 2026-10-26:
* name == the report's Event Time on 81/81 prod-snapshot and 1,249/1,249 DL2
report-paired waveforms;
* the binary's trigger (ts2 - record time) is a second off on 260 of prod's
1,394 waveforms (199 late, 61 early). On BE9558 the 61 early ones land on
their histogram twin's second, and events is unique on (serial, timestamp):
a fresh import wrote each waveform over its histogram's row.
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 in Blastware's timing a
waveform and its histogram share a second 209 times in prod's store, which a
(serial, timestamp) key cannot hold. That correction needs the key changed.
"""
from __future__ import annotations
import datetime
import os
import sqlite3
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.blastware_file import blastware_filename, blastware_filename_time # noqa: E402
from minimateplus.event_file_io import read_blastware_file # noqa: E402
from minimateplus.models import Event, PeakValues, Timestamp # noqa: E402
from sfm.database import SeismoDb # noqa: E402
from sfm.waveform_store import WaveformStore # noqa: E402
FIX = Path(__file__).parent / "fixtures"
ZI0 = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOF.ZI0"
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H"
def _dt(ts):
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
def test_names_decode_to_the_documented_times():
# the three S353L4H0 events the encoder was verified against, plus an H
assert blastware_filename_time("S353L4H0.3M0W") == datetime.datetime(2025, 6, 23, 13, 57, 22)
assert blastware_filename_time("S353L4H0.8S0H") == datetime.datetime(2025, 6, 23, 14, 0, 28)
assert blastware_filename_time("S353L4H0.9X0W") == datetime.datetime(2025, 6, 23, 14, 1, 9)
assert blastware_filename_time("P036L318.C80H") == datetime.datetime(2025, 5, 26, 15, 0, 8)
assert blastware_filename_time("K441LTOF.ZI0") == datetime.datetime(2026, 10, 26, 14, 23, 42)
assert blastware_filename_time("k441ltof.zi0") == datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_the_decoder_inverts_the_encoder():
for t in (datetime.datetime(2018, 1, 2, 3, 4, 5), datetime.datetime(2026, 10, 26, 23, 59, 59),
datetime.datetime(2026, 2, 28, 0, 0, 0)):
ev = Event(index=0)
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=t.year, unknown_byte=0, month=t.month,
day=t.day, hour=t.hour, minute=t.minute, second=t.second)
assert blastware_filename_time(blastware_filename(ev, "BE9441")) == t
assert blastware_filename_time(blastware_filename(ev, "BE9441", ach=True)) == t
def test_other_names_give_nothing():
for name in ("imported.bw", "UM12947_20260406130113.IDFW", "K441LTOF.ZI1", "K441LTOF.ZI0X",
"K441LTO.ZI0", "K441LTOF.Z!0", "", "BE9441.MLG"):
assert blastware_filename_time(name) is None, name
def test_a_waveform_decodes_to_the_time_its_name_encodes():
# BE9441, 2026-10-26: the footer estimate says 14:23:43; the event record, the
# unit's 0C record and the name all say 14:23:42
assert _dt(read_blastware_file(ZI0).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_a_waveform_read_under_another_name_keeps_its_time(tmp_path):
tmp = tmp_path / "upload.bw"
tmp.write_bytes(ZI0.read_bytes())
assert _dt(read_blastware_file(tmp).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42)
assert _dt(read_blastware_file(tmp, name=ZI0.name).timestamp) == \
datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_a_histogram_keeps_the_binarys_window_start():
assert blastware_filename_time(HISTOGRAM.name) != datetime.datetime(2026, 5, 10, 19, 4, 50)
assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 50)
def test_an_import_no_longer_lands_a_waveform_on_its_histogram_twins_row(tmp_path):
"""BE9558's 61: the binary's second was the histogram twin's. Built here from
BE9441's ZI0: a histogram row at the binary's 14:23:43, then the waveform."""
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
hist = Event(index=0)
hist.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
hour=14, minute=23, second=43)
hist._waveform_key = bytes.fromhex("01110000")
hist.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
db.insert_events([hist], serial="BE9441", device_family="series3",
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
ev, rec = store.save_imported_bw(ZI0.read_bytes(), source_path=Path(ZI0.name))
db.insert_events([ev], serial="BE9441", device_family="series3",
waveform_records={ev._waveform_key.hex(): rec})
with sqlite3.connect(str(db.db_path)) as c:
rows = c.execute("SELECT blastware_filename, timestamp FROM events ORDER BY timestamp").fetchall()
assert rows == [("K441LTOF.ZI0", "2026-10-26T14:23:42"), ("K441LTOF.ZJ0H", "2026-10-26T14:23:43")]
-244
View File
@@ -1,244 +0,0 @@
"""DeviceAccess: dispatch by serial, sessions, the lock, the reaper -- and the
contract that both series answer in the same shape."""
from __future__ import annotations
import dataclasses
import os
import sys
import threading
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
import micromate.protocol as mm_proto # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
BadRequest, CallHomeInProgress, ConnectFailed, UnitBusy, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s4 import RingDetected # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
class Clock:
def __init__(self, t=1000.0):
self.t = t
def __call__(self):
return self.t
def access(s3=(), s4=(), clock=None, lock_timeout=0.2):
s3q, s4q = list(s3), list(s4)
return DeviceAccess(
s3_client_factory=lambda a: s3q.pop(0),
s4_client_factory=lambda a: s4q.pop(0),
clock=clock or Clock(), lock_timeout=lock_timeout, start_reaper=False,
)
def test_the_serial_prefix_picks_the_adapter():
da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()])
assert da.identify(ADDR, "be18193").series == 3
assert da.identify(ADDR, " um20147").series == 4
def test_an_unknown_prefix_never_touches_a_unit():
da = access()
with pytest.raises(BadRequest):
da.identify(ADDR, "XX123")
def test_a_micromate_stays_on_the_line_between_requests():
fake = FakeMicromateClient()
da = access(s4=[fake])
da.identify(ADDR, "UM20147")
da.status(ADDR, "UM20147")
da.settings(ADDR, "UM20147")
assert fake.opened == 1 # one call-up, three requests
assert fake.calls[0] == "connect"
def test_a_minimate_reconnects_per_request():
a, b = FakeMiniMateClient(), FakeMiniMateClient()
da = access(s3=[a, b])
da.status(ADDR, "BE18193")
da.status(ADDR, "BE18193")
assert a.closed == 1 and b.closed == 1
def test_a_dropped_line_is_called_up_again_quietly():
first, second = FakeMicromateClient(), FakeMicromateClient()
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first._open = False # the modem dropped the idle line
st = da.status(ADDR, "UM20147")
assert st.series == 4 and second.opened == 1
def test_a_different_serial_at_a_held_address_is_refused_without_io():
first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947")
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
with pytest.raises(WrongUnit, match="hangup"):
da.status(ADDR, "UM12947")
assert first.closed == 0 and second.opened == 0
assert da.held_serial(ADDR) == "UM20147"
def test_a_different_serial_replaces_a_session_that_is_no_longer_open():
first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947")
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first.close()
da.status(ADDR, "UM12947")
assert second.opened == 1
def test_a_busy_unit_answers_423_without_a_second_connection():
fake = FakeMicromateClient()
da = access(s4=[fake], lock_timeout=0.2)
entered, release = threading.Event(), threading.Event()
def slow_request():
with da._locks.hold(ADDR.key): # simulate a request in flight
entered.set()
release.wait(2)
t = threading.Thread(target=slow_request)
t.start()
entered.wait(2)
try:
with pytest.raises(UnitBusy):
da.status(ADDR, "UM20147")
assert fake.opened == 0 # no second connection was opened
finally:
release.set()
t.join()
def test_hang_up_closes_a_held_line():
fake = FakeMicromateClient()
da = access(s4=[fake])
da.status(ADDR, "UM20147")
assert da.hang_up(ADDR) is True
assert fake.closed == 1
assert da.hang_up(ADDR) is False # nothing left to hang up
def test_a_peer_dropped_line_that_still_reads_open_is_retried_once():
first, second = FakeMicromateClient(), FakeMicromateClient()
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first.fail = [mm_proto.TimeoutError("quiet")] # _open untouched: looks open
st = da.status(ADDR, "UM20147")
assert st.series == 4 and first.closed == 1 and second.opened == 1
def test_a_failed_fresh_call_up_is_not_retried():
da = access(s4=[FakeMicromateClient(open_error=ConnectionRefusedError("no"))])
with pytest.raises(ConnectFailed):
da.status(ADDR, "UM20147") # a 2nd attempt would pop an empty queue
def test_a_ring_on_a_held_line_is_not_retried():
first, second = FakeMicromateClient(), FakeMicromateClient()
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress):
da.status(ADDR, "UM20147")
assert second.opened == 0
def test_series3_beside_a_held_series4_line_is_refused_without_io():
micro, mini = FakeMicromateClient(), FakeMiniMateClient()
da = access(s3=[mini], s4=[micro])
da.status(ADDR, "UM20147")
with pytest.raises(WrongUnit):
da.status(ADDR, "BE18193")
assert mini.opened == 0 and micro.closed == 0 and micro.is_open()
# ── the reaper ────────────────────────────────────────────────────────────────
def test_tick_listens_then_keeps_alive_then_hangs_up_when_idle():
clock = Clock(1000.0)
fake = FakeMicromateClient()
da = access(s4=[fake], clock=clock)
da.status(ADDR, "UM20147")
fake.calls.clear()
clock.t = 1030.0
da.tick() # quiet: listen only
assert fake.calls == ["read_unsolicited"]
clock.t = 1061.0
da.tick() # 60 s since traffic: keep-alive
assert fake.calls[-1] == "poll"
clock.t = 1301.0
da.tick() # 300 s since last USE: hang up
assert fake.closed == 1
assert da.hang_up(ADDR) is False
def test_tick_releases_the_line_on_a_ring_while_idle():
clock = Clock(1000.0)
fake = FakeMicromateClient()
da = access(s4=[fake], clock=clock)
da.status(ADDR, "UM20147")
fake.fail = [RingDetected("RADIO RING")]
clock.t = 1010.0
da.tick()
assert fake.closed == 1
def test_tick_skips_a_unit_that_is_busy():
clock = Clock(1000.0)
fake = FakeMicromateClient()
da = access(s4=[fake], clock=clock)
da.status(ADDR, "UM20147")
fake.calls.clear()
clock.t = 1400.0
with da._locks.hold(ADDR.key):
da.tick() # must not block or hang up mid-request
assert fake.calls == [] and fake.closed == 0
def test_a_ring_mid_request_is_a_clear_error():
fake = FakeMicromateClient()
da = access(s4=[fake])
da.status(ADDR, "UM20147")
fake.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress):
da.status(ADDR, "UM20147")
# ── the contract: both series answer in the same shape ────────────────────────
@pytest.mark.parametrize("op", ["identify", "status", "settings"])
def test_both_series_return_the_same_model_with_the_same_fields(op):
da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()])
s3 = getattr(da, op)(ADDR, "BE18193")
s4 = getattr(da, op)(ADDR, "UM20147")
assert type(s3) is type(s4)
assert [f.name for f in dataclasses.fields(s3)] == [f.name for f in dataclasses.fields(s4)]
assert (s3.series, s4.series) == (3, 4)
for name in (f.name for f in dataclasses.fields(s3)):
a, b = getattr(s3, name), getattr(s4, name)
if a is not None and b is not None and name != "detail":
assert type(a) is type(b) or {type(a), type(b)} <= {int, float}, name
def test_held_serial_reports_an_open_line_only():
fake = FakeMicromateClient()
da = access(s4=[fake])
assert da.held_serial(ADDR) is None
da.status(ADDR, "UM20147")
assert da.held_serial(ADDR) == "UM20147"
da.hang_up(ADDR)
assert da.held_serial(ADDR) is None
-799
View File
@@ -1,799 +0,0 @@
"""Start/stop through the safety layer: identity, state, dry run, audit, read-back, no retry."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import micromate.protocol as mm_proto # noqa: E402
from micromate.opcodes import OpcodeRefused # noqa: E402
from sfm.device_access.s4 import RingDetected # noqa: E402
from device_access_fakes import FakeMicromateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, ConnectFailed, DeviceError,
NoAnswer, NotSupported, UnitStateUnknown, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
class Audit:
def __init__(self):
self.rows = {}
def begin(self, **f):
cid = f"c{len(self.rows) + 1}"
self.rows[cid] = dict(f, outcome="pending")
return cid
def finish(self, cid, **f):
self.rows[cid].update(f)
def access(fake, audit="default"):
return DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False,
audit=Audit() if audit == "default" else audit,
sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0)
def unconfirmed(excinfo, da, *, sent, status):
"""A failure after the send: it names the one audit row, says a frame went
out (or may have), and carries its cause's status. Returns the row."""
((cid, row),) = da._audit.rows.items()
e = excinfo.value
assert (e.audit_id, e.sent, e.http_status) == (cid, sent, status)
assert f"audit record {cid}" in str(e)
assert "was sent" in str(e) and "nothing sent" not in str(e)
return row
def released(fake, da):
return fake.is_open() is False and ADDR.key not in da._sessions
def test_a_dry_run_returns_the_exact_frames_and_sends_nothing():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147", dry_run=True)
assert (r.dry_run, r.sent, r.outcome, r.state_before) == (True, False, "dry_run", "idle")
assert r.plan["steps"][0]["frame"] == "41021010009600ffff00000000000000000000a403"
assert r.plan["sends_nothing"] is True
assert fake.executed == [] and da._audit.rows == {}
def test_start_sends_once_and_verifies_by_reading_back():
fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.sent, r.outcome, r.verified, r.state_after) == (True, "sent", "ok", "monitoring")
assert len(fake.executed) == 1
row = da._audit.rows[r.audit_id]
assert (row["outcome"], row["verified"], row["action"]) == ("sent", "ok", "start monitoring")
assert r.detail["states_seen"] == ["idle", "idle", "monitoring"]
assert r.plan["sends_nothing"] is False
assert row["request"]["plan"]["sends_nothing"] is False
def test_already_in_state_is_skipped_and_audited_as_skipped():
fake = FakeMicromateClient(run_states=[0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.sent, r.outcome) == (False, "skipped") and fake.executed == []
assert da._audit.rows[r.audit_id]["outcome"] == "skipped"
def test_even_if_already_sends_anyway():
fake = FakeMicromateClient(run_states=[0x02])
r = access(fake).start_monitoring(ADDR, "UM20147", even_if_already=True)
assert r.sent and len(fake.executed) == 1
def test_a_unit_calling_home_is_refused_and_nothing_is_sent():
fake = FakeMicromateClient(run_states=[0x03])
da = access(fake)
with pytest.raises(CallHomeInProgress):
da.stop_monitoring(ADDR, "UM20147")
assert fake.executed == []
assert fake.is_open() is False # the line was released for THOR
assert da.held_serial(ADDR) is None # and the session dropped
assert ADDR.key not in da._sessions
def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing():
fake = FakeMicromateClient(serial_reported="UM12947")
da = access(fake)
with pytest.raises(WrongUnit):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == []
assert fake.is_open() is False
assert da.held_serial(ADDR) is None
assert ADDR.key not in da._sessions
def test_a_live_change_without_an_audit_sink_is_refused():
fake = FakeMicromateClient()
with pytest.raises(NotSupported, match="audit"):
access(fake, audit=None).start_monitoring(ADDR, "UM20147")
assert fake.executed == [] and fake.opened == 0 and fake.calls == []
def test_a_clean_ack_but_no_state_change_is_a_failed_change():
fake = FakeMicromateClient(run_states=[0x00]) # never leaves idle
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle")
assert len(r.detail["states_seen"]) == 4 # 6 s window / 2 s + the first read
assert da._audit.rows[r.audit_id]["verified"] == "mismatch"
assert da._audit.rows[r.audit_id]["outcome"] == "failed"
def test_a_lost_ack_is_recorded_once_and_not_resent():
fake = FakeMicromateClient(run_states=[0x00, 0x02],
execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert len(fake.executed) == 1
assert (r.outcome, r.state_after) == ("failed", "monitoring")
assert "no ack" in r.detail["error"]
assert da._audit.rows[r.audit_id]["outcome"] == "failed"
def test_a_change_on_a_dropped_held_line_is_not_retried():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
da.status(ADDR, "UM20147") # hold the line
fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails
with pytest.raises(Exception):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == [] # never reached the write, never re-tried
def test_a_read_back_that_fails_still_finishes_the_audit_row():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
orig = fake.read_run_state
calls = []
def flaky():
calls.append(1)
if len(calls) == 2: # the first read-back
raise mm_proto.TimeoutError("dropped")
return orig()
fake.read_run_state = flaky
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="acknowledged", status=504)
assert "sent and acknowledged" in str(e.value) and "dropped" in str(e.value)
assert len(fake.executed) == 1
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
assert row["ack"] is not None
assert "reading the state back failed" in row["error"]
assert row["sent"] == 1
assert fake.is_open() is False and ADDR.key not in da._sessions
def test_a_ring_in_place_of_the_ack_is_a_call_home_not_a_send():
fake = FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING"))
da = access(fake)
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="unknown", status=503)
assert "hung up so the call can reach THOR" in str(e.value)
assert "whether it started is unknown" in str(e.value)
assert len(fake.executed) == 1
assert fake.is_open() is False and ADDR.key not in da._sessions
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
assert "call-home began in place of the ack" in row["error"]
assert row["sent"] is None
def test_calling_home_seen_while_polling_releases_the_line():
fake = FakeMicromateClient(run_states=[0x00, 0x03])
da = access(fake)
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="acknowledged", status=503)
assert "hung up so the call can reach THOR" in str(e.value)
assert len(fake.executed) == 1
assert fake.calls.count("read_run_state") == 2 # the read before + the one poll
assert fake.is_open() is False and ADDR.key not in da._sessions
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
assert row["ack"] is not None
assert row["sent"] == 1
assert row["states"] == {"before": "idle", "seen": ["idle", "calling_home"],
"after": "calling_home"}
def test_calling_home_after_a_lost_ack_releases_the_line():
fake = FakeMicromateClient(run_states=[0x00, 0x03],
execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="unknown", status=503)
assert "acknowledgement was lost" in str(e.value)
assert "whether it started is unknown" in str(e.value)
assert "hung up so the call can reach THOR" in str(e.value)
assert fake.is_open() is False and ADDR.key not in da._sessions
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
assert row["sent"] is None
assert row["states"] == {"before": "idle", "seen": ["idle"], "after": "calling_home"}
def test_a_refusal_by_execute_is_not_a_send():
fake = FakeMicromateClient(execute_error=OpcodeRefused("nope"))
da = access(fake)
with pytest.raises(DeviceError, match="nope"):
da.start_monitoring(ADDR, "UM20147")
(row,) = da._audit.rows.values()
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
assert "refused before sending" in row["error"]
def test_a_failed_audit_write_sends_nothing():
class Broken(Audit):
def begin(self, **f):
raise OSError("disk full")
fake = FakeMicromateClient()
with pytest.raises(AuditUnavailable):
access(fake, audit=Broken()).start_monitoring(ADDR, "UM20147")
assert fake.executed == []
def test_lost_ack_and_failed_follow_up_read_on_a_held_line_releases_it():
fake = FakeMicromateClient(run_states=[0x00], execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
da.status(ADDR, "UM20147") # hold the line
orig, n = fake.read_run_state, []
def flaky():
n.append(1)
if len(n) == 2: # the follow-up after the lost ack
raise mm_proto.TimeoutError("gone")
return orig()
fake.read_run_state = flaky
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="unknown", status=504)
assert "acknowledgement was lost" in str(e.value) and "gone" in str(e.value)
assert len(fake.executed) == 1
assert fake.is_open() is False and ADDR.key not in da._sessions
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", None)
def test_a_live_change_in_an_unmeasured_state_is_refused_but_a_dry_run_is_not():
fake = FakeMicromateClient(run_states=[0x07])
da = access(fake)
with pytest.raises(UnitStateUnknown):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == [] and da._audit.rows == {}
r = da.start_monitoring(ADDR, "UM20147", dry_run=True)
assert r.state_before == "unknown(0x07)"
def test_bad_verify_timings_are_rejected():
with pytest.raises(ValueError):
DeviceAccess(start_reaper=False, verify_interval_s=0)
with pytest.raises(ValueError):
DeviceAccess(start_reaper=False, verify_interval_s=5, verify_timeout_s=2)
def test_a_ring_on_the_follow_up_read_after_a_lost_ack_finishes_the_row():
fake = FakeMicromateClient(run_states=[0x00], execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
orig, n = fake.read_run_state, []
def ringing():
n.append(1)
if len(n) == 2: # the first follow-up read
raise RingDetected("RADIO RING")
return orig()
fake.read_run_state = ringing
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="unknown", status=503)
assert "hung up so the call can reach THOR" in str(e.value)
assert len(fake.executed) == 1
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
assert "a call-home began" in row["error"]
assert row["sent"] is None
assert fake.is_open() is False and ADDR.key not in da._sessions
def test_a_type_error_after_sending_is_recorded_as_no_clean_ack():
fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=TypeError("parser bug"))
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert len(fake.executed) == 1 and r.sent is True
assert "no clean ack" in da._audit.rows[r.audit_id]["error"]
assert "refused before sending" not in da._audit.rows[r.audit_id]["error"]
def test_a_malformed_serial_is_422_even_without_an_audit_sink():
from sfm.device_access.errors import BadRequest
with pytest.raises(BadRequest):
access(FakeMicromateClient(), audit=None).start_monitoring(ADDR, "XX123")
# ── Series 3 ──────────────────────────────────────────────────────────────────
import minimateplus.protocol as mmp_proto # noqa: E402
from device_access_fakes import FakeMiniMateClient # noqa: E402
TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
def access3(fake, audit="default", sleep=lambda s: None):
seen = []
def factory(a, **kw):
seen.append(kw)
return fake
da = DeviceAccess(s3_client_factory=factory, start_reaper=False,
audit=Audit() if audit == "default" else audit,
sleep=sleep, verify_timeout_s=6.0, verify_interval_s=2.0)
da.factory_calls = seen
return da
def test_series3_dry_run_returns_its_own_frame_and_sends_nothing():
fake = FakeMiniMateClient(monitor_states=[False])
r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True)
assert (r.series, r.outcome, r.state_before) == (3, "dry_run", "idle")
assert r.plan["steps"][0]["sub"] == "0x96" and fake.writes == []
assert r.plan["steps"][0]["expect_ack"] == "0x69" and r.plan["sends_nothing"] is True
assert r.plan["steps"][0]["frame"] == "41021010009600000000000000000000000000a603"
stop = access3(FakeMiniMateClient(monitor_states=[True])).stop_monitoring(
TCP3, "BE18193", dry_run=True)
assert stop.plan["steps"][0]["frame"] == "41021010009700000000000000000000000000a703"
assert stop.plan["steps"][0]["expect_ack"] == "0x68" and stop.outcome == "dry_run"
def test_series3_start_is_verified_by_monitor_status():
fake = FakeMiniMateClient(monitor_states=[False, False, True])
da = access3(fake)
r = da.start_monitoring(TCP3, "BE18193")
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring")
assert fake.writes == ["start_monitoring"]
assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x69"]}
assert da.factory_calls == [{"timeout": 120.0}]
def test_series3_stop_acks_0x68():
fake = FakeMiniMateClient(monitor_states=[True, False])
da = access3(fake)
r = da.stop_monitoring(TCP3, "BE18193")
assert r.verified == "ok" and fake.writes == ["stop_monitoring"]
assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x68"]}
def test_series3_wrong_unit_is_refused_before_writing():
fake = FakeMiniMateClient(serial="BE11529")
with pytest.raises(WrongUnit):
access3(fake).stop_monitoring(TCP3, "BE18193")
assert fake.writes == []
def test_series3_a_lost_ack_with_a_good_read_back_is_one_write():
fake = FakeMiniMateClient(monitor_states=[False, True],
write_error=mmp_proto.TimeoutError("no ack"))
da = access3(fake)
r = da.start_monitoring(TCP3, "BE18193")
assert fake.writes == ["start_monitoring"] # one send, no cold-boot retry
assert r.outcome == "failed" and r.state_after == "monitoring"
def test_series3_already_in_state_is_skipped():
fake = FakeMiniMateClient(monitor_states=[True])
da = access3(fake)
r = da.start_monitoring(TCP3, "BE18193")
assert (r.sent, r.outcome) == (False, "skipped") and fake.writes == []
assert da._audit.rows[r.audit_id]["outcome"] == "skipped"
def test_series3_a_state_that_never_changes_is_a_mismatch():
fake = FakeMiniMateClient(monitor_states=[False])
da = access3(fake)
r = da.start_monitoring(TCP3, "BE18193")
assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle")
assert da._audit.rows[r.audit_id]["verified"] == "mismatch"
def test_series3_a_failing_read_back_is_audited_then_raised():
fake = FakeMiniMateClient(monitor_states=[False])
da = access3(fake)
real = fake.get_monitor_status
calls = []
def flaky():
calls.append(1)
if len(calls) > 1:
raise mmp_proto.TimeoutError("quiet")
return real()
fake.get_monitor_status = flaky
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(TCP3, "BE18193")
row = unconfirmed(e, da, sent="acknowledged", status=504)
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
assert "reading the state back failed" in row["error"]
assert fake.writes == ["start_monitoring"]
def test_series3_audit_begin_failing_sends_nothing():
class Broken(Audit):
def begin(self, **f):
raise RuntimeError("disk full")
fake = FakeMiniMateClient(monitor_states=[False])
with pytest.raises(AuditUnavailable):
access3(fake, audit=Broken()).start_monitoring(TCP3, "BE18193")
assert fake.writes == []
def test_series3_lost_ack_with_unreadable_follow_up_raises_and_is_not_retried():
fake = FakeMiniMateClient(monitor_states=[False], write_error=mmp_proto.TimeoutError("no ack"))
da = access3(fake)
real = fake.get_monitor_status
n = []
def second_fails():
n.append(1)
if len(n) > 1:
raise mmp_proto.TimeoutError("still quiet")
return real()
fake.get_monitor_status = second_fails
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(TCP3, "BE18193")
row = unconfirmed(e, da, sent="unknown", status=504)
assert fake.writes == ["start_monitoring"]
assert len(da.factory_calls) == 1 # no second TCP attempt
assert row["outcome"] == "failed"
# The other Series-3 operations still retry once over TCP on a cold unit:
# tests/test_device_access_s3.py::test_a_cold_unit_over_tcp_gets_one_retry.
# ── final fix wave: after-send honesty, the audit row, pre-send ring, S3 states ──
from sfm.audit import DbAudit # noqa: E402
from sfm.database import SeismoDb # noqa: E402
def test_a_lost_stop_ack_then_a_call_home_says_whether_it_stopped_is_unknown():
fake = FakeMicromateClient(run_states=[0x02, 0x03],
execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
with pytest.raises(ChangeUnconfirmed) as e:
da.stop_monitoring(ADDR, "UM20147")
unconfirmed(e, da, sent="unknown", status=503)
assert str(e.value).startswith("stop monitoring was sent but the acknowledgement was lost")
assert "whether it stopped is unknown" in str(e.value)
assert released(fake, da)
def test_a_ring_on_a_read_back_poll_is_unconfirmed_and_releases_the_line():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
orig, n = fake.read_run_state, []
def ringing():
n.append(1)
if len(n) == 2: # the first read-back poll
raise RingDetected("RADIO RING")
return orig()
fake.read_run_state = ringing
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
row = unconfirmed(e, da, sent="acknowledged", status=503)
assert "hung up so the call can reach THOR" in str(e.value)
assert len(fake.executed) == 1
assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "not_checked", 1)
assert row["ack"] is not None and "call-home began" in row["error"]
assert released(fake, da)
def test_a_ring_already_waiting_before_the_send_sends_nothing():
fake = FakeMicromateClient(run_states=[0x00])
def buffered_ring():
fake.calls.append("read_unsolicited")
raise RingDetected("RADIO RING")
fake.read_unsolicited = buffered_ring
da = access(fake)
with pytest.raises(CallHomeInProgress) as e:
da.start_monitoring(ADDR, "UM20147")
assert not isinstance(e.value, ChangeUnconfirmed)
assert fake.executed == []
(row,) = da._audit.rows.values()
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", 0)
assert row["error"] == "a call-home began before sending -- nothing sent"
assert released(fake, da)
def test_the_pre_send_drain_runs_after_the_state_read_and_before_the_send():
fake = FakeMicromateClient(run_states=[0x00, 0x02])
access(fake).start_monitoring(ADDR, "UM20147")
assert fake.calls.index("read_unsolicited") > fake.calls.index("read_run_state")
assert fake.calls.index("read_unsolicited") < fake.calls.index("execute")
def test_a_skip_does_not_drain_the_line():
fake = FakeMicromateClient(run_states=[0x02])
access(fake).start_monitoring(ADDR, "UM20147")
assert "read_unsolicited" not in fake.calls
def test_a_link_fault_on_the_pre_send_drain_sends_nothing_and_finishes_the_row():
fake = FakeMicromateClient(run_states=[0x00])
def dead():
raise OSError("connection reset")
fake.read_unsolicited = dead
da = access(fake)
with pytest.raises(ConnectFailed):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == []
(row,) = da._audit.rows.values()
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", 0)
assert "nothing sent" in row["error"]
assert released(fake, da)
class FinishFails(Audit):
def finish(self, cid, **f):
raise OSError("disk full")
def test_a_finish_that_fails_after_a_verified_send_is_audit_incomplete_and_keeps_the_line():
fake = FakeMicromateClient(run_states=[0x00, 0x02])
da = access(fake, audit=FinishFails())
with pytest.raises(AuditIncomplete) as e:
da.start_monitoring(ADDR, "UM20147")
assert e.value.http_status == 500
assert "start monitoring was sent and verified" in str(e.value)
assert "audit record c1 could not be finished: disk full" in str(e.value)
assert len(fake.executed) == 1
assert fake.is_open() is True and da.held_serial(ADDR) == "UM20147"
def test_a_finish_that_fails_on_a_skip_says_nothing_was_sent():
fake = FakeMicromateClient(run_states=[0x02])
with pytest.raises(AuditIncomplete, match="nothing was sent .*already monitoring"):
access(fake, audit=FinishFails()).start_monitoring(ADDR, "UM20147")
assert fake.executed == []
def test_a_finish_that_fails_while_unconfirmed_keeps_the_unit_outcome():
fake = FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING"))
with pytest.raises(AuditIncomplete) as e:
access(fake, audit=FinishFails()).start_monitoring(ADDR, "UM20147")
assert "start monitoring was sent" in str(e.value)
assert "whether it started is unknown" in str(e.value)
assert "could not be finished: disk full" in str(e.value)
def test_even_if_already_notes_that_the_read_back_proves_nothing():
fake = FakeMicromateClient(run_states=[0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147", even_if_already=True)
note = ("the unit was already monitoring before sending; the read-back cannot show "
"that this send changed anything")
assert (r.outcome, r.verified) == ("sent", "ok")
assert r.detail["note"] == note
assert da._audit.rows[r.audit_id]["error"] == note
def test_without_even_if_already_there_is_no_note():
fake = FakeMicromateClient(run_states=[0x00, 0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert "note" not in r.detail and da._audit.rows[r.audit_id]["error"] is None
# -- the audit row records whether a frame went out, and the states, in the real DB
def db_access(fake, tmp_path):
db = SeismoDb(tmp_path / "s.db")
da = access(fake, audit=DbAudit(lambda: db))
return da, db
def test_db_row_for_a_skip_says_nothing_was_sent(tmp_path):
da, db = db_access(FakeMicromateClient(run_states=[0x02]), tmp_path)
da.start_monitoring(ADDR, "UM20147")
(row,) = db.query_device_commands()
assert (row["outcome"], row["sent"]) == ("skipped", 0)
assert row["states"] == {"before": "monitoring", "seen": ["monitoring"], "after": None}
def test_db_row_for_a_verified_send(tmp_path):
da, db = db_access(FakeMicromateClient(run_states=[0x00, 0x00, 0x02]), tmp_path)
da.start_monitoring(ADDR, "UM20147")
(row,) = db.query_device_commands()
assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "ok", 1)
assert row["states"] == {"before": "idle", "seen": ["idle", "idle", "monitoring"],
"after": "monitoring"}
def test_db_row_for_a_mismatch(tmp_path):
da, db = db_access(FakeMicromateClient(run_states=[0x00]), tmp_path)
da.start_monitoring(ADDR, "UM20147")
(row,) = db.query_device_commands()
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "mismatch", 1)
assert row["states"] == {"before": "idle", "seen": ["idle"] * 4, "after": "idle"}
def test_db_row_for_a_lost_ack_with_a_readable_follow_up(tmp_path):
fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=mm_proto.TimeoutError("no ack"))
da, db = db_access(fake, tmp_path)
da.start_monitoring(ADDR, "UM20147")
(row,) = db.query_device_commands()
assert (row["outcome"], row["sent"]) == ("failed", None)
assert row["states"] == {"before": "idle", "seen": ["idle"], "after": "monitoring"}
def test_db_row_for_a_read_back_failure(tmp_path):
fake = FakeMicromateClient(run_states=[0x00])
orig, n = fake.read_run_state, []
def flaky():
n.append(1)
if len(n) == 3: # the second read-back poll
raise mm_proto.TimeoutError("dropped")
return orig()
fake.read_run_state = flaky
da, db = db_access(fake, tmp_path)
with pytest.raises(ChangeUnconfirmed) as e:
da.start_monitoring(ADDR, "UM20147")
(row,) = db.query_device_commands()
assert e.value.audit_id == row["id"]
assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "not_checked", 1)
assert row["states"] == {"before": "idle", "seen": ["idle", "idle"], "after": "idle"}
def test_db_row_for_a_pre_send_ring_says_nothing_was_sent(tmp_path):
fake = FakeMicromateClient(run_states=[0x00])
def buffered_ring():
raise RingDetected("RADIO RING")
fake.read_unsolicited = buffered_ring
da, db = db_access(fake, tmp_path)
with pytest.raises(CallHomeInProgress):
da.start_monitoring(ADDR, "UM20147")
(row,) = db.query_device_commands()
assert (row["outcome"], row["sent"]) == ("failed", 0)
# -- Series 3: the raw state byte, never collapsed into "idle" ----------------------
def test_series3_an_unmeasured_state_byte_is_refused_with_nothing_written():
fake = FakeMiniMateClient(monitor_states=[0x07])
da = access3(fake)
with pytest.raises(UnitStateUnknown, match="0x07"):
da.start_monitoring(TCP3, "BE18193")
assert fake.writes == [] and da._audit.rows == {}
@pytest.mark.parametrize("flag,state", [(0x00, "idle"), (0x10, "monitoring"),
(0x07, "unknown(0x07)"), (None, "unknown(short)")])
def test_series3_state_names_come_from_the_raw_flag(flag, state):
fake = FakeMiniMateClient(monitor_states=[flag])
r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True)
assert r.state_before == state
@pytest.mark.parametrize("flag,monitoring", [(0x00, False), (0x10, True), (0x0B, True), (0x07, None)])
def test_series3_status_shows_the_change_paths_reading(flag, monitoring):
# 0x0B: BE9441 recording a histogram (2026-10-26) once showed "not monitoring"
st = access3(FakeMiniMateClient(monitor_states=[flag])).status(TCP3, "BE18193")
assert st.monitoring is monitoring
def test_series3_monitor_status_decode_keeps_the_raw_flag():
from minimateplus.client import _decode_monitor_status
tail = bytes.fromhex("02a8000effc0000e9e52") # battery + memory: the last 10 bytes
for flag, monitoring in ((0x00, False), (0x10, True), (0x0B, True), (0x07, False)):
st = _decode_monitor_status(bytes(11) + bytes([0x00, flag]) + bytes(34) + tail)
assert (st.state_flag, st.is_monitoring) == (flag, monitoring)
assert _decode_monitor_status(bytes(12)).state_flag is None # no section[1]
assert _decode_monitor_status(b"").state_flag is None
# ── an audit finish that fails must not turn a hang-up into a held line ───────
def _reads_then(fake, exc):
"""read_run_state answers once (the state before the send), then raises."""
orig, n = fake.read_run_state, []
def flaky():
n.append(1)
if len(n) > 1:
raise exc
return orig()
fake.read_run_state = flaky
return fake
def _drain_raises(fake, exc):
def drain():
raise exc
fake.read_unsolicited = drain
return fake
_LOST = mm_proto.TimeoutError("no ack")
_HANG_UP_PATHS = {
"ring in place of the ack":
lambda: FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING")),
"lost ack, ring on the follow-up":
lambda: _reads_then(FakeMicromateClient(run_states=[0x00], execute_error=_LOST),
RingDetected("RADIO RING")),
"lost ack, follow-up reads calling_home":
lambda: FakeMicromateClient(run_states=[0x00, 0x03], execute_error=_LOST),
"lost ack, follow-up unreadable":
lambda: _reads_then(FakeMicromateClient(run_states=[0x00], execute_error=_LOST),
mm_proto.TimeoutError("silent")),
"read-back raises":
lambda: _reads_then(FakeMicromateClient(run_states=[0x00]), mm_proto.TimeoutError("silent")),
"read-back rings":
lambda: _reads_then(FakeMicromateClient(run_states=[0x00]), RingDetected("RADIO RING")),
"read-back reads calling_home":
lambda: FakeMicromateClient(run_states=[0x00, 0x03]),
"ring before the send":
lambda: _drain_raises(FakeMicromateClient(run_states=[0x00]), RingDetected("RADIO RING")),
"link fault before the send":
lambda: _drain_raises(FakeMicromateClient(run_states=[0x00]), OSError("connection reset")),
"refused by execute":
lambda: FakeMicromateClient(run_states=[0x00], execute_error=OpcodeRefused("nope")),
}
@pytest.mark.parametrize("path", sorted(_HANG_UP_PATHS))
def test_a_finish_that_fails_on_a_hang_up_path_still_releases_the_line(path):
fake = _HANG_UP_PATHS[path]()
da = access(fake, audit=FinishFails())
with pytest.raises(AuditIncomplete) as e:
da.start_monitoring(ADDR, "UM20147")
assert e.value.release_line is True
assert "could not be finished: disk full" in str(e.value)
assert len(fake.executed) <= 1
assert released(fake, da)
def test_series3_a_cold_unit_during_a_change_is_not_retried():
fake = FakeMiniMateClient(fail=[mmp_proto.TimeoutError("cold")])
da = access3(fake)
with pytest.raises(NoAnswer):
da.start_monitoring(TCP3, "BE18193")
assert fake.writes == []
assert len(da.factory_calls) == 1 # the change path never takes _run's retry
# -- Series 3: a monitoring unit answers only after the wake ----------------------
def test_series3_wakes_the_unit_before_every_state_read():
# BE9441, 2026-10-26 23:41: the start was acked, then one bare 0x1C read got
# nothing for 120 s -- a monitoring unit ignores everything until SESSION_RESET
# + POLL (measured 2026-04-08), which only the connect had sent.
fake = FakeMiniMateClient(monitor_states=[False, True])
r = access3(fake).start_monitoring(TCP3, "BE18193")
assert r.outcome == "sent" and r.verified == "ok"
after = fake.calls[fake.calls.index("start_monitoring") + 1:]
reads = [i for i, c in enumerate(after) if c == "get_monitor_status"]
assert reads and all(after[i - 1] == "wake" for i in reads)
def test_series3_a_start_waits_out_the_sensor_check_before_its_first_read():
# Brian (2026-10-26): every unit runs a ~30 s sensor check before
# "Recording..."; a stop's read-back needs no such wait.
from sfm.device_access.s3 import S3_SENSOR_CHECK_S
for start, waited in ((True, True), (False, False)):
slept = []
fake = FakeMiniMateClient(monitor_states=[not start, start])
da = access3(fake, sleep=slept.append)
(da.start_monitoring if start else da.stop_monitoring)(TCP3, "BE18193")
assert (S3_SENSOR_CHECK_S in slept) is waited
-138
View File
@@ -1,138 +0,0 @@
"""Core types of sfm.device_access: errors, series selection, models."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import micromate.protocol as mm_proto # noqa: E402
import minimateplus.protocol as mmp_proto # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
BadRequest, ConnectFailed, DeviceError, MalformedReply, NoAnswer, translate,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.series import normalise_serial, series_for_serial # noqa: E402
# ── series ────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize(
"serial, series",
[("UM20147", 4), ("BE18193", 3), ("BA4521", 3), (" um20147 ", 4), ("be11529", 3)],
)
def test_the_prefix_picks_the_series(serial, series):
assert series_for_serial(serial) == series
def test_serials_are_normalised():
assert normalise_serial(" um20147\n") == "UM20147"
@pytest.mark.parametrize("serial", ["", "UM", "XX12345", "12345", "MP1234"])
def test_an_unknown_or_bare_prefix_is_a_bad_request(serial):
with pytest.raises(BadRequest, match="UM"):
series_for_serial(serial)
# ── errors ────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize(
"exc, connecting, cls, status",
[
(mm_proto.TimeoutError("no frame"), False, NoAnswer, 504),
(mmp_proto.TimeoutError("no frame"), False, NoAnswer, 504),
(mm_proto.ChecksumError("bad"), False, MalformedReply, 502),
(mmp_proto.ProtocolError("bad"), False, MalformedReply, 502),
(ConnectionRefusedError("refused"), True, ConnectFailed, 503),
(OSError("reset"), False, ConnectFailed, 503),
],
)
def test_library_exceptions_translate_to_typed_errors(exc, connecting, cls, status):
out = translate(exc, connecting=connecting)
assert isinstance(out, cls)
assert out.http_status == status
def test_connect_and_mid_session_failures_read_differently():
assert "could not connect" in str(translate(OSError("x"), connecting=True))
assert "connection lost" in str(translate(OSError("x"), connecting=False))
def test_a_device_error_passes_through_unchanged():
e = NoAnswer("quiet")
assert translate(e, connecting=False) is e
def test_anything_else_becomes_a_plain_device_error():
out = translate(ValueError("boom"), connecting=False)
assert type(out) is DeviceError and out.http_status == 500
# ── models ────────────────────────────────────────────────────────────────────
def test_an_address_needs_a_host_or_a_port():
with pytest.raises(BadRequest):
UnitAddress(host=None, tcp_port=None, port=None, baud=None)
def test_the_lock_key_names_the_physical_link():
assert UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None).key == "tcp:10.0.0.5:9034"
assert UnitAddress(host=None, tcp_port=None, port="/dev/ttyACM0", baud=115200).key == "serial:/dev/ttyACM0"
# ── per-unit lock ─────────────────────────────────────────────────────────────
import threading # noqa: E402
from sfm.device_access.errors import UnitBusy # noqa: E402
from sfm.device_access.locks import UnitLocks # noqa: E402
def test_a_second_request_for_a_busy_unit_gets_unit_busy():
locks = UnitLocks(timeout=0.2)
entered = threading.Event()
release = threading.Event()
def holder():
with locks.hold("tcp:10.0.0.5:9034"):
entered.set()
release.wait(2)
t = threading.Thread(target=holder)
t.start()
entered.wait(2)
try:
with pytest.raises(UnitBusy, match="busy"):
with locks.hold("tcp:10.0.0.5:9034"):
pass
finally:
release.set()
t.join()
def test_different_units_do_not_block_each_other():
locks = UnitLocks(timeout=0.2)
with locks.hold("tcp:10.0.0.5:9034"):
with locks.hold("tcp:10.0.0.6:9034"):
pass
def test_try_hold_never_waits():
locks = UnitLocks(timeout=5)
with locks.hold("k"):
with locks.try_hold("k") as got:
assert got is False
with locks.try_hold("k") as got:
assert got is True
def test_the_lock_is_released_after_an_exception():
locks = UnitLocks(timeout=0.2)
with pytest.raises(RuntimeError):
with locks.hold("k"):
raise RuntimeError("boom")
with locks.hold("k"):
pass
-106
View File
@@ -1,106 +0,0 @@
"""Events through the one door: same shape both series, the held line, ring safety."""
from __future__ import annotations
import dataclasses
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import FakeMicromateClient, FakeMiniMateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import BadRequest, CallHomeInProgress # noqa: E402
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s4 import RingDetected # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
def access(s3=(), s4=()):
s3q, s4q = list(s3), list(s4)
return DeviceAccess(s3_client_factory=lambda a, **kw: s3q.pop(0),
s4_client_factory=lambda a, **kw: s4q.pop(0), start_reaper=False)
def test_both_series_list_events_in_the_same_shape():
s3 = access(s3=[FakeMiniMateClient()]).list_events(ADDR, "BE18193")
s4 = access(s4=[FakeMicromateClient()]).list_events(ADDR, "UM20147")
f3 = [set(dataclasses.asdict(e)) for e in s3.events]
f4 = [set(dataclasses.asdict(e)) for e in s4.events]
assert all(f == f3[0] for f in f3 + f4)
def test_no_shared_field_is_empty_for_either_series():
# A field one series cannot fill belongs under `detail`, not at the top level.
# Except Series 3's record_type: its 0C cannot tell a histogram yet, and null beats a wrong type.
allowed = {3: {"record_type"}, 4: set()}
for out in (access(s3=[FakeMiniMateClient()]).list_events(ADDR, "BE18193"),
access(s4=[FakeMicromateClient()]).list_events(ADDR, "UM20147")):
for e in out.events:
empty = {k for k, v in dataclasses.asdict(e).items() if v is None}
assert empty == allowed[out.series], (out.series, empty)
def test_a_micromate_list_and_download_share_one_held_line():
fake = FakeMicromateClient()
da = access(s4=[fake])
listed = da.list_events(ADDR, "UM20147")
dl = da.download_event(ADDR, "UM20147", listed.events[0].event_id)
assert fake.opened == 1 and dl.idf_bytes
assert da.held_serial(ADDR) == "UM20147"
def test_an_id_from_another_unit_is_refused_before_any_io():
fake = FakeMicromateClient()
with pytest.raises(BadRequest):
access(s4=[fake]).download_event(ADDR, "UM20147", "UM12947:055d4a81:20250531135901")
assert fake.opened == 0
def test_a_minimate_download_goes_through_the_series3_adapter():
dl = access(s3=[FakeMiniMateClient()]).download_event(ADDR, "BE18193", "BE18193:01110000:-")
assert dl.series == 3 and dl.a5_frames and all(f.sub == 0xA5 for f in dl.a5_frames)
def test_a_ring_mid_download_releases_the_line_and_downloads_nothing():
fake = FakeMicromateClient()
def ring(*a, **kw):
raise RingDetected("RADIO RING")
fake.fetch_event = ring
da = access(s4=[fake])
with pytest.raises(CallHomeInProgress):
da.download_event(ADDR, "UM20147", "UM20147:055d4a81:20250531135901")
assert fake.closed == 1 and da.held_serial(ADDR) is None
def test_a_library_error_mid_download_hangs_up():
# Only a DeviceError verdict keeps the line; anything the library raises means
# the link is suspect. A fresh DeviceAccess, so the held-line retry cannot apply.
from micromate.protocol import TimeoutError as MicromateTimeout
from sfm.device_access.errors import NoAnswer
fake = FakeMicromateClient()
def quiet(*a, **kw):
raise MicromateTimeout("quiet")
fake.fetch_event = quiet
da = access(s4=[fake])
with pytest.raises(NoAnswer):
da.download_event(ADDR, "UM20147", "UM20147:055d4a81:20250531135901")
assert fake.closed == 1 and da.held_serial(ADDR) is None
def test_a_stale_or_missing_event_keeps_the_line():
# The operation's own verdict (404/409) says nothing is wrong with the link;
# hanging up would cost a call-up for no reason.
from sfm.device_access.errors import EventNotFound, StaleEvent
fake = FakeMicromateClient()
da = access(s4=[fake])
with pytest.raises(StaleEvent):
da.download_event(ADDR, "UM20147", "UM20147:055d4a81:20240101000000")
with pytest.raises(EventNotFound):
da.download_event(ADDR, "UM20147", "UM20147:deadbeef:-")
assert fake.opened == 1 and fake.closed == 0
assert da.held_serial(ADDR) == "UM20147"
-53
View File
@@ -1,53 +0,0 @@
"""Event identity: serial + key + timestamp, so a stale or foreign id fails loudly."""
from __future__ import annotations
import datetime
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.device_access.errors import BadRequest, EventNotFound, StaleEvent # noqa: E402
from sfm.device_access.events import ( # noqa: E402
iso_of, make_event_id, parse_event_id, stamp_of,
)
KEY = bytes.fromhex("055d4a81")
WHEN = datetime.datetime(2025, 5, 31, 13, 59, 1)
def test_an_event_id_round_trips():
eid = make_event_id("um20147", KEY, stamp_of(WHEN))
assert eid == "UM20147:055d4a81:20250531135901"
assert parse_event_id(eid, "UM20147") == (KEY, "20250531135901")
def test_an_unknown_timestamp_round_trips_as_none():
eid = make_event_id("BE18193", bytes.fromhex("01110000"), None)
assert eid == "BE18193:01110000:-"
assert parse_event_id(eid, "be18193") == (bytes.fromhex("01110000"), None)
def test_an_id_from_another_unit_is_refused():
# UM12947 and UM20147 both have an event 055d4a81
with pytest.raises(BadRequest, match="UM12947"):
parse_event_id("UM12947:055d4a81:20250531135901", "UM20147")
@pytest.mark.parametrize("bad", ["", "UM20147", "UM20147:055d4a81",
"UM20147:zz:20250531135901", "UM20147:055d4a:20250531135901",
"UM20147:055d4a81:2025"])
def test_a_malformed_id_is_refused(bad):
with pytest.raises(BadRequest):
parse_event_id(bad, "UM20147")
def test_iso_and_stamp_of_none_are_none():
assert iso_of(None) is None and stamp_of(None) is None
assert iso_of(WHEN) == "2025-05-31T13:59:01"
def test_the_new_errors_have_their_statuses():
assert (EventNotFound.http_status, StaleEvent.http_status) == (404, 409)
-87
View File
@@ -1,87 +0,0 @@
"""The Series-3 adapter: connect-per-request, mapped into the shared models."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import minimateplus.protocol as mmp_proto # noqa: E402
from device_access_fakes import FakeMiniMateClient # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
ConnectFailed, MalformedReply, NoAnswer, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter # noqa: E402
TCP = UnitAddress(host="10.0.0.5", tcp_port=12345, port=None, baud=None)
SERIAL_LINK = UnitAddress(host=None, tcp_port=None, port="/dev/ttyUSB0", baud=None)
def adapter(*clients):
queue = list(clients)
return Series3Adapter(client_factory=lambda address: queue.pop(0))
def test_identify_maps_device_info():
fake = FakeMiniMateClient()
info = adapter(fake).identify(TCP, "BE18193")
assert (info.serial, info.series, info.model, info.firmware) == ("BE18193", 3, "MiniMate Plus", "S338.17")
assert info.active_setup == "BRIDGE-A"
assert info.monitoring is None # connect() does not read it on Series 3
assert fake.closed == 1
def test_a_different_unit_answering_is_refused():
fake = FakeMiniMateClient(serial="BE11529")
with pytest.raises(WrongUnit, match="BE18193.*BE11529"):
adapter(fake).identify(TCP, "BE18193")
assert fake.closed == 1
def test_status_maps_monitor_status():
fake = FakeMiniMateClient(monitoring=True)
st = adapter(fake).status(TCP, "BE18193")
assert (st.series, st.monitoring, st.battery_volts) == (3, True, 6.8)
assert (st.memory_total_bytes, st.memory_free_bytes) == (983026, 900000)
assert st.event_count is None and st.device_time is None
assert st.detail == {"serial_verified": False}
assert fake.calls == ["poll", "get_monitor_status"]
def test_settings_maps_the_compliance_config():
s = adapter(FakeMiniMateClient()).settings(TCP, "BE18193")
assert s.record_mode == "Continuous"
assert (s.sample_rate, s.record_time_s, s.histogram_interval_s) == (1024, 3.0, 300)
assert s.geo_trigger_ips == 0.5
assert s.setup_name == "BRIDGE-A"
assert s.notes == {"Project": "Bridge job", "Client": "Acme", "User Name": "BH", "Seis Loc": "Loc 1"}
assert s.detail["record_mode_code"] == 0x01
def test_settings_without_a_compliance_read_is_a_malformed_reply_and_not_retried():
# One fake only: a retry would ask the factory for a second and fail.
with pytest.raises(MalformedReply, match="settings"):
adapter(FakeMiniMateClient(compliance=None)).settings(TCP, "BE18193")
def test_a_cold_unit_over_tcp_gets_one_retry():
first = FakeMiniMateClient(fail=[mmp_proto.TimeoutError("cold")])
second = FakeMiniMateClient()
info = adapter(first, second).identify(TCP, "BE18193")
assert info.serial == "BE18193"
assert first.closed == 1 and second.closed == 1
def test_a_serial_link_is_not_retried():
fake = FakeMiniMateClient(fail=[mmp_proto.TimeoutError("quiet")])
with pytest.raises(NoAnswer):
adapter(fake).identify(SERIAL_LINK, "BE18193")
def test_a_failed_connect_is_connect_failed_and_not_retried():
fake = FakeMiniMateClient(open_error=ConnectionRefusedError("refused"))
with pytest.raises(ConnectFailed, match="could not connect"):
adapter(fake).identify(TCP, "BE18193")
-134
View File
@@ -1,134 +0,0 @@
"""Series-3 events: listed from headers, one downloaded, mapped into the shared shape."""
from __future__ import annotations
import datetime
import os
import struct
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
EventNotFound, MalformedReply, StaleEvent, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter # noqa: E402
TCP = UnitAddress(host="10.0.0.5", tcp_port=12345, port=None, baud=None)
FIRST = bytes.fromhex("01110000")
def adapter(*clients):
queue = list(clients)
seen = []
def factory(address, **kw):
seen.append(kw)
return queue.pop(0)
a = Series3Adapter(client_factory=factory)
a.seen = seen
return a
def test_listing_maps_each_header_into_the_shared_shape():
out = adapter(FakeMiniMateClient()).list_events(TCP, "BE18193")
assert (out.serial, out.series, len(out.events)) == ("BE18193", 3, 2)
e = out.events[1]
assert e.event_id == "BE18193:0111245a:20261002093015"
assert (e.index, e.timestamp) == (1, "2026-10-02T09:30:15")
# The 0C record does not say waveform or histogram (every layout reads "Waveform").
assert e.record_type is None and "not decoded yet" in e.detail["record_type_note"]
assert e.peaks_ips == {"tran": 0.05, "vert": 0.08, "long": 0.03}
assert e.peak_vector_sum_ips == 0.12 and e.detail["mic_psi"] == 0.0001
assert e.filename and e.filename.startswith("T193")
def test_listing_uses_the_header_walk_and_the_default_timeout():
# A header walk is small replies only; a lost one should cost 10 s, not 120 s.
fake = FakeMiniMateClient()
a = adapter(fake)
a.list_events(TCP, "BE18193")
assert "list_event_headers" in fake.calls and "download_event_by_key" not in fake.calls
assert a.seen == [{}]
assert fake.closed == 1
def test_downloading_uses_the_long_timeout():
a = adapter(FakeMiniMateClient())
a.download_event(TCP, "BE18193", FIRST, None)
assert a.seen == [{"timeout": 120.0}]
def test_listing_refuses_a_different_unit():
with pytest.raises(WrongUnit):
adapter(FakeMiniMateClient(serial="BE11529")).list_events(TCP, "BE18193")
def test_download_returns_the_event_its_frames_and_the_settings():
fake = FakeMiniMateClient()
dl = adapter(fake).download_event(TCP, "BE18193", FIRST, "20261001080000")
assert (dl.series, dl.event_id, dl.verified) == (3, "BE18193:01110000:20261001080000", True)
assert dl.event is fake.events[0] and dl.a5_frames is fake.events[0]._a5_frames
assert dl.a5_frames and all(f.sub == 0xA5 for f in dl.a5_frames)
assert dl.compliance is fake.compliance and dl.filename.startswith("T193")
assert dl.timestamp == datetime.datetime(2026, 10, 1, 8, 0, 0)
def test_download_refuses_a_different_unit_before_downloading():
fake = FakeMiniMateClient(serial="BE11529")
with pytest.raises(WrongUnit):
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
assert "download_event_by_key" not in fake.calls
def test_a_key_that_is_not_stored_is_404():
with pytest.raises(EventNotFound):
adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", bytes.fromhex("0111ffff"), None)
def test_a_stale_id_is_refused_rather_than_downloading_another_event():
fake = FakeMiniMateClient()
with pytest.raises(StaleEvent, match="20261001080000"):
adapter(fake).download_event(TCP, "BE18193", FIRST, "20250101000000")
# The walk was told what to expect, so it compared after 0C and sent no 5A.
assert fake.download_requests == [(FIRST, "2025-01-01T00:00:00")]
assert fake.last_download is not None and fake.last_download._a5_frames is None
def test_an_id_without_a_timestamp_skips_the_check():
fake = FakeMiniMateClient()
dl = adapter(fake).download_event(TCP, "BE18193", FIRST, None)
assert dl.event_id == "BE18193:01110000:20261001080000"
assert fake.download_requests == [(FIRST, None)]
def test_a_target_whose_record_could_not_be_read_is_not_called_stale():
# A lost 0C reply leaves no timestamp to compare: that is a bad reply, not an erase.
ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0))
ev.timestamp = None
fake = FakeMiniMateClient(events=[ev])
with pytest.raises(MalformedReply, match="0C"):
adapter(fake).download_event(TCP, "BE18193", FIRST, "20261001080000")
assert fake.last_download._a5_frames is None
def test_a_failed_5a_is_a_clear_error():
fake = FakeMiniMateClient(events=[s3_event(0, "01110000",
datetime.datetime(2026, 10, 1, 8, 0, 0), frames=False)])
with pytest.raises(MalformedReply, match="5A"):
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
def test_an_assembly_fault_is_a_named_502_not_a_bare_500():
# Once the 64 KB page bug's signature; that is fixed (2026-10-26), and the
# mapping stays as a defence against any struct.error in assembly.
fake = FakeMiniMateClient()
def boom(key4, **kw):
raise struct.error("argument out of range")
fake.download_event_by_key = boom
with pytest.raises(MalformedReply, match="could not be assembled.*not saved"):
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
-142
View File
@@ -1,142 +0,0 @@
"""A MiniMate download is checked against the unit's own peaks before it is stored.
Series 4 downloads were already checked (decoded PVS against the unit's).
Series 3's were not, so two bad files went into the store as successes at the
bench (2026-10-25). Now: if the waveform decodes, all three geophone channels
must be the same length and each channel's peak must match the unit's own 0C
peak to one 0.005 in/s step, or the download is refused and nothing is stored.
No waveform decode (a histogram -- 0 of ~430 fixture histograms decode as one)
or a sensitive-range unit (its scale is still open) is stored unverified.
"""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import minimateplus.blastware_file as bw # noqa: E402
from minimateplus.framing import S3FrameParser # noqa: E402
from minimate_replay import FIX # noqa: E402
import minimateplus.client as mc # noqa: E402
from minimate_replay import KEY, SessionReplay, fast_clock, recorded_replies # noqa: E402
from minimateplus.models import ComplianceConfig, Event, PeakValues # noqa: E402
from sfm.device_access.errors import MalformedReply # noqa: E402
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter, verify_s3_download # noqa: E402
CABLE = UnitAddress(host=None, tcp_port=None, port="/dev/ttyUSB0", baud=38400)
COUNTS_PER_IPS = 3200 # 32000 counts = 10.000 in/s (normal range)
@pytest.fixture(autouse=True)
def _fast(monkeypatch):
fast_clock(monkeypatch)
def event(samples, peaks):
ev = Event(index=0)
ev.raw_samples = samples
ev.peak_values = PeakValues(tran=peaks[0], vert=peaks[1], long=peaks[2])
return ev
def flat(n, peak_ips):
return [0] * (n - 1) + [round(peak_ips * COUNTS_PER_IPS)]
NORMAL = ComplianceConfig(geo_range=0)
GOOD = bw.extract_body_bytes( # BE9441 event 1, whole
[f for f in S3FrameParser().feed(FIX.read_bytes()) if f.sub == 0xA5])[1]
_H = (FIX.parent.parent / "ts-fix" / "K441LKZU.C30H").read_bytes() # BE9441's own histogram
HISTOGRAM = _H[bw._WAVEFORM_HEADER_SIZE + 21:-26]
def test_matching_peaks_and_lengths_verify():
ev = event({c: flat(100, p) for c, p in zip(("Tran", "Vert", "Long"), (0.03, 0.095, 0.02))},
(0.02999996, 0.09499989, 0.01999998))
assert verify_s3_download(ev, NORMAL, body=GOOD)[0] is True
def test_a_peak_that_disagrees_is_refused():
ev = event({c: flat(100, p) for c, p in zip(("Tran", "Vert", "Long"), (0.01, 0.01, 0.005))},
(0.03, 0.095, 0.02))
with pytest.raises(MalformedReply, match="Tran peak is 0.0100.*not saved"):
verify_s3_download(ev, NORMAL, body=GOOD)
def test_unequal_channel_lengths_are_refused():
ev = event({"Tran": flat(100, 0.03), "Vert": flat(100, 0.095), "Long": flat(90, 0.02)},
(0.03, 0.095, 0.02))
with pytest.raises(MalformedReply, match="lengths.*not saved"):
verify_s3_download(ev, NORMAL, body=GOOD)
def test_a_histogram_is_stored_unverified():
ok, why = verify_s3_download(event(None, (0.03, 0.095, 0.02)), NORMAL, body=HISTOGRAM)
assert ok is None and "histogram" in why
def test_a_body_that_decodes_as_neither_is_refused():
with pytest.raises(MalformedReply, match="neither a waveform nor a histogram.*not saved"):
verify_s3_download(event(None, (0.03, 0.095, 0.02)), NORMAL, body=GOOD[:4000])
def test_a_waveform_without_its_end_record_is_refused():
ev = event({c: flat(100, p) for c, p in zip(("Tran", "Vert", "Long"), (0.03, 0.095, 0.02))},
(0.03, 0.095, 0.02))
with pytest.raises(MalformedReply, match="end record.*not saved"):
verify_s3_download(ev, NORMAL, body=GOOD[:20_000])
def test_a_sensitive_range_unit_is_structure_checked_but_not_peak_checked():
ev = event({c: flat(100, 0.5) for c in ("Tran", "Vert", "Long")}, (0.03, 0.095, 0.02))
assert verify_s3_download(ev, ComplianceConfig(geo_range=1), body=GOOD)[0] is None
short = event({"Tran": flat(100, 0.5), "Vert": flat(100, 0.5), "Long": flat(90, 0.5)},
(0.03, 0.095, 0.02))
with pytest.raises(MalformedReply, match="lengths"):
verify_s3_download(short, ComplianceConfig(geo_range=1), body=GOOD)
def test_an_unknown_range_is_not_peak_checked():
ev = event({c: flat(100, 0.5) for c in ("Tran", "Vert", "Long")}, (0.03, 0.095, 0.02))
assert verify_s3_download(ev, ComplianceConfig(), body=GOOD)[0] is None
def test_a_clipped_blast_is_not_refused():
ev = event({c: [0] * 99 + [32032] for c in ("Tran", "Vert", "Long")}, (10.0, 10.0, 10.0)) # 10.010 in/s: two steps past
assert verify_s3_download(ev, NORMAL, body=GOOD)[0] is True
def test_the_tolerance_is_one_step():
near = event({c: flat(100, 0.095) for c in ("Tran", "Vert", "Long")}, (0.095 + 0.005,) * 3)
assert verify_s3_download(near, NORMAL, body=GOOD)[0] is True
far = event({c: flat(100, 0.095) for c in ("Tran", "Vert", "Long")}, (0.095 + 0.0055,) * 3)
with pytest.raises(MalformedReply):
verify_s3_download(far, NORMAL, body=GOOD)
def adapter():
def factory(address, **kw):
return mc.MiniMateClient(transport=SessionReplay(recorded_replies()))
return Series3Adapter(client_factory=factory)
def test_be9441_event_1_downloads_verified():
dl = adapter().download_event(CABLE, "BE9441", KEY, "20261025141049")
assert dl.verified is True
def test_the_check_refuses_the_file_the_metadata_page_bug_produced(monkeypatch):
real = bw._frame_body_bytes
calls = []
def old_rule(frame, skip): # the bug, back: frames 1 and 2 cut as metadata pages
calls.append(1)
return real(frame, skip + 1 if len(calls) in (2, 3) and skip == 12 else skip)
monkeypatch.setattr(bw, "_frame_body_bytes", old_rule)
with pytest.raises(MalformedReply, match="not saved"):
adapter().download_event(CABLE, "BE9441", KEY, "20261025141049")
-331
View File
@@ -1,331 +0,0 @@
"""Series-4 sessions: one call-up, then stay on the line; ring safety."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import micromate.protocol as mm_proto # noqa: E402
from device_access_fakes import FakeMicromateClient # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
CallHomeInProgress, ConnectFailed, NoAnswer, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s4 import ( # noqa: E402
RingDetected, RingWatchTransport, Series4Session,
)
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
class ScriptedInner:
"""A minimal real-interface transport: is_connected is a PROPERTY."""
def __init__(self, chunks):
self.chunks = list(chunks)
self.written = []
self._c = False
def connect(self):
self._c = True
def disconnect(self):
self._c = False
@property
def is_connected(self):
return self._c
def write(self, data):
self.written.append(data)
def read(self, n):
return self.chunks.pop(0) if self.chunks else b""
class Clock:
def __init__(self, t=1000.0):
self.t = t
def __call__(self):
return self.t
def session(*clients, clock=None):
queue = list(clients)
return Series4Session(ADDR, "UM20147", lambda address: queue.pop(0), clock=clock or Clock())
# ── RingWatchTransport ────────────────────────────────────────────────────────
def test_ordinary_bytes_pass_through():
t = RingWatchTransport(ScriptedInner([b"\x02abc\x03"]))
assert t.read(4096) == b"\x02abc\x03"
def test_a_ring_raises():
t = RingWatchTransport(ScriptedInner([b"\r\nRADIO RING\r\n"]))
with pytest.raises(RingDetected):
t.read(4096)
def test_a_ring_split_across_reads_still_raises():
t = RingWatchTransport(ScriptedInner([b"\r\nRADIO R", b"ING\r\n"]))
assert t.read(4096) == b"\r\nRADIO R"
with pytest.raises(RingDetected):
t.read(4096)
def _real_frame(payload_data: bytes, sub: int = 0xA4) -> bytes:
from micromate.framing import ETX, STX, checksum, stuff
payload = bytes([0x00, 0xC5, sub, 0x00, 0x00]) + payload_data
return bytes([STX]) + stuff(payload + bytes([checksum(payload)])) + bytes([ETX])
def test_a_ring_inside_a_frame_is_data_not_a_call_home():
# The 0x2C call-home config block's dial string is literally "RADIO RING".
wire = _real_frame(b"\x00" * 6 + b"RADIO RING" + b"\x00" * 4)
t = RingWatchTransport(ScriptedInner([wire]))
assert t.read(4096) == wire
def test_a_ring_inside_a_frame_split_across_reads_is_still_data():
wire = _real_frame(b"xxRADIO RINGyy")
cut = wire.index(b"RADIO R") + 7
t = RingWatchTransport(ScriptedInner([wire[:cut], wire[cut:]]))
assert t.read(4096) == wire[:cut]
assert t.read(4096) == wire[cut:]
def test_a_ring_between_frames_still_raises():
t = RingWatchTransport(ScriptedInner([_real_frame(b"abc") + b"\r\nRADIO RING\r\n"]))
with pytest.raises(RingDetected):
t.read(4096)
def test_a_ring_split_across_reads_after_a_frame_still_raises():
t = RingWatchTransport(ScriptedInner([_real_frame(b"abc") + b"\r\nRADIO R", b"ING\r\n"]))
t.read(4096)
with pytest.raises(RingDetected):
t.read(4096)
def test_a_ring_arriving_right_after_a_frame_ends_still_raises():
t = RingWatchTransport(ScriptedInner([_real_frame(b"abc"), b"RADIO RING"]))
t.read(4096)
with pytest.raises(RingDetected):
t.read(4096)
def test_an_escaped_etx_inside_a_frame_does_not_end_it():
# DLE ETX inside the payload is literal data; the ring after it is still inside.
wire = b"\x02" + b"ab\x10\x03RADIO RINGcd" + b"\x03"
t = RingWatchTransport(ScriptedInner([wire]))
assert t.read(4096) == wire
def test_a_ring_that_follows_a_frame_with_an_escaped_etx_still_raises():
wire = b"\x02" + b"ab\x10\x03cd" + b"\x03" + b"RADIO RING"
t = RingWatchTransport(ScriptedInner([wire]))
with pytest.raises(RingDetected):
t.read(4096)
def _real_chain_client(chunks):
from micromate.client import MicromateClient
inner = ScriptedInner(chunks)
return MicromateClient(RingWatchTransport(inner), recv_timeout=0.5), inner
def test_real_chain_a_response_carrying_a_ring_in_its_payload_succeeds():
client, _ = _real_chain_client([_real_frame(b"\x30" + b"\x00" * 8 + b"RADIO RING")])
client.open()
frame = client.protocol.poll()
assert b"RADIO RING" in frame.data
def test_real_chain_an_unsolicited_ring_before_the_response_hangs_up():
from types import SimpleNamespace
client, inner = _real_chain_client([b"\r\nRADIO RING\r\n", _real_frame(b"\x30" + b"\x00" * 8)])
# Only the identity read is stubbed; open/close/protocol/transport are the real chain.
client.connect = lambda: SimpleNamespace(serial="UM20147")
s = Series4Session(ADDR, "UM20147", lambda address: client, clock=Clock())
with pytest.raises(CallHomeInProgress):
s.run(lambda c: c.protocol.poll())
assert not s.is_open and not inner.is_connected
def test_the_wrapper_keeps_is_connected_a_property():
inner = ScriptedInner([])
t = RingWatchTransport(inner)
t.connect()
assert t.is_connected is True
# ── call-up ───────────────────────────────────────────────────────────────────
def test_call_up_verifies_the_serial_once():
fake = FakeMicromateClient()
s = session(fake)
s.run(lambda c: c.get_state())
s.run(lambda c: c.get_event_count())
assert fake.calls == ["connect", "get_state", "get_event_count"]
assert fake.opened == 1
def test_a_different_unit_answering_is_refused_and_closed():
fake = FakeMicromateClient(serial="UM12947")
s = session(fake)
with pytest.raises(WrongUnit, match="UM20147.*UM12947"):
s.run(lambda c: c.get_state())
assert fake.closed == 1 and not s.is_open
assert fake.calls == ["connect"] # nothing after the identity check
def test_a_failed_connect_is_connect_failed():
s = session(FakeMicromateClient(open_error=ConnectionRefusedError("no")))
with pytest.raises(ConnectFailed, match="could not connect"):
s.run(lambda c: c.get_state())
# ── ring safety ───────────────────────────────────────────────────────────────
def test_a_ring_during_a_request_releases_the_line():
fake = FakeMicromateClient()
s = session(fake)
s.call_up()
fake.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress, match="calling home"):
s.run(lambda c: c.get_state())
assert not s.is_open and fake.closed == 1
def test_listen_while_idle_releases_the_line_on_a_ring_and_sends_nothing():
fake = FakeMicromateClient()
s = session(fake)
s.call_up()
fake.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress):
s.listen()
assert not s.is_open
assert fake.calls == ["connect", "read_unsolicited"]
def test_the_next_request_after_a_ring_calls_up_fresh():
first, second = FakeMicromateClient(), FakeMicromateClient()
s = session(first, second)
s.call_up()
first.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress):
s.run(lambda c: c.get_state())
s.run(lambda c: c.get_state())
assert second.calls == ["connect", "get_state"]
# ── what counts as use ────────────────────────────────────────────────────────
def test_keepalive_and_listen_do_not_count_as_use():
clock = Clock(1000.0)
fake = FakeMicromateClient()
s = session(fake, clock=clock)
s.call_up()
clock.t = 1060.0
s.keepalive()
clock.t = 1065.0
s.listen()
assert s.last_used == 1000.0
assert s.last_traffic == 1060.0
assert fake.calls == ["connect", "poll", "read_unsolicited"]
def test_a_request_counts_as_use():
clock = Clock(1000.0)
s = session(FakeMicromateClient(), clock=clock)
s.call_up()
clock.t = 1100.0
s.run(lambda c: c.get_state())
assert s.last_used == 1100.0 and s.last_traffic == 1100.0
def test_a_failure_mid_request_hangs_up():
fake = FakeMicromateClient()
s = session(fake)
s.call_up()
fake.fail = [mm_proto.TimeoutError("quiet")]
with pytest.raises(NoAnswer):
s.run(lambda c: c.get_state())
assert not s.is_open
# ── operations ────────────────────────────────────────────────────────────────
from sfm.device_access.s4 import s4_identify, s4_settings, s4_status # noqa: E402
def test_s4_identify():
info = s4_identify(FakeMicromateClient(monitoring=True), "UM20147")
assert (info.serial, info.series, info.model, info.monitoring) == ("UM20147", 4, "MM/ISEE/S", True)
assert info.active_setup == "test2.MMB"
assert info.firmware is None and info.detail["firmware_line"] == "thor"
def test_s4_status_includes_the_cheap_event_count():
st = s4_status(FakeMicromateClient(events=5), "UM20147")
assert (st.series, st.monitoring, st.battery_volts, st.event_count) == (4, False, 3.8, 5)
assert (st.memory_total_bytes, st.memory_free_bytes) == (15_000_000, 14_799_296)
assert st.device_time == "2026-10-20T18:07:58"
def test_s4_status_reads_0x49_only_when_asked():
# speed: 0x49 is one more round trip, so a plain status never reads it
fake = FakeMicromateClient(run_states=[0x01])
assert "run_state" not in s4_status(fake, "UM20147").detail
assert "read_run_state" not in fake.calls
st = s4_status(fake, "UM20147", run_state=True)
assert st.detail["run_state"] == {"code": 1, "name": "unknown(0x01)"}
def test_s4_settings_maps_the_decoded_setup():
s = s4_settings(FakeMicromateClient(), "UM20147")
assert (s.series, s.setup_name, s.record_mode) == (4, "test2.MMB", "Histogram Combo")
assert (s.sample_rate, s.record_time_s, s.histogram_interval_s) == (1024, 10.0, 2)
assert s.geo_trigger_ips == pytest.approx(0.5, abs=1e-6)
assert list(s.notes) == ["Location", "Client", "Company", "General Notes"]
assert s.detail["pretrigger_s"] == 1.0
assert s.detail["mic_type"] == "linear"
assert s.detail["mic_trigger_db"] == pytest.approx(131.0, abs=0.01)
assert s.detail["geo_trigger_ips_per_channel"] == pytest.approx([0.5, 0.5, 0.5], abs=1e-6)
def test_a_new_request_clears_frame_state_left_by_a_stray_stx():
# A stray STX on an idle line would otherwise hide the ring that answers the
# next request. MicromateProtocol resets its own parser at every request too.
t = RingWatchTransport(ScriptedInner([b"\x02stray", b"\r\nRADIO RING\r\n"]))
t.connect()
t.read(64)
t.write(b"x")
with pytest.raises(RingDetected):
t.read(64)
def test_is_open_survives_a_hang_up_between_its_two_reads():
# held_serial() calls is_open without the unit lock; a concurrent hang-up can
# clear _client between the None check and the method call.
class Racy(Series4Session):
_reads = 0
@property
def _client(self):
Racy._reads += 1
return object.__new__(type("C", (), {"is_open": lambda s: True})) if Racy._reads == 1 else None
@_client.setter
def _client(self, value):
pass
s = Racy(ADDR, "UM20147", client_factory=lambda a: None)
assert s.is_open in (True, False)
-82
View File
@@ -1,82 +0,0 @@
"""Series-4 events: the chain walk mapped into the shared shape; download at the cursor."""
from __future__ import annotations
import datetime
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import THOR_IDF, FakeMicromateClient # noqa: E402
from micromate.protocol import THOR_CHUNK_SIZE # noqa: E402
from sfm.device_access.errors import EventNotFound, StaleEvent # noqa: E402
from sfm.device_access.s4 import s4_download_event, s4_list_events # noqa: E402
W_KEY, H_KEY = bytes.fromhex("055d4a81"), bytes.fromhex("055d4a83")
def test_listing_maps_each_ref_into_the_shared_shape():
out = s4_list_events(FakeMicromateClient(), "UM20147")
assert (out.serial, out.series, len(out.events)) == ("UM20147", 4, 2)
e = out.events[0]
assert e.event_id == "UM20147:055d4a81:20250531135901"
assert (e.index, e.timestamp, e.record_type) == (0, "2025-05-31T13:59:01", "waveform")
assert e.peaks_ips == {"tran": 0.1, "vert": 0.15, "long": 0.05}
assert e.filename == "UM20147_20250531135901.IDFW"
assert e.detail["mic"] == 0.0002 and e.detail["size_bytes"] > 0
def test_download_walks_to_the_event_and_uses_thors_chunk_size():
fake = FakeMicromateClient()
dl = s4_download_event(fake, "UM20147", W_KEY, "20250531135901")
assert "iter_events" in fake.calls and "list_events" not in fake.calls
assert fake.fetched == [("055d4a81", THOR_CHUNK_SIZE)]
assert dl.idf_bytes == (THOR_IDF / "UM20147_20250531135901.IDFW").read_bytes()
assert (dl.series, dl.filename, dl.verified) == (4, "UM20147_20250531135901.IDFW", True)
def test_download_carries_the_units_timestamp_and_its_own_record():
# What the unit's 0x0C said: the store looks up an existing row by the
# timestamp, and fills what the file alone cannot give from the record.
ref = FakeMicromateClient().event_refs[0]
ref.sensor_location, ref.setup = "Loc A", "test2"
fake = FakeMicromateClient(event_refs=[ref])
dl = s4_download_event(fake, "UM20147", W_KEY, "20250531135901")
assert dl.timestamp == datetime.datetime(2025, 5, 31, 13, 59, 1)
assert dl.record == {"peak_vector_sum_ips": 0.2, "sensor_location": "Loc A", "setup": "test2"}
def test_the_walk_stops_at_the_event_rather_than_reading_ahead():
fake = FakeMicromateClient()
s4_download_event(fake, "UM20147", W_KEY, None)
assert fake.cursor == 0
def test_a_histogram_has_no_self_check_so_verified_is_none():
dl = s4_download_event(FakeMicromateClient(), "UM20147", H_KEY, None)
assert dl.verified is None and dl.filename.endswith(".IDFH")
def test_a_stale_id_is_refused_and_nothing_is_downloaded():
fake = FakeMicromateClient()
with pytest.raises(StaleEvent, match="20250531135901"):
s4_download_event(fake, "UM20147", W_KEY, "20240101000000")
assert fake.fetched == []
def test_a_key_that_is_not_stored_is_404():
with pytest.raises(EventNotFound):
s4_download_event(FakeMicromateClient(), "UM20147", bytes.fromhex("deadbeef"), None)
def test_a_record_whose_timestamp_did_not_decode_is_not_called_stale():
# Mirrors Series 3 (F3): an unreadable 0C timestamp is a comms/decode fault,
# not proof the unit was erased -- and nothing is downloaded.
from sfm.device_access.errors import MalformedReply
fake = FakeMicromateClient()
fake.event_refs[0].timestamp = None
with pytest.raises(MalformedReply, match="0C"):
s4_download_event(fake, "UM20147", W_KEY, "20250531135901")
assert fake.fetched == []
-123
View File
@@ -1,123 +0,0 @@
"""The device_commands audit table: one row per change attempt, pending -> result."""
from __future__ import annotations
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.audit import DbAudit # noqa: E402
from sfm.database import SeismoDb # noqa: E402
ROW = dict(serial="UM20147", series=4, address="serial:/dev/ttyACM0",
action="start monitoring", tier="change",
request={"plan": {"steps": [{"sub": "0x96"}]}}, caller="test")
def test_a_command_is_pending_until_finished(tmp_path):
db = SeismoDb(tmp_path / "s.db")
cid = db.begin_device_command(**ROW)
row = db.query_device_commands(serial="UM20147")[0]
assert (row["id"], row["outcome"], row["verified"]) == (cid, "pending", None)
assert row["request"]["plan"]["steps"][0]["sub"] == "0x96"
db.finish_device_command(cid, outcome="sent", verified="ok",
ack={"subs": ["0x69"]}, error=None)
row = db.query_device_commands(serial="UM20147")[0]
assert (row["outcome"], row["verified"], row["ack"]) == ("sent", "ok", {"subs": ["0x69"]})
assert row["finished_ts"]
def test_the_table_survives_reopening(tmp_path):
SeismoDb(tmp_path / "s.db").begin_device_command(**ROW)
assert len(SeismoDb(tmp_path / "s.db").query_device_commands()) == 1
def test_db_audit_is_a_thin_sink(tmp_path):
db = SeismoDb(tmp_path / "s.db")
audit = DbAudit(lambda: db)
cid = audit.begin(**ROW)
audit.finish(cid, outcome="failed", verified="mismatch", ack=None, error="unit reads idle")
row = db.query_device_commands()[0]
assert (row["outcome"], row["verified"], row["error"]) == ("failed", "mismatch", "unit reads idle")
def test_finishing_an_unknown_id_raises_and_creates_nothing(tmp_path):
import pytest
db = SeismoDb(tmp_path / "s.db")
with pytest.raises(ValueError, match="no-such-id"):
db.finish_device_command("no-such-id", outcome="sent", verified="ok",
ack=None, error=None)
assert db.query_device_commands() == []
def test_a_second_finish_raises_and_keeps_the_first_result(tmp_path):
import pytest
db = SeismoDb(tmp_path / "s.db")
cid = db.begin_device_command(**ROW)
db.finish_device_command(cid, outcome="failed", verified="mismatch",
ack={"subs": ["0x69"]}, error="unit reads idle")
with pytest.raises(ValueError, match=cid):
db.finish_device_command(cid, outcome="sent", verified="ok",
ack={"other": 1}, error=None)
row = db.query_device_commands()[0]
assert (row["outcome"], row["verified"], row["ack"], row["error"]) == \
("failed", "mismatch", {"subs": ["0x69"]}, "unit reads idle")
def test_a_finish_records_whether_a_frame_went_out_and_the_states(tmp_path):
db = SeismoDb(tmp_path / "s.db")
states = {"before": "idle", "seen": ["idle", "monitoring"], "after": "monitoring"}
cid = db.begin_device_command(**ROW)
db.finish_device_command(cid, outcome="sent", verified="ok", ack={"subs": ["0x69"]},
error=None, sent=1, states=states)
row = db.query_device_commands()[0]
assert (row["sent"], row["states"]) == (1, states)
def test_sent_and_states_default_to_null(tmp_path):
db = SeismoDb(tmp_path / "s.db")
cid = db.begin_device_command(**ROW)
db.finish_device_command(cid, outcome="failed", verified="not_checked", ack=None,
error="no clean ack")
row = db.query_device_commands()[0]
assert (row["sent"], row["states"]) == (None, None)
def test_db_audit_passes_sent_and_states_through(tmp_path):
db = SeismoDb(tmp_path / "s.db")
audit = DbAudit(lambda: db)
cid = audit.begin(**ROW)
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None, error="already idle",
sent=0, states={"before": "idle", "seen": ["idle"], "after": None})
row = db.query_device_commands()[0]
assert row["sent"] == 0 and row["states"]["before"] == "idle"
# The device_commands table as Task 3 created it: no `sent`, no `states`.
_TASK3_TABLE = """
CREATE TABLE device_commands (
id TEXT PRIMARY KEY, ts TEXT NOT NULL, finished_ts TEXT, serial TEXT NOT NULL,
series INTEGER NOT NULL, address TEXT NOT NULL, action TEXT NOT NULL, tier TEXT NOT NULL,
request TEXT, ack TEXT, verified TEXT, outcome TEXT NOT NULL, error TEXT, caller TEXT
);
INSERT INTO device_commands (id, ts, serial, series, address, action, tier, outcome)
VALUES ('old', '2026-10-22T00:00:00+00:00', 'UM20147', 4, 'tcp:x', 'stop monitoring',
'change', 'pending');
"""
def test_an_existing_task3_table_gains_sent_and_states(tmp_path):
import sqlite3
path = tmp_path / "s.db"
with sqlite3.connect(path) as conn:
conn.executescript(_TASK3_TABLE)
db = SeismoDb(path)
with sqlite3.connect(path) as conn:
cols = {r[1] for r in conn.execute("PRAGMA table_info(device_commands)")}
assert {"sent", "states"} <= cols
old = db.query_device_commands()[0]
assert (old["id"], old["sent"], old["states"]) == ("old", None, None)
db.finish_device_command("old", outcome="failed", verified="not_checked", ack=None,
error="x", sent=0, states={"before": "idle", "seen": ["idle"], "after": None})
assert db.query_device_commands()[0]["sent"] == 0
SeismoDb(path) # a second open is a no-op
+20
View File
@@ -132,6 +132,26 @@ def test_hdf5_samples_in_physical_units_sensitive_range(tmp_path: Path):
assert abs(max(vert) - expected_peak) < 1e-4
def test_hdf5_geo_ips_per_count_replaces_range_scale(tmp_path: Path):
"""A source whose counts have their own scale passes it explicitly.
The range-derived ``full_scale / 32000`` is the MiniMate body codec's
count; a Thor count is 0.000310308 in/s. Using the MiniMate scale for
Thor counts read every sample 0.71% high (issue #42)."""
ev = _make_event_with_samples()
h5 = tmp_path / "t.h5"
event_hdf5.write_event_hdf5(
h5, ev, serial="UM12947", geo_range="normal",
geo_ips_per_count=0.000310308,
)
data = event_hdf5.read_event_hdf5(h5)
vert = data["samples"]["Vert"]
assert abs(max(vert) - 32767 * 0.000310308) < 1e-5
# The range attrs still describe the range, not the count scale.
assert data["attrs"]["geo_full_scale_ips"] == 10.0
def test_hdf5_includes_int16_samples(tmp_path: Path):
ev = _make_event_with_samples()
h5 = tmp_path / "i.h5"
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more