diff --git a/CHANGELOG.md b/CHANGELOG.md index 21a5034..33922f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,501 @@ All notable changes to seismo-relay are documented here. --- +## v0.34.0 — 2026-11-04 + +**SFM reaches Series-4 parity, and reads most of Blastware's report from the +event file alone.** + +Two lines of work ship together. + +**Series-4 parity** (`feat/series4-sfm-parity`). One device door, by serial, +for both series. Each change is audited, identity-checked, sent once and read +back. Benched on BE9441 and UM20147. +- reads and downloads +- start / stop monitoring +- call-home on / off +- settings changes (preview → send → read back) + +It also fixes MiniMate request framing (#46) and the 5A walk across a 64 KB +page. + +**The file-only decode, groups A–D.** 47 of Blastware's 88 report fields now +match on every DL2 event, about 6 before v0.33.0. Eight more match on all but +one or two of 6,524 waveforms. +- **Fixed:** + - Sensitive-range events no longer read 8× high + - histograms the waveform codec had claimed, and short histograms with a + loud interval, now decode + - histograms are no longer a day late + - every histogram's start and stop are Blastware's own (#51), not a second + early + - interval frequencies follow the sample rate (#50) +- **New from the file:** + - the job number + - the unit's serial, version, calibration date and battery + - the trigger source and levels + - each interval's frequencies, vector sum and time + - the peak dates and times + - a waveform's time of peak and peak acceleration +- **Events are identified by unit + time + type:** a waveform and its histogram + may share a second. + +Prod still overlays a paired ASCII report onto the decode. That overlay is the +plan's step 3 and is not part of this release. + +⚠ **This release migrates the events table and owes a backfill that moves every +Series-3 histogram's stored time by one second.** See *Migration*. + +### Fixed +- ✅ **MiniMate requests and config writes are framed as Blastware frames them + (#46; `feat/series4-sfm-parity`).** + - Every request escapes 02 / 03 / 04 / 10. + - A config write is an ordinary escaped request carrying a whole block (as + read, plus two bytes). All four blocks are checked before the first frame. + - SFM's frames equal Blastware's in the 2026-04-20 and 2026-10-26 captures. + Benched on BE9441 2026-11-04. +- ✅ **The 5A walk crosses a unit's 64 KB page.** The walk is 32-bit linear + (the CLAUDE.md "KNOWN BUG"); BE9441's page-crossing events rebuild Blastware's + own files byte for byte. + - A one-event download is whole or an error. + - A non-first event's stream has no metadata pages. +- **A MiniMate settings read is assembled as content** (measured at the bench + 2026-11-04). + - Unescape each 1A frame and drop the one non-content byte that starts every + frame but the last: 2,090 bytes headed by N = 2090. + - The read takes exactly the length it asked for. When a reply's checksum + byte is itself escaped (about 1 frame in 85), the parser leaves its 0x10 in + the data. It hit the first live read; the recordings never had it. The + waveform-data read now trims it too. +- **A live download is held to its record type (#51):** a same-second + waveform / histogram twin is no longer skipped as "already stored". An untyped + row at that second still counts as stored. +- Smaller wire fixes from the parity benches: + - SUB 0x15's serial is cut at its first NUL. + - 0x1C reads a histogram run as monitoring. + - A MiniMate that boots on connect is waited for. + - A start's read-back waits out the sensor check and wakes the unit. + - A built call-home image is framed once. + +- ✅ **#51: events are identified by unit + time + type, and histograms take + Blastware's times.** + - **The new key.** The events table was `UNIQUE(serial, timestamp)`, one + event per unit per second. A waveform and its histogram share a second + legitimately: 209 times in prod's 2026-09-30 store. The key is now + `UNIQUE(serial, timestamp, record_type)` (agreed with Brian 2026-11-03). + - **Migration 3** rebuilds the table from its own definition with only the + key swapped, in one transaction. Every column, row and id is kept, and + the indexes are recreated. + - **Lookups:** the upsert, the estimate guard and the restamp match on + type. The restamp also re-types a file's own row in place. An untyped + event still dedups against an untyped row. + - **Histogram times.** A histogram's start and stop now come from its own + event record (lead `00 28 05 00`, source `04 00`, marker `fe f5`). That is + Blastware's Histogram Start and Stop on 63,490 / 63,490 DL2 histograms; the + footer's start was a second early on 97%. Without a validated record, the + footer stands and the decoder logs a decode problem. + - **Interval times and peak times follow:** + - each interval's printed time is its end, start + (i + 1) × interval, + capped at the stop (2,308,524 / 2,308,524 rows; `interval_times`) + - each peak's date and time is its interval's + - **Decode checker:** 760,410 comparisons fixed, 0 regressions, **47 of 88** + fields fully match (was 34). Histogram start and stop times, interval + times and the ten peak date/time fields match every DL2 histogram. + - **Rehearsed on a copy of prod's 2026-09-30 snapshot (15,432 events):** + - The migration kept every row identical, rebuilt the indexes and passed + the integrity check, in 0.27 s. + - `backfill_sidecars.py`: 11,944 files, 0 errors. 9,852 Series-3 + histograms moved +1 s in place, with no id lost and review state + untouched. The 209 same-second pairs coexist, and 0 collisions were + refused. (It also created 341 rows for store files that never had one: + the known one-time behaviour, not duplicates.) + - `backfill_event_shape.py`: exit 0, `cleared_stale` 0. + - ⚠ **Schema migration + codec change.** SFM migrates the events table by + itself on first start: back up `seismo_relay.db` first. The release + backfill (`backfill_sidecars.py` then `backfill_event_shape.py`) moves + every Series-3 histogram's stored time by one second, in place. + - Terra-View pairs twins by peak values and reads rows by id: no change + needed there. + - Note for Terra-View's changelog: Series-3 histograms move forward one + second, so an event can cross a deployment-window edge. + - Three tests that pinned the old footer start now pin the record's. The + estimate-guard test's neighbour is now the same type. +- **A Blastware file's geophone range comes from its setup, so Sensitive + events no longer read 8× high.** + - **Where it is:** in the setup's channel blocks, the byte 29 after each + geophone label. `0x00` is Normal (10 in/s full scale), `0x01` is Sensitive + (1.25 in/s). SFM's live 1A read has the same byte at label+33. + - **Measured:** it matches Blastware's GeoRange on 70,042 / 70,042 DL2 + events, all three channels agreeing on every one (35 Sensitive). + - **Before:** SFM assumed Normal, so every Sensitive event's peaks, vector + sum and `.h5` samples read 8× high. + - **`Event.geo_range`** is new: 0 or 1, or None when it isn't read (the + channels disagree, an unknown value, or a missing block). None comes with + a `decode_problems` entry, and peaks then assume Normal as before. + - **`decode_blastware_bytes`** scales peaks and the histogram vector sum by + the range. + - **`event_hdf5.write_event_hdf5`:** `geo_range` now defaults to None, + meaning the event's own range, else Normal. An explicit argument still + wins. + - **`waveform_store.save_imported_bw` and `scripts/backfill_sidecars.py`** + no longer force `"normal"`. The `waveform_store` line was agreed with the + parity session, which owns that file. + - **Decode checker:** GeoRange 70,042 / 70,042, and geophone samples exact + on **6,524 / 6,524** waveforms (was 6,491). PPV mismatches about halved, + and 10 of 88 fields fully match (was 6). 70,287 comparisons fixed, 0 + regressions. + - ⚠ **Codec change: bump `TOOL_VERSION` at the next release.** The backfill + (`backfill_sidecars.py` then `backfill_event_shape.py`) rewrites stored + Sensitive events' peaks and `.h5` files. No schema change. +- **Histograms go to the histogram codec, and a loud interval no longer hides + a short one.** These were the histograms the decode checker found decoding + wrongly. + - **The codec now follows the record type.** The file decoder used to try the + waveform codec first, whatever `STRT[18]` said. That codec accepted BE9440, + BE9557 and BE17354's 2018 5 s histograms and returned about 5× too many + "samples" (K440HDXX.XH0H: 44,504 against Blastware's 6,976). Only an + unknown type still falls back to trying both, and a chosen codec that + fails is now a decode problem rather than a silent switch. + - **A loud interval no longer breaks the sub-minute layout check.** The check + required each record's "zero word" to be `0000`. That word is the high word + of the interval's PVS², which is non-zero above 1.28 in/s, so a one-block + histogram with a loud interval decoded to nothing (T193KR5M.X90H, + K440HA3C.JM0H, R352HFZ7.530H). + - The check is now the measured relation peak ≤ PVS ≤ √3·peak. It holds + on 34,502,955 / 34,502,955 DL2 sub-minute intervals. + - The trim for a stream with no terminal tail uses the same test. + - **New decode-checker carve-out, `interval-count-is-duration`.** Blastware's + "Number of Intervals" is (stop − start) / interval. When the unit never + wrote the last minute, Blastware's own interval table lists one block + fewer, and SFM matches the table. It covers 8 events. + - **Decode checker:** 462 comparisons fixed, 0 regressions, 16 of 88 fields + fully match (was 11). + - Every DL2 histogram's Tran / Vert / Long interval peaks now match + Blastware (bar the clipped intervals the saturation carve-out covers). + - Channels 70,042 / 70,042. + - Histogram start dates a day off: 26 → 9. + - Peak vector sum mismatches: 45 → 18. + - ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and + backfill (`backfill_sidecars.py` then `backfill_event_shape.py`). Those + files are stored wrongly on prod today, and the backfill rewrites them. No + schema change. +- **A Blastware file's footer is its last 26 bytes: no more day-late + histograms.** + - **Measured:** every DL2 file ends in a valid footer (`0e 08` and two valid + times), 70,041 / 70,041. + - **The bug:** the decoder took the first "`0e 08` + plausible year". On 14 + files there is an earlier record, about 1.1 KB before the end, holding the + stop time followed by zeros. + - A histogram then started at its own stop: a day late on BE9558's daily + histograms (K558L9XP.FK0H read 2025-10-08 19:10:01 for Blastware's + 2025-10-07 19:14:08). + - T003LCYV.JD0H got no time at all. + - A waveform lost its stop, so its trigger was never computed and the stop + was stamped instead (K440I4LG.JK0W: 11:14:12 for 11:14:08). + - **The fix:** the last 26 bytes are now taken when they are a footer, and + the old search remains only as the fallback. + - **Decode checker:** event times 6,524 / 6,524 and histogram start dates + 63,518 / 63,518. 13 comparisons fixed, 0 regressions, 18 of 88 fields + fully match (was 16). + - **Also:** the protocol reference records where the 1995 default-clock + events come from (units back from calibration with the battery unplugged; + 17 in DL2). + - ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and + backfill. It moves the stored time of those ~14 events on prod. No schema + change. + +### Added +- **Series-4 parity in SFM: everything by serial, for both series** + (`feat/series4-sfm-parity`, merged 2026-11-04; spec + `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`). + - **One door, `DeviceAccess`.** + - A unit is addressed by its serial: UM is Series 4, BE / BA is Series 3. + The unit's own answer is checked before anything is sent. + - A Micromate's line is held between requests and released when idle or + on RADIO RING. + - One connection per unit; 423 while busy. + - **Reads, both series:** `GET /device/info`, `/device/monitor/status`, + `/device/settings`, `/device/events` and `POST /device/events/download`. + - A download is stored as the watcher stores it, through the Blastware / + IDF import path, typed. + - It never overwrites a stored event. + - SFM's MiniMate files carry Blastware's W/H type letter. + - **Changes, both series, each audited** (a `device_commands` row per + attempt), identity-checked, sent once, never retried, read back: + - start / stop monitoring; + - call-home on / off: `GET /device/call_home/state`, + `POST /device/call_home/{enable,disable}`; + - **settings**, `POST /device/settings/change`. + - **Settings, in detail:** + - A preview (dry run) shows old → new and returns a revision; a live + change must carry it, covering the unit's block and the changes asked for. + - Fields: record mode, sample rate, histogram interval, record time, + geophone trigger, the four notes, job number and its report flag, and + (MiniMate) range and alarm. + - Limits are the units' own, from Instantel's manuals, checked on the + block that would result. + - Refused before anything is sent: a monitoring unit, a stale preview, a + Micromate on its factory setup, or one whose schedule would load another + setup. SFM reads `schedule.dat`, read-only. + - **One settings codec for both series** (`micromate/setup_fields.py`): a + MiniMate's settings block is Series IV's `0x1A` layout. All 11 Blastware + compliance writes reproduce from the block before them. + - **The page:** + - units by serial, with the series badge from the unit's own answer; + - the events list and download, start / stop, the Call Home tab; + - the Config tab's Preview → Send → "the unit now holds"; + - page JavaScript in `sfm/static/`, tested through Node (no inline JS). + - **Benched on BE9441 and UM20147:** phase 4 on 2026-11-03, phase 5 on + 2026-11-04. Every change was acknowledged, read back and confirmed on the + unit's screen; both units were restored byte for byte. + - ⚠ A MiniMate's open setup menu loses a remote change when the operator + presses Cancel or Save (the menu writes its whole-block copy back). The + preview warns. + - ⚠ The Micromate scheduler switch is in no block SFM reads, so a leftover + schedule blocks a change even with the scheduler Off. + - ⚠ **Operational:** additive schema only. SFM creates `device_commands`, or + adds `sent` / `states` to an older one, on first start; this branch does not + touch `events`. No `TOOL_VERSION` bump and no backfill from this branch: + event decoding is unchanged. Production ingest (the watchers) is untouched; + the new device routes are used only from SFM's page and API. +- **A waveform's time of peak, vector-sum time and peak acceleration** (group D, + part 1 of the file-only decode). Measured on DL2 2026-11-04. + - **Time of peak** = (first peak sample − pre-trigger samples) / sample rate, + per channel including the mic. + - **The vector sum's time**: the same, on √(T² + V² + L²). + - **Peak acceleration** = the largest |v[i+1] − v[i]| × sample rate / g, which + the manuals describe as "subtracts two velocity readings and divides the + result by the elapsed time between them". + - Blastware's g is fitted: every printed acceleration in DL2 bounds it, and + together they leave [386.2236, 386.2240] in/s². + - That is 9.81 m/s² (386.2205) plus an offset not explained, as with the + mic's fitted dB offset. The standard 9.80665 m/s² fits 17,806 of + 19,479 values; the fitted value fits 19,475. + - **`PeakValues` gains** `*_time_of_peak`, `pvs_time` and `*_peak_accel_g`, + filled for waveforms only. + - **Decode checker:** 52,177 comparisons fixed, 0 regressions. Times of peak + are 6,523 / 6,524 on every channel, peak acceleration 6,522–6,523 / 6,524. + Every miss is in two 2019 files (O117I1NK.R70W on all channels, S353I5PZ + on Vert), not yet explained. + - **Not shipped yet:** peak displacement and ZC frequency. They follow the + manuals' methods (half the largest half-cycle integral; the half-cycle at + the peak), but match only 84% and 46%, so Blastware does something more. + - ⚠ **Codec change:** it rides this release's `TOOL_VERSION` bump and + backfill. No schema change; the new values are not stored in the DB or + the `.h5` yet. +- **A histogram's interval detail: frequencies, vector sums, interval size and + stop** (group B of the file-only decode). Measured on DL2 2026-11-03. + - **Frequency** = (sample rate / 2) / half-period: 527,915 / 527,915 cells + at 1024 sps and 1,725 / 1,725 at 2048. + - ✅ **Fixes #50.** `half_period_to_hz` used a fixed 512 and halved every + 2048-sps frequency. It now takes the rate (default 1024). + - Blastware prints "N/A" for a half-period of 0, ">100" (">200" at 2048) + at 5 samples or fewer, and "<1.0" below 1 Hz. + - **Each interval's vector sum**, √PVS² at the event's range. + - **Interval size:** uint16 seconds at `k − 40` (Series IV `[8:10]`). + - **Stop time:** the footer's. + - **`Event` gains** `histogram_interval_sec`, `interval_half_periods`, + `interval_pvs` and `stop_time`. + - **The `.h5` gains** `/intervals/half_period/` and `/intervals/pvs_ips`, + plus a `histogram_interval_sec` attribute. + - **Decoder:** a histogram is now walked once + (`histogram_codec.channels_from_records`). + - **Decode checker:** 508,080 comparisons fixed, 0 regressions, 34 of 88 + fields fully match (was 28). + - Frequencies on all four channels, interval size and stop date match + every DL2 histogram. + - Interval vector sum: 63,497 match, plus 17 clipped intervals now under + the saturation carve-out. Blastware prints OORANGE when the sum exceeds + the range in an interval where it clamped a channel (17 / 17). + - 4 cells sit 4e-6 past a rounding boundary and stay mismatches. + - 58 stop times are Blastware a second earlier, part of #51. + - ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and + backfill. The `.h5` additions are additive. No schema change. +- **A Blastware file's identity, battery and trigger settings** (group A of the + file-only decode). Every field is matched against every DL2 report + (2026-11-03). + - **Identity block** before the setup name: what the live read gets from + SUB FE. + - serial `k − 202`, firmware `k − 147`, DSP version `k − 138`, firmware + minor `k − 193` + - calibration date `k − 132` and "by" `k − 128` + - manufacturer `k − 94`, model `k − 72` + - Filled into `Event.device_info`; `DeviceInfo` gains `calibration_date` / + `calibrated_by`. + - Serial, Version and Calibration match 70,042 / 70,042. + - **Battery:** uint16 hundredths of a volt at `k − 190` + (`Event.battery_volts`), 70,042 / 70,042. Blastware rounds half up + (6.25 → "6.3 Volts"). + - **Trigger source:** the two bytes between the embedded event record's lead + and `fe 80`, a bitmask (`0x01` Tran, `0x02` Vert, `0x04` Long, `0x08` + MicL, `0x200` Manual). 6,524 / 6,524 (`Event.triggered_by`). + - **Trigger settings,** in Series IV's `0x1A` layout: + - the sources bitmask at `k − 19` + - the stop mode at `k − 31` (0 = Fixed) + - each channel's float32 level at label + 30 (geo in/s, mic psi) + - the mic type code at MicL + 4 (2 = Linear Weighting) + + Blastware prints a level when its channel is a trigger source and the + event wasn't Manual. Geo level 6,484 / 6,484, mic level 4,412 / 4,412 + (its dB uses 6895 Pa/psi). + - **`.h5`:** all of them as attributes (additive). + - **Decode checker:** 444,188 comparisons fixed, 0 regressions, 28 of 88 + fields fully match (was 18). + - A mic level is now compared in the unit it is printed in: K441LA17.IN0W + prints dB under psi Units. + - New carve-out `units-is-a-display-preference` (3,532 events). dB or psi + in a Blastware report is that PC's Blastware preference when it wrote the + report (Blastware manual §4, Preferences → Units and Channel), not the + unit's Microphone Units setting (MiniMate Plus manual §3.9.7). DL2's + reports switch fleet-wide in 61 clean runs by write time, and no byte of + the file separates them. + - Single-value fields are proven for that value only: Version `10.72-8.17`, + stop mode Fixed, mic type Linear. + - ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and + backfill. No schema change. +- **A Blastware file's job number, and whether Blastware shows it.** + - **Where it is:** the setup block has Series IV's `0x1A` layout here too. + The report flags sit at 9 bytes before the setup name, with bit `0x02` + meaning the job number is shown. The number is a uint16 BE at 8 bytes + before the name, and it is kept while switched off. + - **Measured:** the flag matches Blastware's JobNumber on 2,997 / 2,997 DL2 + events that print one, and 66,986 / 66,986 that don't. + - Every printed value is 1, so the value is only proven for 1. + - Hidden ones hold real numbers (802, 1012, 1013, 622). + - **`ProjectInfo.job_number_enabled` / `job_number`**, named as in + `micromate.setup_block`. + - **`write_event_hdf5`** stores both as `.h5` attributes when they were read. + - **Decode checker:** JobNumber 2,997 / 2,997, and 11 of 88 fields fully + match (was 10). 0 regressions. A job number only SFM shows now counts as a + mismatch. + - **Not in the database, the API or the PDF report yet.** That needs a + column. + - ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and + backfill (`backfill_sidecars.py` then `backfill_event_shape.py`). The new + `.h5` attributes are additive. No schema change, no migration. + +### Removed +- **`POST /device/config` and `POST /device/config/project` answer 410**, + pointing at `POST /device/settings/change`. Terra-View does not call them. + Removed with them, because they wrote a live unit through the encoder #46 + found wrong: + - `MiniMateClient.apply_config`, `set_project_info` and + `_encode_compliance_config`; + - `poc_set_project.py`, and `experiments.py`'s EXP6. + +### Protocol / Documentation +- **The parity benches in both protocol references:** + - Series III: the settings write measured end to end, the escaped-checksum + stray byte, the keypad menu writing its whole-block copy back, the alarm at + channel +38, and `[26:28]` re-set while monitoring. + - Series IV: the first setup push, with the unit's CRC equal to SFM's; the + schedule read on a real unit; the scheduler switch in none of the blocks. + - Spec and plan: `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md`, + `docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md`. +- **Histogram timing in the protocol reference (D.6.10):** + - the histogram's own event record + - the interval-time and peak-time rules + - "histograms stay on ts1" retracted in place + - CLAUDE.md records the unit + time + type key + - Docs only. +- **Group B in the protocol reference (D.6.9):** + - interval size, the stop, and per-interval frequency, with Blastware's + words (`N/A`, `>100` / `>200`, `<1.0`) + - each interval's vector sum, with its OORANGE rule + - #50's fixed-512 formula is retracted in place + - CLAUDE.md and the README roadmap follow + - Docs only. +- **Group A in the protocol reference, and the three meanings of mic + "units".** + - **D.6.8:** the identity block, the trigger-source bitmask and the trigger + settings. + - **D.6.6:** recorded data vs report units vs unit peaks, with the + MiniMate Plus and Blastware manual sections. CLAUDE.md carries the same + glossary. + - 🔶 Inferred: the histogram "terminal tail" `9c 06 00 42` is `9c 06 00` + plus the serial's `B`. + - Docs only: no code change, no migration. +- **Where file-only decoding stands, and that prod's ASCII overlay is + scaffolding.** + - **CLAUDE.md "Where things stand"** now says plainly that a paired + Blastware ASCII report overwrites SFM's decode on import, and that only + report-less events run on the decoder alone. The overlay is to be retired + at step 3 of the plan. + - The checker status is brought up to `dev`: 18 of 88 fields match on every + DL2 event, with the remaining groups A–F in the proposed order. The README + roadmap is updated to match. + - **The protocol reference** records: + - the footer as the file's last 26 bytes (D.3.3, with `[18:24]` retracted + as "fixed") + - the codec chosen by STRT[18] + - the job number + - the PVS² high word and the peak / PVS consistency check (retracting + "reads 0000") + - Blastware's interval count + - a refreshed "not read yet" list + - Docs only: no code change, no migration. +- **`docs/instantel_protocol_reference.md` gains Appendix D.6:** the bytes + and DL2 verification for every field SFM reads from a Blastware event file. + - the record type, `STRT[18]` + - the recording-setup block: sample rate, pre-trigger, record time and the + four notes + - the geophone range + - each histogram interval's PVS² + - the mic scale +- **Retracted in place:** + - `STRT[20]` as the record time: it is `00` on every DL2 file. + - The 2026-08-26 reading of sub-minute histogram records as little-endian: + they are big-endian from byte 5 (#47/#49), and the "2-word tail" is the + PVS². This is corrected in CLAUDE.md too. +- **#48 is still open.** The event file's setup block puts the pre-trigger where + the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, it is + **each event's own pre-trigger**, not the unit's setting: it varies on the + same unit on the same day, and Blastware reports it per event. So the files + say little about whether the live 1A read loses its anchor. (Corrected the + same day; the first version read the file's value as the setting.) +- **CLAUDE.md "Where things stand"** now reflects the range fix. +- Docs only: no code change, no migration. + +### Migration + +⚠ **Schema migration and backfill.** Rehearsed twice on a copy of prod's +2026-09-30 snapshot (15,432 events), before and after the parity merge, with +identical results. + +**Before you start:** +- `TOOL_VERSION` is bumped to **0.34.0**, which gates the regeneration, so no + `--force` is needed. +- **Back up `seismo_relay.db` first.** + +**Then:** +1. **Deploy.** On first start SFM migrates the database by itself. + - The events table is re-keyed `UNIQUE(serial, timestamp, record_type)` + (Migration 3): every row and id is kept and the indexes are rebuilt. + Rehearsal: 0.27 s, every row identical, integrity ok. + - `device_commands` is created. +2. **In the `sfm` container, `python scripts/backfill_sidecars.py`** re-decodes + every event file. ⚠ **Plan an overnight run:** the store holds about 64,000 + events after the 2200-day watcher forward, at about 1.5 files/s on the NAS, + so roughly 12 hours. + - **Every Series-3 histogram's time moves forward one second, in place**, + with id and review state kept. Rehearsal: 9,852 moved, 0 refused, no id + lost. + - **The same-second waveform/histogram pairs coexist** (209 in the + snapshot). + - It also creates a row for any store file that never had one (341 in the + snapshot): the known one-time behaviour, not duplicates. + - **Report-less events** pick up every new field. **Report-paired events** + keep the report's overlaid peaks, notes, sample rate and record time. +3. **`python scripts/backfill_event_shape.py --db-path bridges/captures/seismo_relay.db + --store-root bridges/captures/waveforms`** recomputes shape and offset + metrics. Rehearsal: exit 0, `cleared_stale` 0. + +**Terra-View** needs no change: it pairs twins by peak values and reads rows by +id. Moving a histogram forward one second can carry an event across a +deployment-window edge. + +**Series-4** event times do not move. + ## v0.33.0 — 2026-11-01 **SFM reads Series-3 events from the file alone, and proves it against diff --git a/CLAUDE.md b/CLAUDE.md index 8ceb078..f8cea4c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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.33.0**. +(Sierra Wireless RV50 / RV55). Current version: **v0.34.0**. Stack-level context — which repo owns what, and how the three project versions pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as @@ -10,10 +10,27 @@ pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as --- -## Where things stand (updated 2026-11-01) +## Where things stand (updated 2026-11-03) Read this first when picking the project back up. +- **🔑 Prod still leans on Blastware's ASCII report, and that is scaffolding.** + - **How it works today:** when a `_ASCII.TXT` report arrives with a + Blastware file, `WaveformStore.save_imported_bw` overlays its peaks, notes, + sample rate and record time onto SFM's decode + (`event_file_io.apply_report_to_event`). + - **Only events without a report** run on the decoder alone: all DL2 events + before 2025, and everything SFM downloads itself. + - **Why that matters:** the overlay made SFM trustworthy from day one. It + also hid how much the decoder could not yet do; until the checker (below) + there was no full list of what Blastware reports. + - **The goal is full function without Blastware (Brian, 2026-10-29).** The + README roadmap has four steps: + 1. the checker ✅ + 2. complete the file-only decode, one field group at a time + 3. switch ingest so reports are kept only for checking (retire the overlay) + 4. stop the watchers forwarding reports + - Until step 3, prod keeps the report as truth wherever one exists. - **🔑 The Series-3 decode checker (2026-10-29; v0.33.0).** - **Goal:** SFM produces everything Blastware reports, from the event file alone (spec and plan in `docs/superpowers/`). @@ -25,27 +42,74 @@ Read this first when picking the project back up. `~/dl2-archive/checker-runs/` and is never committed. - **The rule:** every mismatch is SFM's bug unless a carve-out with evidence covers it. + - **Byte layouts** of every field read from the file: + `docs/instantel_protocol_reference.md` Appendix **D.6**. - **As of v0.33.0:** - - ✅ **Match on every event:** sample rate, record time, pre-trigger, notes, - and event type (#41, from STRT[18]). - - ✅ **Geophone samples** are exact on 6,491 / 6,524 waveforms in every year. - The 33 others are the 1.250 in/s range, 8× under SFM's Normal-range - assumption. - - ✅ **Histogram PVS** = the stored per-interval PVS²: 69,919 / 70,042. - - ✅ **Mic: one count = 0.25 Pa,** with Blastware's dB offset at 81.9384. It - fails on only a few dozen events. + **Where the decoder stands on `dev`** (2026-11-03, run `20261103-213557`): + **47 of 88 fields match on every event**, up from about 6 before v0.33.0. + Everything below on `dev` shares one release and one backfill. Groups A, B + and C are done, which also fixed #50 and #51. + - 🔑 **Events are keyed unit + time + type:** `UNIQUE(serial, timestamp, + record_type)` (#51, Migration 3 in `sfm/database.py`, `dev`). + - A waveform and its histogram may share a second: 209 times in prod's + 2026-09-30 store. + - Any lookup "by event" must include the type. + - An untyped event still dedups against an untyped row. + - Rehearsed on a copy of the prod snapshot: rows and ids kept, 9,852 + histograms moved +1 s in place. + - ✅ **Match on every event:** + - sample rate, record time, pre-trigger, notes and event type (v0.33.0) + - geophone range, job number, event times (6,524 / 6,524) and histogram + start dates (63,518 / 63,518) — `dev` + - group A (`dev`, reference D.6.8): serial, version, calibration, battery, + trigger source, geo and mic trigger levels, stop mode, mic type + - group B (`dev`, D.6.9): interval frequencies, vector sums, size, stop + - group C (`dev`, D.6.10): histogram start and stop from the histogram's + own event record, interval times, and the peak dates and times + - 🔑 **"Units" means three different things — keep them apart** (reference + D.6.6): + - **Recorded data:** the mic samples and interval peaks in the file, as + raw counts with no unit. + - **Report units:** dB(L) or psi(L) in a report. + - A Blastware report uses that PC's Blastware preference at the moment + it wrote the report; carve-out `units-is-a-display-preference`. + - SFM's report uses SFM's own fixed choice. + - **Unit peaks:** the unit's own summary, in its keypad Microphone Units + setting. Shown on its screen, in Blastware's event list, and in the 0C + record. + - Where the unit stores that setting is not measured yet; a keypad test + on a bench unit would show it. + - ✅ **Geophone samples** are exact on **6,524 / 6,524** waveforms in every + year (`dev`; v0.33.0 had 6,491, its 33 others being Sensitive-range events + read 8× high). + - ✅ **Histograms** decode to Blastware's own interval table on every DL2 + file: Tran / Vert / Long interval peaks have 0 mismatches (`dev`). + - The codec is now chosen by STRT[18]. The waveform codec had been + claiming 2018 5 s histograms. + - The sub-minute layout check now tests peak ≤ PVS ≤ √3·peak. + - Blastware's "Number of Intervals" is the monitoring time ÷ the interval: + a carve-out, 8 events. + - ✅ **Histogram PVS** = the stored per-interval PVS²: 69,989 / 70,042. + **Mic:** one count = 0.25 Pa, dB offset 81.9384; a few dozen stragglers. - ❌ **Open:** - - histogram start times are 1 s early (#51) - - 35 sub-minute (5 s / 2 s) histograms decode wrongly, plus 2 one-minute - no-mic histograms (`R352HFZ7`-shaped, likely a separate cause) - - 26 histogram start dates are a day off - - the per-interval PVS is not stored + - the mic stragglers: ~20 one-minute histograms with an interval or two off - Blastware prints `OORANGE` when the vector sum alone exceeds the range (a carve-out to prove) - - ⬜ **Not read yet:** job number, ZC frequency, acceleration, displacement, - time of peak, sensor check, battery, calibration, range, units, monitor - log. + - ⬜ **Not read yet, in the order proposed** (2026-11-03): + - ~~**A. Setup fields**~~ ✅ done on `dev`. + - ~~**B. Histogram interval detail**~~ ✅ done on `dev`. Frequencies (#50), + per-interval PVS, interval size, stop. + - ~~**C. #51 timing**~~ ✅ done on `dev`. + - **D. Blastware's waveform calculations:** ZC frequency, acceleration, + displacement, time of peak. + - **E. Sensor check results.** + - **F. Monitor log:** probably not in the event file at all. + - 🔶 **#48 is still open.** The event file's setup block puts the pre-trigger + where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, + it is **each event's own pre-trigger**, not the setting: 253–256 samples at + 1024 sps, alternating on the same unit on the same day, and reported that + way by Blastware. So the files say little about whether the live 1A read + loses its anchor (reference D.6.2). - **The Series-4 LIVE wire protocol is reverse-engineered end to end (2026-09-25).** `docs/micromate_protocol_reference.md` is the Series-4 Rosetta Stone, sibling to `instantel_protocol_reference.md`. **A Micromate @@ -56,9 +120,31 @@ 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. + 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). - **✅ `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 @@ -129,8 +215,144 @@ 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. Not yet in SFM — nothing there uses the - Micromate client. + 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 `/* */` 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. + **Batch 1 fixed (2026-10-29):** #1 (`b320a53`, settings read after unescaping: + mode −7, rate −6, interval −4, record time +6), #9 (`ce441a0`, one reconnect for + the read-back), #8 (`9492e49`, downloads stored through `save_imported_bw`; since + 2026-11-02 everything comes from the file -- peaks, vector sum, mic and the range + it was recorded at -- and the unit's 0C summary is only the download check). #2 came with the + `dev` merge. **#15 retracted** -- `sent` NULL is "unknown", by design. + Final review fixes: `dbd8a91` (wake before the reconnect's identity read), + `3a1d34a` ("already stored" by Blastware name too), `a72d3a9` (the 1A write + encoder refuses a patch that would not read back -- its offsets are 1024-sps + raw ones, #46). + **Phase 4 built 2026-11-02, benched 2026-11-03:** call-home on/off by serial for + both series (`GET /device/call_home/state`, `POST /device/call_home/{enable,disable}`, + the page's Call Home tab). The MiniMate frame is Blastware's byte for byte + (`tests/test_s3_call_home_bw_frames.py`, the 4-20-26 captures). On both units, + idle, the no-op, off and on writes were all verified and agreed with the unit's + menu. ⚠ **Neither series takes a call-home change while monitoring:** a MiniMate + returns its device-info block, and a Micromate acks the write and ignores it. + SFM refuses both up front. + **Phase 5 built 2026-11-03, benched 2026-11-04:** change a unit's settings by serial, + both series (`POST /device/settings/change`; the Config tab's Preview, then Send). + Spec `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md`. + - 🔑 **A MiniMate's settings block IS Series IV's `0x1A` layout** (measured): + the 1A read assembles to 2,090 bytes headed by N = 2090, and all 11 + Blastware compliance writes reproduce from the block before them. One codec + serves both series: `micromate/setup_fields.py`. + - Limits are the units' own, from Instantel's manuals (Brian). A live send + needs its preview's revision; refused up front: monitoring, a Micromate on + its factory setup or whose schedule would load another setup. + - Retired: `/device/config` (410), `apply_config`, `_encode_compliance_config`. + - **Benched 2026-11-04, both series:** every change acknowledged, read back, + and confirmed on the unit's screen; both units restored byte for byte. The + MiniMate alarm write is measured and now on. + - ⚠ **A MiniMate's open setup menu wins:** a change sent while it is open is + lost when the operator presses Cancel or Save (the menu writes its whole-block + copy back). The preview warns; nobody in the menus while the office sends. + - ⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data + (about 1 frame in 85). The settings and waveform reads take exactly what they + asked for; other reads are unaudited for it. + - ⚠ The Micromate scheduler switch is not in any block SFM reads, so a leftover + schedule blocks a change even with the scheduler Off. + **Ring path measured the same night:** with THOR's watchdog off, a call-home + reaches THOR when nobody holds the line, and **is lost when SFM holds it** -- + the unit takes SFM's connection for the call, times out and does not retry. + 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. - **🔑 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, @@ -211,7 +433,37 @@ 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`. -- **⚠ KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB.** +- **✅ 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.**~~ `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 @@ -229,8 +481,22 @@ 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. -- **Open, not blocking:** 14 sensitive-range files show an exact 8x - (= 10.0/1.25) units discrepancy; `scripts/backfill_sidecars.py --force` also + **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~~ (**resolved on `dev` 2026-11-02:** the + range is read from the file, reference D.6.4); `scripts/backfill_sidecars.py --force` also inserts DB rows for store files that have none (one-time per store) and the dry-run does not report that count. - **After any codec change, regenerate the store** — `backfill_sidecars.py` @@ -459,6 +725,9 @@ minimateplus/ ← Python client library (primary focus) per-sample decoder — see "Waveform body codec" section below) sfm/server.py ← FastAPI REST server exposing device data over HTTP +sfm/sfm_webapp.html ← the SFM page; its JavaScript is in sfm/static/ (no inline JS, +sfm/static/ ← a stack-wide rule since 2026-11-02): device_routing.js holds the + DOM-free rules (Node-tested), sfm_webapp.js the page glue seismo_lab.py ← Tkinter GUI (Bridge + Analyzer + Console tabs) bridges/ mm_probe.py ← name the fault behind a dead unit (4 verdicts, read-only) @@ -488,7 +757,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** | ✅ **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** | ✅ **(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. | | 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 | @@ -640,6 +909,14 @@ block still covers exactly one minute: | 15 s | 4 | 92 | | 2 s | 30 | 612 | +> ⚠ **CORRECTED in v0.32.0 (#47/#49), recorded here 2026-11-02.** The +> records are **big-endian, starting at byte 5**. Each holds a uint16 peak +> and a uint16 half-period per channel, then the interval's **PVS² as a +> uint32 BE**. Record = 4 × channels + 4 bytes: 20 with the mic, 16 +> without. `stride = 12 + n × record`. The little-endian reading below was +> the same words shifted by one byte. Its "2-word tail" is the PVS² +> (reference D.6.5). + `stride = 12 + n * 20`. Block = `[00][segment][ctr uint16 LE][0a][00]`, then n x 20-byte records of 8 x uint16 **LITTLE**-endian values (`T_peak, T_halfp, V_peak, V_halfp, L_peak, L_halfp, M_peak, M_halfp`) @@ -647,6 +924,7 @@ plus a 2-word tail whose first word is `0000` on every real interval, then a 6-byte block trailer. ⚠ The standard 32-byte block is BIG-endian; this variant is LITTLE-endian. +*(Retracted: both are big-endian; see the box above.)* Recovers **415 files** (216 on BE18193, 199 on BE9440) that decoded to nothing. Ground truth `BE9440/K440L3AQ.T70H` matches its BW ASCII export @@ -674,6 +952,9 @@ block has its own tail signature. Two long-standing errors: `1e 0a 00 00`, with arbitrary bytes at `[21:23]`. Rejecting it dropped the final interval of nearly every histogram — frequently the one holding the event peak, so the file's PPV read low. +- **`[21:25]` is the interval's PVS² as a uint32 BE** (v0.33.0, reference + D.6.5). The "arbitrary bytes" above are probably its high half + (inferred). Verified against 1211 production histograms paired with their BW ASCII exports: **1211/1211 decode exactly** (interval count plus every @@ -682,11 +963,13 @@ with zero mismatches. Before: 1 of 1196. ### What's NOT solved -- **MicL channel conversion to dB(L)** — the codec emits MicL as +- ~~**MicL channel conversion to dB(L)** — the codec emits MicL as raw ADC counts (same format as geo channels), but BW's ASCII export shows mic in dB(L) with ~6 dB quantization steps. Need to map ADC counts → dB(L) for direct comparison; likely - `dB = 20*log10(|counts|) + offset` or similar. + `dB = 20*log10(|counts|) + offset` or similar.~~ **Solved in v0.33.0.** + One count = 0.25 Pa, and dB(L) = 81.9384 + 20·log10(|count|), an offset + measured from Blastware's printed values (reference D.6.6). - **Variable-prefix segment descriptors** — 3 of the 75 ground-truth production events still truncate. The walk reaches a segment header whose channel-id field is preceded by a *variable-width* prefix (2, 4 @@ -817,6 +1100,14 @@ 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.** @@ -857,6 +1148,9 @@ 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 @@ -941,6 +1235,11 @@ 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: @@ -970,6 +1269,11 @@ 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 @@ -1005,6 +1309,11 @@ 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: @@ -1029,12 +1338,18 @@ 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 @@ -1076,6 +1391,11 @@ 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: @@ -1241,6 +1561,7 @@ 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. @@ -1345,7 +1666,7 @@ Do NOT use fixed absolute offsets for sample_rate or record_time. | trigger_level_geo | float32 BE, located in channel block | | alarm_level_geo | float32 BE, adjacent to trigger_level_geo | | geo_hardware_constant (adc_scale_factor) | float32 BE at **channel_label+28** in both read (E5) and write (SUB 71) payloads — reads **6.206053** on BOTH tested units (BE11529 and BE18189); identical across all geo channels (Tran/Vert/Long) and all captures. **Confirmed 2026-04-17 from Interface Handbook §4.5**: this is the **ADC-to-velocity scale factor** = 1/sensitivity = (in/s per V). Firmware uses it as: `PPV (in/s) = ADC_voltage × 6.206053`. Cross-check: `1.61133 V (ADC full-scale) × 6.206053 = 10.000 in/s` (Normal range ✅). Do NOT write this field — it is a hardware/firmware constant. | -| geo_range (sensitivity selector) | **uint8 at channel_label+33** in both read (E5) and write (SUB 71) payloads — **CONFIRMED 2026-04-20** from 4-20-26 geo sensitivity captures: `0x00` = Normal 10.000 in/s (standard gain), `0x01` = Sensitive 1.250 in/s (high gain). Present in all three geo channel blocks (Tran, Vert, Long). **NOTE: `channel_label+20` reads `0x01` on ALL captures regardless of range setting — it is NOT this field.** Note: the "SUB 71 write offset = +29" that appears in earlier analysis was an artifact of incorrect BW-style destuffing applied to write frame data — write frame data is RAW, so the literal `0x10` bytes in the channel block header are preserved, and the offset is the same as in the E5 read payload. | +| geo_range (sensitivity selector) | **uint8 at channel_label+33** in both read (E5) and write (SUB 71) payloads (an event file's setup copy has it at label+29: reference D.6.4) — **CONFIRMED 2026-04-20** from 4-20-26 geo sensitivity captures: `0x00` = Normal 10.000 in/s (standard gain), `0x01` = Sensitive 1.250 in/s (high gain). Present in all three geo channel blocks (Tran, Vert, Long). **NOTE: `channel_label+20` reads `0x01` on ALL captures regardless of range setting — it is NOT this field.** Note: the "SUB 71 write offset = +29" that appears in earlier analysis was an artifact of incorrect BW-style destuffing applied to write frame data — write frame data is RAW, so the literal `0x10` bytes in the channel block header are preserved, and the offset is the same as in the E5 read payload. | | setup_name | ASCII, null-padded, in cfg body | | project / client / operator / sensor_location | ASCII, label-value pairs | @@ -1459,12 +1780,32 @@ 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) @@ -1475,6 +1816,7 @@ 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). @@ -1486,17 +1828,30 @@ 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 | +| 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) | | 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); 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) (⚠ 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. | --- ## 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 @@ -2071,7 +2426,7 @@ body) because writing a dial string may require DLE escaping for embedded contro - **Database** — SQLite store for events + monitor log entries; dedup by key; queryable - **Histograms** — decode histogram-mode A5 data (noise floor tracking) -- **Blastware-compatible file output** — `write_blastware_file()` and `write_mlg()` implemented. `blastware_filename()` generates correct Blastware filenames (AB0 for direct, AB0W/AB0H for ACH). **Confirmed BYTE-PERFECT against BW reference (v0.14.3, 2026-05-05):** when fed the BW 5-1-26 3-sec capture's A5 frames, the SFM-built file matches BW's saved `M529LKIQ.G10` byte-for-byte (8708 bytes, 0 differences). Live SFM downloads of event 0 (3-sec) and event 1 (3-sec continuation) both open cleanly in Blastware with full Event Reports, frequency analysis, and waveform plots. Body assembly is just contiguous concatenation of frame contributions in stream order (probe → meta@0x1002 → meta@0x1004 → samples → TERM); no stripping, no overlay, no special handling. Histogram+Continuous mode deferred (5A stream for those events embeds histogram interval records that may need different handling — untested under v0.14.x). Extension mapping: extensions encode timestamp (AB0T for ACH, AB0 for direct), NOT recording mode. Filename format: `<4-char-base36-stem>` +- **Blastware-compatible file output** — `write_blastware_file()` and `write_mlg()` implemented. `blastware_filename()` generates correct Blastware filenames (AB0 for direct, AB0W/AB0H for ACH). **SFM's own MiniMate downloads carry the W/H letter (2026-10-30):** `with_type_letter()` reads it from the file's STRT[18] (#41) on all three naming paths (device-access download, `WaveformStore.save`, the legacy `/device/event/{i}/blastware_file`); Blastware's direct downloads leave it off. **Confirmed BYTE-PERFECT against BW reference (v0.14.3, 2026-05-05):** when fed the BW 5-1-26 3-sec capture's A5 frames, the SFM-built file matches BW's saved `M529LKIQ.G10` byte-for-byte (8708 bytes, 0 differences). Live SFM downloads of event 0 (3-sec) and event 1 (3-sec continuation) both open cleanly in Blastware with full Event Reports, frequency analysis, and waveform plots. Body assembly is just contiguous concatenation of frame contributions in stream order (probe → meta@0x1002 → meta@0x1004 → samples → TERM); no stripping, no overlay, no special handling. Histogram+Continuous mode deferred (5A stream for those events embeds histogram interval records that may need different handling — untested under v0.14.x). Extension mapping: extensions encode timestamp (AB0T for ACH, AB0 for direct), NOT recording mode. Filename format: `<4-char-base36-stem>` **Serial encoding (CONFIRMED 2026-04-22):** `prefix_letter = chr(ord('B') + floor(serial_numeric / 1000))`, `serial3 = f"{serial_numeric % 1000:03d}"`. Examples: BE6907→H907, BE11529→M529, BE14036→P036, BE17353→S353, BE18003→T003. The prefix letter encodes the production generation (batch of 1000 units). @@ -2107,7 +2462,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. | +| `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) | | `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) | @@ -2119,7 +2474,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, 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 (⚠ 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/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. | diff --git a/README.md b/README.md index 2b12e08..3d5b207 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# seismo-relay `v0.33.0` +# seismo-relay `v0.34.0` A ground-up replacement for **Blastware** — Instantel's aging Windows-only software for managing seismographs. Supports both the **MiniMate Plus @@ -95,6 +95,25 @@ over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55). > > ⚠ The deploy owes a backfill; it does not move event times. See the > changelog's *Migration*. +> +> **v0.34.0 (2026-11-04)** reaches Series-4 parity and reads most of +> Blastware's report from the event file alone. +> - **Series-4 parity:** one device door by serial for both series, with +> reads, downloads, start/stop, call-home and settings changes, each audited +> and read back. MiniMate request framing is fixed (#46). +> - **The file-only decode:** 47 of Blastware's 88 report fields match on +> every DL2 event, and 8 more on all but one or two. +> - Sensitive-range events are no longer 8× high. +> - Histograms decode correctly and carry Blastware's own times (#51). +> - Interval frequencies follow the sample rate (#50). +> - New from the file: the job number, serial, version, calibration, +> battery, trigger source and levels, interval detail, peak times and +> peak acceleration. +> - **Events are identified by unit + time + type.** +> +> ⚠ The deploy migrates the events table and owes an overnight backfill that +> moves every Series-3 histogram time by one second. See the changelog's +> *Migration*. > See [CHANGELOG.md](CHANGELOG.md) for full version history. --- @@ -213,10 +232,25 @@ 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. @@ -621,16 +655,35 @@ Implementation steps (concrete): ### High-impact (unblocks product features) -- [x] **Series III waveform body codec reverse-engineering.** ✅ The body codec is fully decoded (`minimateplus/waveform_codec.py`, `histogram_codec.py`), and verified per-sample against Blastware's own exports. As of v0.33.0, geophone samples are exact on 6,491 / 6,524 DL2 waveforms against their `_XML.XML` reports, across 2016–2026. -- [ ] **SFM produces everything Blastware reports, from the event file alone.** The four-piece plan: +- [x] **Series III waveform body codec reverse-engineering.** ✅ The body codec is fully decoded (`minimateplus/waveform_codec.py`, `histogram_codec.py`), and verified per-sample against Blastware's own exports. Geophone samples are exact on all 6,524 DL2 waveforms against their `_XML.XML` reports, across 2016–2026 (`dev`; v0.33.0 had 6,491, before the geophone range was read from the file). +- [ ] **SFM produces everything Blastware reports, from the event file alone.** + + **Why this matters:** until it's done, prod overlays Blastware's ASCII report onto SFM's decode wherever a report exists. That made SFM trustworthy from day one, but it is scaffolding: the goal is full function without Blastware. + + The four-piece plan: 1. the decode checker ✅ v0.33.0 2. complete the file-only decode, one field group at a time, each proven by the checker - 3. flip ingest so reports are kept only for checking + 3. flip ingest so reports are kept only for checking (retire the overlay) 4. stop the watchers forwarding reports - **Done so far:** setup fields, notes, event type, histogram PVS, mic. + **Done so far: 47 of 88 report fields match on every DL2 event.** + - In v0.33.0: setup fields, notes, event type, histogram PVS, mic. + - On `dev`: + - the geophone range + - the job number + - histograms that decoded wrongly + - the footer: no more day-late histograms; every waveform time exact + - serial, version, calibration, battery, trigger source and levels, stop mode, mic type + - histogram interval detail: frequencies (#50 fixed), per-interval PVS, interval size, stop + - histogram start, stop, interval and peak times (#51 fixed); events keyed unit + time + type + - A Blastware report's dB/psi is its PC's preference, not anything in the event file: a carve-out. - **Next:** histogram start times (#51), the 37 histograms that decode wrongly, the job number, the geophone range (Sensitive-range events read 8×), and the values Blastware computes itself (ZC frequency, acceleration, displacement, time of peak), plus the sensor check, battery, calibration and monitor log. Design: `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`. + **Next:** + - the values Blastware computes itself: ZC frequency, acceleration, displacement, time of peak + - the sensor check results + - the monitor log + + Design: `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`. Status detail: CLAUDE.md "Where things stand". - [x] **Series IV (Thor IDF) binary codec reverse-engineering.** ✅ v0.21.0 — `micromate/idf_file.read_idf_file()` decodes both IDFW (waveform body at offset `0x0f1f`, reusing `decode_waveform_v2()`; 87–99% sample fidelity on quiet events) and IDFH (dedicated segment-based decoder: all 859 corpus files decode, 181,071 intervals, peaks within ~1.8% of sidecar values). `WaveformStore.save_imported_idf` now also projects parsed Thor data into a `bw_report` block via `micromate/idf_to_bw_report.py` so Thor events render in the existing Event Report PDF pipeline without a separate renderer. - [ ] **In-app waveform viewer accuracy.** Depends on Series III codec decode. Plot.v1 JSON pipeline + viewer skeleton already exist; will start showing real waveforms automatically once `_decode_a5_waveform` produces correct samples. Series IV waveforms come online when the IDF codec lands. - [ ] **Series IV live-device support.** Once the IDF binary is decoded, extend `micromate/` with `transport.py` / `framing.py` / `protocol.py` / `client.py` mirroring the `minimateplus/` package layout — depends on capturing Thor's wire protocol (TCP / RS-232 captures TBD). diff --git a/bridges/mm_dry_run.py b/bridges/mm_dry_run.py new file mode 100644 index 0000000..3bef3ad --- /dev/null +++ b/bridges/mm_dry_run.py @@ -0,0 +1,91 @@ +#!/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()) diff --git a/docs/instantel_protocol_reference.md b/docs/instantel_protocol_reference.md index ccd9fa9..97214a2 100644 --- a/docs/instantel_protocol_reference.md +++ b/docs/instantel_protocol_reference.md @@ -11,9 +11,24 @@ | Date | Section | Change | |---|---|---| +| 2026-11-04 | SUB 1A / 09 reads, SUB 68–74 settings write, the keypad | **SFM's settings write, benched on BE9441 (Brian at the unit; ~12 writes, each with his go).** **Every write** -- trigger 0.04 ↔ 0.05, a note, several fields at once (Project, job number + its report flag, trigger), the alarm 1.0 ↔ 1.5, and a full restore -- was acknowledged on all nine steps (`97 8C 8E×5 8D 7D 7C 96 8B 8D`), read back as sent, and **confirmed on the unit's own screen**; the unit ended byte for byte as found. Moved bytes were exactly the field's: trigger f32 at each geophone channel +30 (`+31..+33` moved), **alarm f32 at channel +38** (`+39` moved; the first Series-3 alarm write), job number `[40:42]`, its report bit `[39]` `0x02`, a note's value window. **`[26:28]`** went `01 7f` → `00 00` on SFM's first write (Blastware's value) and the unit **set `01 7f` again during the next monitoring session**. The **two bytes after the block** went out as `00 00` (Blastware sends a per-unit constant) and were taken. **🔑 Escaped-checksum artifact:** when a reply's checksum byte is itself escaped (02 / 03 / 04, ~1 frame in 85), `S3FrameParser` keeps the escape's `0x10` and strips only the byte after it, so the frame's data gains one trailing `0x10`. It hit the first live 1A read (frame B 1,026 bytes after the header); the 12 recorded reads never had. SFM's settings read and waveform read now take exactly the length they asked for. **🔑 The keypad menu wins:** a write sent while the setup menu was open was acknowledged and read back, then **lost when the operator pressed Cancel or Save** -- the menu writes its own copy of the **whole** block back (both times the block returned byte for byte to its state when the menu was opened). A keypad Cancel with nothing pending leaves the block unchanged. **While monitoring**, the 1A read returns the device-info block (SFM refuses, nothing sent), and the opening poll was answered only intermittently (2 of 3 attempts timed out). Code: `minimateplus.protocol.read_compliance_content` / `read_waveform_data_raw`, `micromate.setup_fields`; notes `~/bench-logs/2026-11-04-sfm-settings/`. | +| 2026-11-03 (5) | SUB 1A / 71 / 69 (settings read and write) | **The settings block, read and written as content (measured, BE9441's 10-26 recording and BE11529's 2026-04-20 captures).** **Read:** unescape each 1A data frame and take `data[11:]`; every frame but the last starts with one `00` that is not content; dropped, the frames join into **2,090 bytes headed by N = 2090: Series IV's `0x1A` content layout** (12 / 12 reads, Blastware's 4 × 512 + 42 and SFM's 1024 + 1024 + 42). The old "stable anchor" `be 80 00 00 00 00` is content `[12:18]` (pre-trigger −0.25 + stop mode Fixed). **Round trip:** the read after each of Blastware's two 10-26 writes equals the image it had just written, all 2,090 bytes (2 / 2). While monitoring, the read returns the device-info block (`0e 'BE9441' …`, 5 / 5). **`[26:28]`:** Blastware writes `00 00` on all 11 writes; the unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19) and sets it by itself; meaning unknown. **The two bytes after the block** (`[2090:2092]` of the 0x71 image) are Blastware's own per-unit constant -- `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's -- not the block's CRC-16/AUG, and in no reply of BE9441's three-hour session; SFM sends `00 00`. **`0x09` `[200:202]`:** Blastware echoed the unit's `8c 76` on all nine April writes; on 10-26 it read `17 17` and wrote `78 76` (read back so); meaning unknown. **Blastware re-renders the mic trigger level:** on BE11529's first write (4-20 15:19) the unit read 0.005 and 0.01 psi in its two `MicL` channel blocks (3 and 7; Series 3 carries 8 channel blocks of 48 bytes from `[1708]`, the second four prefixed `0x32`) and Blastware wrote 0.004983 and 0.010058 -- the same levels to its 0.1 dB; every other write left them alone. **Every one of the 11 Blastware writes reproduces** from the block before it with only the fields Blastware changed (plus that re-render and, on 10-26, the mic bit of `[25]`). Code: `minimateplus.protocol.assemble_compliance_content`, `read_compliance_content`, `micromate.setup_fields`; tests `tests/test_s3_settings_read.py`, `tests/test_setup_fields.py`. | +| 2026-11-03 (4) | Appendix D.6.10 (NEW), D.6.11 | ✅ **Histogram timing from its own event record (#51).** `00 28 05 00` `04 00` `fe f5` [start][stop]: Blastware's Histogram Start and Stop on 63,490 / 63,490 each; exactly one per histogram, start 0–1 s after the footer's ts1. Interval time = its end (start + (i + 1) × interval, capped at the stop), 2,308,524 / 2,308,524 rows; a peak's date/time = its interval's. Retracted: "histograms stay on ts1" (it held only while SFM's events were unique on serial + time; now unit + time + type). 47 of 88 report fields match on every DL2 event. | +| 2026-11-03 (3) | Appendix D.6.9 (NEW), D.6.10 | ✅ **Histogram interval detail.** Interval size = uint16 seconds at `k − 40`; stop = footer ts2. Frequency = (sample rate / 2) / half-period, 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048 — **#50 retracted** (a fixed 512 halved 2048-sps frequencies). Blastware's words: `N/A` (half-period 0), `>100` / `>200` (≤ 5 samples), `<1.0`. Per-interval vector sum √PVS²: 63,497 histograms; `OORANGE` when over range with a clamped channel, 17 / 17. 34 of 88 report fields now match on every DL2 event. | +| 2026-11-03 (2) | Appendix D.6.6, D.6.8 (NEW), D.6.9 | ✅ **Identity, battery and trigger, from the file.** **D.6.8:** the identity block before the setup name is SUB FE's (serial `k − 202`, firmware `k − 147`, DSP `k − 138`, calibration `k − 132` + by `k − 128`, model `k − 72`; battery uint16 /100 at `k − 190`); all 70,042 / 70,042. The embedded event record's two unknown bytes are the **trigger source** bitmask (6,524 / 6,524). Trigger sources `k − 19`, stop mode `k − 31`, per-channel trigger level float32 at label + 30, mic type at MicL + 4 (Series IV's code). **D.6.6:** recorded data vs report units vs unit peaks, with the manual sections; a Blastware report's dB/psi is the PC's preference. 🔶 `9c 06 00 42` (the histogram "terminal tail") looks like `9c 06 00` + the serial's `B`. 28 of 88 report fields now match on every DL2 event. | +| 2026-11-03 | Appendix D.3.3, D.6.1, D.6.3, D.6.5, D.6.7, §8 | ✅ **File-only decode, second pass (on `dev`).** **D.3.3:** the footer is the file's last 26 bytes (70,041 / 70,041); an earlier stop-time record fooled the first-match search on 14 files, making histograms a day late. Its `[18:24]` is **not** fixed (retracted). **D.6.1:** STRT[18] now picks the codec; the waveform codec had claimed 2018 5 s histograms. **D.6.3:** the job number (flags `k − 9` bit `0x02`, uint16 at `k − 8`; 2,997 / 2,997). **D.6.5:** the PVS² high word is non-zero above 1.28 in/s (retracted "reads 0000"), so the layout check now uses peak ≤ PVS ≤ √3·peak (34,502,955 / 34,502,955); Blastware's "Number of Intervals" is the monitoring time ÷ the interval. **§8:** where the 1995 default-clock events come from. 18 of 88 report fields now match on every DL2 event. | +| 2026-11-03 | call home (SUB 2C / 7E / 7F) | **SFM's call-home write, measured both ways.** SFM's 0x7E image (`write_image` of the 0x2C read with byte 5 set, framed ONCE) and its 0x7F confirm reproduce Blastware's 2026-04-20 enable and disable writes byte for byte (BE11529; `tests/test_s3_call_home_bw_frames.py`). Live on BE9441, idle: a no-op, on and off were all acked (0x81 / 0x80) and read back, and the unit's menu agreed. Only byte 5 changes: no unit-maintained field, unlike Series 4's `[118:120]`. Byte 5 is read from the UNESCAPED block. ⚠ Unescaping is not idempotent, so a built image must never pass through `write_image` again: a call-in time of 16:02-16:04 is `10 02`-`10 04` in the image. ⚠ **While monitoring, the unit answers the 0x2C read with its DEVICE-INFO block** ('Instantel', 'MiniMate Plus', its serial), as it answers 1A. Idle again, minutes later, it returns the call-home block. So a monitoring unit's call-home cannot be read-modify-written; SFM refuses with 'stop monitoring first'. A blind write while monitoring stays untested on purpose. | +| 2026-11-02 | Appendix D.3.1, D.6 (NEW), §15 | ✅ **Event fields SFM reads from the file alone (v0.33.0, plus the range on `dev`).** New D.6 records the bytes and the DL2 verification for each field: the record type `STRT[18]`, the recording-setup block (sample rate, pre-trigger, record time, the four notes), the geophone range (label + 29 in the setup's channel blocks), each histogram interval's PVS², and the mic scale (one count = 0.25 Pa). **Retracted in place:** D.3.1's `STRT[20]` = record time (it is `00` on every DL2 file; the "70 s" SFM used to report was `STRT[18]`, the record-type byte), and the 2026-08-26 reading of sub-minute histogram records as little-endian (big-endian from byte 5 since v0.32.0, #47/#49). **For #48:** the file's copy of the block puts the pre-trigger where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, it is each event's own pre-trigger, which varies on the same unit on the same day (253–256 samples at 1024 sps), and Blastware reports it per event. So the file says little about whether the live 1A loses its anchor, and #48 stays open. | +| 2026-10-29 | §7.6.1, §6 | **The SUB 1A settings fields are read AFTER unescaping (measured, BE9441).** The unit escapes 02/03/04/10 in its replies and `S3FrameParser` keeps the `10` of `10 02/03/04`, so on the raw bytes an escaped mode, sample rate or interval shifts every field after it: BE9441 at Histogram / 4096 sps / 2 s read 0 sps and a 4098 s interval, and a Continuous unit read as Single Shot. After `unescape_reply`, every recorded reply (4 settings, two of them Blastware's own writes: 15 min, then 2 s) has one layout: **mode anchor−7, sample rate anchor−6 (u16 BE), histogram interval anchor−4 (u16 BE, s), record time anchor+6 (f32 BE)**. ⚠ The older table's "anchor−7 = constant 0x10" (and mode at anchor−8) was the escape in front of `04` at 1024 sps — right only at that rate. The channel block (`Tran`+28 scale, +33 range, +34 trigger) and the note strings are correct on the RAW bytes and wrong unescaped; 🔶 open: a trigger/alarm float that itself contains 02/03/04/10 would read shifted there. Also measured: **while monitoring, BE9441 answered the 1A reads with its device-info block** (`BE9441`, `Instantel` — the 0x01 reply), so no settings can be read then; the decoder leaves them unknown. The 2026-10-17 anchor question is untouched: every reply measured so far carries the anchor. Fixed in SFM `b320a53`. ⚠ **The write side was not moved:** `_encode_compliance_config` still patches the raw bytes at the 1024-sps offsets (mode anchor−8), which at 2048/4096 sps rewrite the byte in front of the mode (measured on BE9441's 10-25 block); it now refuses a patch whose four fields do not read back as asked (`a72d3a9`) until rewritten on unescaped bytes (#46). | +| 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 (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-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-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-26 | S7.6.2, S15 | **MULTI-INTERVAL HISTOGRAM BLOCKS - sub-minute intervals pack several per block.** ⚠ *Corrected 2026-11-02: the records are big-endian from byte 5, not little-endian (v0.32.0, #47/#49), and the "2-word tail" is the interval's PVS². See D.6.5.* 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. | | 2026-08-25 (2) | S7.6.2, S15 | **HISTOGRAM BLOCK IS BIG-ENDIAN + terminal block tail.** The 32-byte histogram block's per-channel fields are uint16 **big-endian** (`T_peak` [5:7], `T_halfperiod` [7:9], `V_peak` [9:11], `V_halfperiod` [11:13], `L_peak` [13:15], `L_halfperiod` [15:17], `M_peak` [17:19], `M_halfperiod` [19:21]); only `block_ctr` [2:4] is little-endian. The marker is `block[4]` alone - the previous uint16 LE marker test at [4:6] forced `block[5] == 0` and thereby capped every geo peak at 255 counts (1.275 in/s), silently clipping larger peaks. The byte previously documented as a per-channel "annotation" is the high byte of the big-endian half-period, which is why it was non-zero exactly on sub-Hz intervals. Separately, the **final block of each stream carries tail `9c 06 00 42`** rather than `1e 0a 00 00` and holds arbitrary bytes at [21:23]; rejecting it dropped the last interval of nearly every histogram. Verified against 1211 production histograms paired with their Blastware ASCII exports: 1211/1211 decode exactly, plus 842,442 per-interval frequency comparisons with zero mismatches (previously 1 of 1196 files fully correct). | | 2026-08-25 | §7.6.1, §15, Appendix E (NEW) | **BODY CODEC + SCALE PASS — five findings, all verified against 75 production events paired with their preserved Blastware ASCII exports.** (1) **Geo full scale is 32000 ADC counts, not 32768** — one decoder unit (16 counts) is exactly 0.005 in/s, so 10.000 in/s = 32000 counts. Consumers dividing by 32768 read every geophone sample and derived peak **2.34% low**; the error scales with amplitude so it was invisible on quiet events and worst on loud ones. 216 per-channel comparisons: 32768 → 151/216 exact (worst 0.238 in/s on a 10 in/s event); 32000 → 216/216 exact, worst 1 LSB. Affects waveforms, histograms and series-4 alike. (2) **Wide-NN RLE `0X NN`** — the 12-bit NN encoding already known for `1X`/`2X` also applies to the `00 NN` RLE tag (runs > 252 samples). (3) **`30 NN` is not capped at NN=0x10** — data-section blocks reach at least 0x18; the length formula was already right. (4) **`40 NN` segment headers are variable width** — NN counts the previous-channel continuation deltas, so the header is `2*NN + 16` bytes; `40 01` and `40 03` occur alongside `40 02`. A header can also appear **tagless** (the NN=0 case): just the 14-byte tail. (5) **The header field documented as a "monotonic uint32 LE counter" is really `[channel_id][00][00][segment_index]`** with 0x46=Tran 0x47=Vert 0x48=Long 0x49=MicL — verified on 1697/1697 segment headers, zero disagreements. Decoders should take the channel from this field, not from rotation position. Items (2)–(5) each caused **silent channel truncation**: an unhandled tag ends the walk and the decoder returns short channels with no error. Corpus result end-to-end: exact 37 → 72, truncated 23 → 3, full-length value errors 15 → 0. New Appendix E documents the field-observed "offset" device fault. | @@ -554,6 +569,8 @@ 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 | @@ -2668,6 +2685,11 @@ Appears in event index blocks. Time-of-day fields (hour/min/sec) are absent. | `1E` | 30 | Day (0x1E = 30 decimal) | ✅ CONFIRMED | > ✅ **2026-02-26 — CONFIRMED:** The year 1995 is the **MiniMate Plus factory default RTC date**, which the device reverts to whenever the internal battery is disconnected or the real-time clock loses power. Any event timestamped around 1995 means the clock was not set. This is known device behavior, not an encoding anomaly. +> +> **2026-11-03 — where they come from (operator account, Brian):** units come back from calibration with the internal battery unplugged, so an event triggered while testing communications, before anyone sets the date, carries the default. +> - **DL2 (measured):** 17 such events on 6 units (BE9440, BE9557, BE11529, BE17354, BE18189, BE18190). All fall between 1995-09-01 12:02:02 and 1995-09-03 11:24:06, most of them between 12:02 and 13:01 on 1 September. +> - 🔶 **Inferred:** the clock restarts at a fixed default near 1995-09-01 12:00 and runs from power-up. +> - These files still end in a valid footer. SFM reads the 1995 times and reports them as `CLOCK_NOT_SET` (`models.Timestamp`). ### 8.2 9-byte format (Full Waveform Record / SUB 0C, sub_code=0x10) > ✅ **CONFIRMED 2026-04-01** — Cross-referenced against Blastware event report @@ -3170,7 +3192,7 @@ The `.bin` files produced by `s3_bridge` are **not raw wire bytes**. The logger | **RV55 DCD/DTR default** — newer Sierra Wireless RV55 firmware does not assert DCD/DTR by default, so the MiniMate Plus never detects TCP disconnect and stays idle instead of resuming monitoring. Root cause: RV55 ACEmanager `DCD Control` setting. Workaround not yet found. | MEDIUM | 2026-04-11 | Still open | | ~~**Variable-prefix segment descriptors**~~ - **RESOLVED 2026-08-25:** there is no variable prefix. The body is a chain of self-delimiting records (see S7.6.1); the 0/2/4/6/8-byte prefix was walker drift from reading `40 NN` as a segment header. All 25 affected files now chain cleanly to the `06` terminator. | RESOLVED | 2026-08-25 | Resolved 2026-08-25 | | ~~**Histogram codec drops trailing intervals (series-3)**~~ - **RESOLVED 2026-08-25.** Two errors, both in the block model. (1) The block is **uniformly big-endian**: peaks and half-periods are uint16 BE (`T_peak` [5:7], `T_halfperiod` [7:9], `V_peak` [9:11], ...); only `block_ctr` [2:4] is LE. The old uint8-peak + "annotation"-byte model silently clipped any peak above 1.275 in/s, and the "annotation" byte was really the half-period high byte - non-zero exactly on the sub-Hz intervals BW renders `<1.0`. The marker is `block[4]` alone; testing [4:6] as a uint16 LE marker forced `block[5] == 0`, which is what capped the peak at one byte. (2) The **final block of the stream carries tail `9c 06 00 42`** instead of `1e 0a 00 00`, with arbitrary bytes at [21:23]; rejecting it dropped the last interval of nearly every histogram - often the one holding the event peak. Verified on 1211 production histograms vs their BW ASCII exports: **1211/1211 exact** (interval count + every per-interval peak) and 842,442 frequency comparisons with zero mismatches; was 1/1196. | RESOLVED | 2026-08-25 | Resolved 2026-08-25 | -| ~~**Unmapped histogram block variant (415 files, 2 units)**~~ - **RESOLVED 2026-08-26.** When the histogram interval is SHORTER than one minute the device packs several intervals into a single block so each block still covers exactly one minute: 1 min -> 1 interval (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612). `stride = 12 + n * 20`. Block is `[00][segment][ctr uint16 LE][0a][00]` then n x 20-byte records of 8 x uint16 **LITTLE**-endian `T_peak,T_halfp,V_peak,V_halfp,L_peak,L_halfp,M_peak,M_halfp` plus a 2-word tail whose first word is `0000` on every real interval (a session ending mid-block leaves buffer garbage in the remaining slots), then a 6-byte block trailer. **Note the endianness flip** - the standard 32-byte block is big-endian. Ground truth `BE9440/K440L3AQ.T70H` (5,710 intervals at 15 s) decodes with 17,130/17,130 geo peaks, 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) matching its Blastware ASCII export exactly; across all 455 affected files 1,354/1,365 channel peaks (99.2%) match the device-reported PPV. | RESOLVED | 2026-08-25 | Resolved 2026-08-26 | +| ~~**Unmapped histogram block variant (415 files, 2 units)**~~ - **RESOLVED 2026-08-26.** ⚠ *Corrected 2026-11-02: the records are big-endian from byte 5, not little-endian (v0.32.0, #47/#49), and the "2-word tail" is the interval's PVS². See D.6.5.* When the histogram interval is SHORTER than one minute the device packs several intervals into a single block so each block still covers exactly one minute: 1 min -> 1 interval (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612). `stride = 12 + n * 20`. Block is `[00][segment][ctr uint16 LE][0a][00]` then n x 20-byte records of 8 x uint16 **LITTLE**-endian `T_peak,T_halfp,V_peak,V_halfp,L_peak,L_halfp,M_peak,M_halfp` plus a 2-word tail whose first word is `0000` on every real interval (a session ending mid-block leaves buffer garbage in the remaining slots), then a 6-byte block trailer. **Note the endianness flip** - the standard 32-byte block is big-endian. Ground truth `BE9440/K440L3AQ.T70H` (5,710 intervals at 15 s) decodes with 17,130/17,130 geo peaks, 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) matching its Blastware ASCII export exactly; across all 455 affected files 1,354/1,365 channel peaks (99.2%) match the device-reported PPV. | RESOLVED | 2026-08-25 | Resolved 2026-08-26 | | **Micromate (UM-series) IDF decode is ~1000x low** — e.g. `UM11402_20260406130113.IDFW` decodes a Tran peak of 0.0009 in/s against a device-reported 1.1168. Distinct from the Thor IDF path, which decodes sanely. Suspect a different per-count LSB or a body offset that does not hold for UM-series files. | MEDIUM | 2026-08-25 | Still open | | **Thor IDF per-count LSB** — after the 32000 geo full-scale correction, series-4 Thor peaks sit at a median 0.983 of the device-reported peak (was 0.960 under 32768). Closer, but the residual ~1.7% suggests Thor uses its own per-count LSB rather than the BW 16-count/0.005 in/s convention. A code comment in `sfm/waveform_store.py` claims Thor's LSB is 0.0003 in/s, which would predict Thor reading *high* — the measurement shows the opposite, so that comment is unverified. | LOW | 2026-08-25 | Still open | @@ -3397,8 +3419,16 @@ The STRT record immediately follows the 22-byte header. | 4 | 2 | `ff fe` | Fixed | | 6 | 4 | event key (key4) | 4-byte waveform key | | 10 | 4 | device-specific | NOT a repeat of key4 — device-internal field | -| 14 | 6 | device-specific | NOT zero-padded — device-internal fields | -| 20 | 1 | rectime | uint8 seconds | +| 14 | 4 | device-specific | not identified (see the retraction below) | +| 18 | 1 | **record type** ✅ | `0x46` waveform, `0x0A` histogram: 6,541 / 6,541 `…W` and 63,500 / 63,500 `…H` DL2 files (2026-11-02). See D.6.1 | +| 19 | 2 | `00 00` | zero on 70,041 / 70,041 DL2 files | + +> ⚠ **RETRACTED 2026-11-02.** This table used to end `| 14 | 6 | device-specific |` and +> `| 20 | 1 | rectime | uint8 seconds |`. `STRT[20]` is `0x00` on every DL2 file, so it is not +> the record time. Until v0.33.0, SFM read a record time from `STRT[18]`, the record-type byte, +> which is why every waveform reported "70 s" (`0x46`). It also read pre-trigger and sample count +> from `[16:18]`; both were wrong (#45). The record time and pre-trigger live in the +> recording-setup block (D.6.2). **Critical:** The STRT record must be copied verbatim from A5[0].data[7+strt_pos:] — bytes [10:20] contain device-specific values that cannot be reconstructed from protocol-level Event fields alone. @@ -3427,12 +3457,16 @@ The body is reconstructed from the raw A5 bulk waveform stream frames by strippi The footer terminates the N00 file. Its bytes come directly from the terminator A5 frame's inner content — do NOT reconstruct from event metadata. +✅ **It is the file's last 26 bytes** (2026-11-03): `0e 08` and two valid times end every one of 70,041 DL2 files. +- ⚠ **Do not search for the first `0e 08` + plausible year.** 14 DL2 files also hold an earlier record of that shape, about 1.1 KB before the end, carrying the stop time followed by zeros. +- Taking it made a histogram start at its own stop (a day late on BE9558's daily histograms). It also cost a waveform its stop, and with it the trigger time. + | Offset | Length | Field | Notes | |---|---|---|---| | 0 | 2 | `0e 08` | Fixed marker | | 2 | 8 | ts1 | Start timestamp (8B big-endian) | | 10 | 8 | ts2 | Stop timestamp (8B big-endian) | -| 18 | 6 | `00 01 00 02 00 00` | Fixed | +| 18 | 6 | varies | ⚠ **Not fixed** (2026-11-03). `00 01 00 02 00 00` in M529LIY6.N00. Elsewhere: `00 21 04 00 00 00` (K558L9XP.FK0H, K439I2WY.RK0H, T1895KDW.6J0H), `00 01 02 00 00 00` (K5575KDW.5L0W), `00 01 00 01 00 00` (S3545KFL.S60W). Not identified | | 24 | 2 | CRC | 2-byte CRC — algorithm unconfirmed | **CRC:** The 2-byte CRC at footer[24:26] has an unconfirmed algorithm. In M529LIY6.N00 it reads `fe da`. Attempts to match CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), and 40+ polynomial/init combinations all failed. The writer copies it verbatim from the terminator frame. @@ -3576,6 +3610,10 @@ observed) and does NOT follow the AB0T formula. **DLE-shift offset note for reading recording_mode from N00/9T0 body:** +> ⚠ **2026-11-02:** this note finds the block by the 6-byte anchor. In an event file that anchor +> exists only when the event's own pre-trigger is exactly −0.25 s: 3,886 / 6,541 DL2 waveforms, +> and no histogram. Find the block by its setup name instead (D.6.2). + The compliance block in the file body has been through `_strip_inner_frame_dles`. The 0x10 constant at logical `anchor−7` (between recording_mode and sample_rate_HI) gets stripped when sample_rate_HI = `0x04` (1024 sps), because `0x10` precedes `0x04 ∈ {0x02,0x03,0x04}`. After stripping, the anchor shifts left by 1, so: | 1024 sps (strip occurs) | 2048 or 4096 sps (no strip) | @@ -3594,6 +3632,329 @@ file[anc−4]: histogram_interval_HI file[anc−3]: histogram_interval_LO ``` +### D.6 Event fields read from the file alone ✅ 2026-10-29 → 2026-11-02 + +Since v0.33.0, SFM decodes the fields below from an event file's bytes alone: no filename, no +Blastware report. The code is in `minimateplus/event_file_io.py`, `histogram_codec.py` and +`waveform_codec.py`. + +Each field was proven by the decode checker, `scratch/check_s3_decode.py`. It compares SFM's +decode with Blastware's `_XML.XML` report for every DL2 event: 70,042 events, 2016–2026, local +copy in `~/dl2-archive`. Counts below are from that archive unless stated otherwise. + +#### D.6.1 Record type — `STRT[18]` ✅ + +| `STRT[18]` | Type | DL2 | +|---|---|---| +| `0x46` | Waveform | 6,541 / 6,541 `…W` files | +| `0x0A` | Histogram | 63,500 / 63,500 `…H` files | + +- The 5A stream shows the same byte after the STRT keys (§7.8.5, `data[35]`). +- The filename's `W` / `H` is only a cross-check. On a disagreement SFM logs it and keeps the + byte (#41). +- Checker, event type: 70,042 / 70,042. +- **It also picks the codec** (2026-11-03). Trying the waveform codec first handed it BE9440, + BE9557 and BE17354's 2018 5 s histograms. It accepted them and returned about 5× too many + "samples" (K440HDXX.XH0H: 44,504 for Blastware's 6,976). + +#### D.6.2 Recording-setup block — sample rate, pre-trigger, record time ✅ + +**Find the block by structure:** `1c 08`, then the setup name (1–40 printable ASCII), then `00`. +That pattern occurs exactly once in every DL2 file. Do not search for the name "Standard +Recording Setup": 37% of DL2 files use another name. + +Offsets are from `k`, the first byte of the setup name: + +| Offset | Type | Field | Notes | +|---|---|---|---| +| `k − 42` | uint16 BE | sample rate | 1024 / 2048 / 4096 | +| `k − 36` | float32 BE | pre-trigger | seconds, ≤ 0: `−0.25` is a quarter second before the trigger. **This event's own length, not the unit's setting** (below) | +| `k − 32` | 2 bytes | — | `00 00` on 70,041 / 70,041 files | +| `k − 30` | float32 BE | record time | seconds | + +- Pre-trigger samples = `round(−pre-trigger × sample rate)`. +- A histogram carries the block too, with pre-trigger `0.0` (63,500 / 63,500). Blastware reports + no record time or pre-trigger for a histogram, and SFM reports none. +- Sample rate, record time and pre-trigger match Blastware on every DL2 event that reports them + (#44, #45). + +⚠ **The file's pre-trigger is the event's, not the setting (measured 2026-11-02).** +- **It varies from event to event on the same unit, often on the same day.** BE18193 has both + −0.25 and −0.248 on 2026-08-21. + - At 1024 sps the common values −0.25, −0.249, −0.248 and −0.2471 are 256, 255, 254 and 253 + samples. + - At 4096 sps, BE18193's events range from −0.002 to −0.249 s. +- **Blastware reports the same per-event value** as `Pre-triggerLength`, for example + `-0.094 sec` for `T193KMX5.4Z0W`. +- 🔶 Inferred: the unit's setting stays fixed while the captured length falls short of it. Why it + falls short is unknown. + +**What this means for #48 (the 1A "stable anchor"):** +- This is the 1A compliance layout. Sample rate at anchor − 6 and record time at anchor + 6 + (§7.6.1) put the anchor at `k − 36`, so the 6-byte `be 80 00 00 00 00` is a pre-trigger of + −0.25 s followed by the `00 00` at `k − 32`. +- **In a file**, the anchor bytes appear only when that event's pre-trigger is exactly −0.25 s: + 3,886 / 6,541 waveforms, and no histogram (histogram files store 0.0). A file parser that + searches for the anchor breaks on the rest. SFM's file decoder finds the block by its setup + name instead. +- **The live 1A read holds the setting, not an event's length.** So these files say little about + whether the live read loses its anchor; #48 is still unsettled. +- `k − 32 : k − 30` is `00 00` on all 70,041 files. 🔶 If `[17]` is the stop mode, as on + Series IV, no DL2 event was recorded in Auto stop mode, so the archive cannot test that case. +- The two blocks differ in at least one field. A live 1A in Histogram mode showed the anchor + (−0.25 s), but histogram files store 0.0. + +#### D.6.3 Notes — four label/value pairs after the name ✅ + +- After the name's `00`, NUL-terminated `label`, `value` pairs fill four slots, in order: + project, client, operator ("User Name") and sensor location ("Seis Loc"). +- **Read them by position, never by label.** Blastware lets the operator relabel the slots + ("Seis. Loc:", "Location:", "Project: "). +- An empty value means none. +- They match Blastware on every DL2 event. +- Not read yet: extended notes. + +**Job number** ✅ 2026-11-02, in Series IV's `0x1A` layout (`[39]` report flags, `[40:42]` the +number): + +| Offset | Type | Field | +|---|---|---| +| `k − 9` | uint8 | report flags: bit `0x02` = job number shown | +| `k − 8` | uint16 BE | job number, kept while not shown | + +- **The flag** matches Blastware's `JobNumber` on 2,997 / 2,997 DL2 events that print one, and + 66,986 / 66,986 that don't. +- **The value** matches on all 2,997, but every printed value is 1, so it is only proven for 1. + Hidden ones hold real numbers (802, 1012, 1013, 622). +- Bit `0x04` is also seen (2,311 files); it is not identified. + +#### D.6.4 Geophone range — the setup's channel blocks ✅ 2026-11-01 + +The channel blocks follow the notes, within 2,000 bytes of the name: `00 00 01` then `Tran` / +`Vert` / `Long`. The range is the byte at label + 29, where label is the first byte of +`Tran` / `Vert` / `Long`: + +| label + 29 | Range | Full scale | +|---|---|---| +| `0x00` | Normal | 10.000 in/s | +| `0x01` | Sensitive | 1.250 in/s | + +- It matches the report's `GeoRange` on 70,042 / 70,042 events. The three channels agree on + every event, and 35 are Sensitive. +- The live 1A carries the same byte at label + 33 (§7.6, confirmed 2026-04-20). +- Full scale is 32,000 counts at either range, so a Sensitive count is 8× smaller. +- Until `dev` `057df47` (2026-11-02), SFM assumed Normal and read every Sensitive event 8× high. +- If the channels disagree, a value is unknown or a block is missing, SFM reports no range, logs + a decode problem and assumes Normal. + +#### D.6.5 Histogram interval peak vector sum ✅ 2026-10-30 + +Each interval stores its peak vector sum **squared**: + +| Block | Where | Type | +|---|---|---| +| Standard 32-byte block (intervals of a minute or more) | `[21:25]` | uint32 BE | +| Sub-minute record | the record's last 4 bytes | uint32 BE | + +- `PVS = √value × unit`. The unit is 16 counts: 0.005 in/s at Normal, 0.000625 in/s at + Sensitive. +- **The event's PVS is the largest interval's.** Combining the three channel peaks instead read + high on 86% of DL2 histograms, because the peaks can come from different moments. +- **Verified:** √value matches Blastware's "Geo PVS" on 34.5 M DL2 sub-minute intervals, and the + event PVS matches on 69,989 / 70,042 events (`dev`, 2026-11-03). +- **A consistency check** (2026-11-03): an interval's vector sum is never below its largest + channel peak, nor above √3 times it, give or take one unit of rounding. That holds on + 34,502,955 / 34,502,955 DL2 sub-minute intervals, and is what the codec now uses to recognise + a sub-minute record layout. +- 🔶 On the stream's last block, the "arbitrary bytes at [21:23]" in the 2026-08-25 note are + probably the high half of this field (inferred from the layout, not measured). + +**Sub-minute records (corrected in v0.32.0, #47/#49):** +- They are **big-endian, starting at byte 5** of the block. +- Each holds, per channel, a uint16 peak and a uint16 half-period (Tran, Vert, Long, and MicL + when the mic is on), then the uint32 PVS². +- Record = 4 × channels + 4 bytes: 20 with the mic, 16 without. `stride = 12 + n × record`. + +> ⚠ **RETRACTED:** the 2026-08-26 notes (Changelog, §15) read these records as 8 × uint16 +> little-endian after a 6-byte header. That was the same big-endian words shifted by one byte. +> Their "2-word tail whose first word is 0000" is the PVS², whose high word reads `0000`. +> +> ⚠ **RETRACTED 2026-11-03:** "the high word reads `0000`" holds only on quiet intervals. It is +> non-zero above 1.28 in/s. The layout check required it, so a one-block histogram with a loud +> interval was not recognised at all (T193KR5M.X90H, K440HA3C.JM0H, R352HFZ7.530H). The check is +> now the consistency test above. + +**Blastware's "Number of Intervals" is the monitoring time ÷ the interval** (measured +2026-11-03), from the footer's start and stop: +- It is exact on T193KSWP.FF0H (2,880), M462KSWR.1R0H (1,650) and T193KY0A.740H (6,390). +- When the unit never wrote the last minute, the file holds one block fewer (30 intervals at + 2 s). Blastware's own interval table lists only the stored intervals, which is what SFM + decodes. +- A decode-checker carve-out (`interval-count-is-duration`) covers the 8 DL2 events where the + two differ. + +#### D.6.6 Mic ✅ v0.33.0 + +- One count = **0.25 Pa**, so psi = count × 0.25 / 6894.757. +- dB(L) = **81.9384** + 20·log10(|count|). + - The exact value, 20·log10(0.25 Pa / 20 µPa), is 81.9382. Blastware's printed values pin the + offset in [81.9383, 81.9385] instead. + - With the exact value, 280 events mismatched, all at count 129. + - float32 rounding does not explain the difference. +- **Verified:** interval psi mismatches fell from 42,783 to 26, and mic peak mismatches from 345 + to 40. + +**Three things share the word "units". Keep them apart** (2026-11-03): + +| Name | What it is | Its units are set by | Where it shows | +|---|---|---|---| +| **Recorded data** | the mic samples and interval peaks in the event file | nothing: they are raw counts | the event file | +| **Report units** | dB(L) or psi(L) in a report | Blastware's report: the PC's preference (Blastware manual 714U0301 Rev 22 §4, Preferences → Units and Channel). SFM's report: SFM's own fixed choice (PDF PSPL in dB(L), plot in psi) | a Blastware report, an SFM report | +| **Unit peaks** | the peaks the unit works out for its own summary | the unit's Microphone Units setting: psi(L), dB(L) or Pa(L), on the keypad (Right Arrow + Setups) or from Compliance Setup → Special Setups (MiniMate Plus manual 716U0101 Rev 15 §3.9.7) | the unit's screen, Blastware's event list, the 0C record on a live download | + +- A Blastware report converts the recorded counts in its PC's preference. That is why DL2's + reports flip dB ↔ psi fleet-wide, in 61 clean runs by report-write time. The decode checker's + `units-is-a-display-preference` carve-out covers it. +- 🔶 **Where the unit stores its own setting, and its unit peaks, is not measured.** Blastware's + event list must read the unit peaks from somewhere, so they are probably in the event file, + perhaps near the embedded event record. +- **To settle it (proposed, not done):** on a bench unit, change Microphone Units on the keypad, + then diff a read-only `1A` read and a short recorded event. + +#### D.6.8 Identity, battery and trigger ✅ 2026-11-03 + +**The identity block** sits before the setup name. It is what the live read gets from SUB FE +(`DeviceInfo`); offsets are from `k`: + +| Offset | Content | DL2 | +|---|---|---| +| `k − 202` | serial number, NUL-terminated | 70,042 / 70,042 | +| `k − 193` | firmware minor (`0x11` = 17), as SUB EA | — | +| `k − 190` | battery, uint16 BE, hundredths of a volt | 70,042 / 70,042 (Blastware rounds half up: 6.25 → "6.3 Volts") | +| `k − 147` | firmware, `"S338.17"` | | +| `k − 138` | DSP version, `"10.72"` | Version 70,042 / 70,042 as `V {DSP}-{firmware after "S33"} {model}`; only `10.72-8.17` occurs, so the rule is proven for that alone | +| `k − 132` | calibration date, `dd mm yyyy` (BE year) | Calibration 70,042 / 70,042 as `{Month} {d}, {yyyy} by {k − 128}` | +| `k − 128` | calibrated by, `"Instantel"` | | +| `k − 94` | manufacturer, `"Instantel"` | | +| `k − 72` | model, `"MiniMate Plus"` / `"BlastMate III"` | | + +- `k − 180 … k − 149` hold eight float32s (1.0, 8.0, then 1.0s). Not identified. +- 🔶 **Inferred, not measured:** the three bytes before the serial are `9c 06 00`. With the + serial's `B` (0x42) that makes `9c 06 00 42`, the histogram codec's "terminal tail". It looks + like the start of this record rather than the end of a block. Every serial starts with B + (BE… / BA…). + +**The trigger source** is in the embedded event record (§7.8.9). The two bytes between its lead +`00 28 05 00` and `fe 80`, a uint16 BE bitmask, were "unknown" until now: + +| Value | Blastware's Trigger | +|---|---| +| `0x0001` | Tran | +| `0x0002` | Vert | +| `0x0004` | Long | +| `0x0008` | MicL | +| `0x0200` | Manual | + +That holds on 6,524 / 6,524 waveforms. + +**Trigger settings,** in Series IV's `0x1A` layout: + +| Offset | Content | DL2 | +|---|---|---| +| `k − 19` | trigger sources: `0x07` geophones, `0x08` mic (`0x80` seen once, not identified) | — | +| `k − 23` | active sensors, `0x0f` (all four) | 69,975, `0x07` on 8 mic-less files | +| `k − 31` | stop mode: 0 = Fixed | 6,524 / 6,524, the only value in DL2 | +| channel label + 30 | float32 trigger level: geophones in/s, mic psi | geo 6,484 / 6,484, mic 4,412 / 4,412 | +| MicL + 4 | mic type code: 2 = Linear Weighting, as Series IV | 70,034 / 70,034, the only value | + +- **Blastware prints a trigger level only when its channel is a trigger source** and the event + was not Manual. +- **For the mic level in dB, Blastware converts with 6895 Pa per psi.** That gives 4,272 / 4,272; + the exact 6894.757 gives 4,271, failing one boundary case (0.01 psi → "130.8 dB(L)"). +- **The file's channel block is the 1A's, 4 bytes earlier.** Compare the 1A's scale constant at + +28 and range at +33 with the file's +24 and +29. + +#### D.6.9 Histogram interval detail ✅ 2026-11-03 + +**Interval size** is a uint16 count of seconds at `k − 40` (Series IV `[8:10]`): 2, 5, 15, 60 or +300. It matches Blastware's IntervalSize ("1 minute", "5 seconds", …) on 63,518 / 63,518 DL2 +histograms. **The stop** is the footer's ts2: 63,460 / 63,518. The other 58 are Blastware a +second earlier, the #51 family. + +**Each interval's frequency** comes from its half-period in samples: +`frequency = (sample rate / 2) / half-period`. That matches 527,915 / 527,915 printed cells at +1024 sps and 1,725 / 1,725 at 2048. +- ⚠ **RETRACTED (#50):** "frequency = 512 / half-period". 512 is half the sample rate at + 1024 sps only; at 2048 sps it halved every frequency. + +Blastware prints these words instead of a number, on ~3.1 M DL2 cells: + +| half-period / frequency | printed | +|---|---| +| half-period 0 | `N/A` | +| half-period ≤ 5 samples | `>100` at 1024 sps, `>200` at 2048 | +| below 1 Hz | `<1.0` | +| below 10 Hz (20 at 2048) | one decimal | +| otherwise | a whole number | + +All four channels match every DL2 histogram. + +**Each interval's vector sum** is √PVS² (D.6.5) at the event's range: 63,497 histograms match. +- Blastware prints `OORANGE` for an interval's vector sum above the range when it also clamped + a channel in that interval: 17 / 17 cells. The decode checker's saturation carve-out covers + it. +- 4 cells sit about 4e-6 past a rounding boundary. Blastware's arithmetic is a hair lower; they + stay counted as mismatches. + +#### D.6.10 Histogram timing — the histogram's own event record ✅ 2026-11-03 (#51) + +**A histogram carries an embedded event record like a waveform's** (§7.8.9): + + 00 28 05 00 04 00 fe f5 [start 8 B] [stop 8 B] + lead source marker dd mm yyyy 00 hh mm ss (as the footer) + +- **Source `04 00`** sits where a waveform's trigger-source bitmask goes (D.6.8). +- **The start is Blastware's Histogram Start Time** on 63,490 / 63,490 DL2 histograms, and the + stop is its Stop Time on 63,490 / 63,490. +- On all 63,500 there is exactly one such record. Its start is 0 or 1 s after the footer's ts1 + (1 s on 61,645), and its stop 0 or 1 s before the footer's ts2 (1 s on 57). +- That makes the footer's start a second early on 97%. #51 had read it as SFM's error; it is + the footer's own convention. + +**What follows from the start:** + +| Field | Blastware's rule | DL2 sample | +|---|---|---| +| Each interval's printed time | its end: start + (i + 1) × interval, capped at the stop | 2,308,524 / 2,308,524 rows | +| Each peak's date and time (Tran, Vert, Long, vector sum, mic) | those of the interval holding its first maximum | 2,000 / 2,000 each | + +> ⚠ **RETRACTED 2026-11-03:** "histograms stay on ts1". That held only while SFM's events +> table was unique on (serial, timestamp). A waveform and its histogram share a second in +> Blastware's timing (209 times in prod's 2026-09-30 store). SFM's events are now keyed on +> unit + time + type. + +#### D.6.11 Not read from the file yet + +*Updated 2026-11-03. 47 of 88 report fields now match on every DL2 event.* +- **Fields not read yet:** + - extended notes + - the values Blastware computes: ZC frequency, acceleration, displacement, time of peak + - sensor check results + - monitor log +- **Open cases:** + - about 20 one-minute histograms with a mic peak an interval or two off + - Blastware prints `OORANGE` when an event's vector sum alone exceeds the range, with no + clamped channel (a carve-out still to prove; the interval version is proven, D.6.9) +- **Resolved on `dev`, 2026-11-02 → 03:** + - the 37 histograms that decoded wrongly (D.6.1, D.6.5) + - the 26 histogram start dates a day off (D.3.3; 17 of them were the same 5 s files, timed + as waveforms) + - the job number (D.6.3) + - identity, battery, trigger source and trigger settings (D.6.8); Units is Blastware's + preference (D.6.6) + - histogram interval detail: frequencies (#50), vector sums, interval size, stop (D.6.9) + - histogram start, stop, interval and peak times (#51, D.6.10) + --- *All findings reverse-engineered from live RS-232 bridge captures.* diff --git a/docs/micromate_protocol_reference.md b/docs/micromate_protocol_reference.md index 39d7ccb..6b134d6 100644 --- a/docs/micromate_protocol_reference.md +++ b/docs/micromate_protocol_reference.md @@ -1782,6 +1782,36 @@ 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 @@ -1895,6 +1925,15 @@ at `payload[3:5]`: | 2nd | `0x0002` | 535 B | the file body | | 3rd | `0x0000` | 11 B | all zeros = **end of file** | +✅ **SFM reads the schedule this way, read-only (2026-11-03, phase 5)** -- +`MicromateProtocol.read_file` / `MicromateClient.read_schedule`, frames equal to +THOR's byte for byte (`tests/test_micromate_schedule.py`). Two details the table +above leaves out: the `0x94` request carries **`params[3] = 1`**, and the **first** +`0x48` carries **`params[7] = 1`** (the later ones all-zero params); both `0x48` +offsets are `0xFFFF`. A long file is **written** in 1,024-byte `0x8E` pieces +(the five-entry *actioncheck* schedule went as 1,024 + 280). ⚠ Unmeasured: what +`0x94` / `0x48` return for a unit with no schedule file. + ⚠ This is the single most consequential find of the session, because it is not specific to the scheduler. **`callhome.MMB` is a file too**, and the call-home config is the last unsolved piece of the project. Reading it should be a @@ -2187,6 +2226,13 @@ 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 @@ -2527,6 +2573,28 @@ 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. @@ -2634,10 +2702,82 @@ noted, which is cheap to collect during any future ACH capture. Neighbouring bytes: `write[117]` is `0x03`, lining up with Series III's `num_retries` of 3, and `write[120:122]` is `00 3c` = 60. +#### Bench 2026-11-03: SFM's own call-home writes to UM20147 + +SFM's audited `POST /device/call_home/{enable,disable}`, one send per go. +Audit records are in the bench DB. + +**Measured, idle:** +- UM20147 reads `content[5] = 0x01` for on. It **accepts `0x00` for off**, a + value THOR was never seen writing. The read-back reads off, and the unit's own + menu said "Auto Call Home: Disabled"; on again, "Enabled". +- **A no-op write is acked** (`0x81`, `0x80`), and `[118:120]` does **not** move: + `8fab` → `8fab`. +- **Flipping bit 0 of `[5]` moves `[118:120]` by XOR `0x6D7D`, both directions:** + `8fab` ↔ `e2d6`. That is the same XOR as UM12947's `0x04` ↔ `0x05` above, on + a different unit with a different block. Writing the original block back + restores the original value (`8fab`). + +This **settles the open question above (hash vs nonce): it is not a per-write +nonce.** The field is a function of the block's content, and the fixed delta +for a fixed bit flip is the signature of a linear checksum (CRC family) over a +region that includes `[5]`. The fixed-delta part is *inferred*. A desk lead: +solve the polynomial from the deltas; the earlier sweep's regions or variants +were wrong. + +**Measured, monitoring:** +- The unit returns its **real** call-home block (`00 7C DC`…). +- It **acks** a `0x7E`/`0x7F` write but **does not apply it**: three read-backs + over 3 s were unchanged, and `[118:120]` did not move. After the stop, + call-home still read on, so the write was **ignored, not staged**. +- Its own menu refuses the call-home screen while monitoring: **"Feature + disabled while monitoring"**. +- SFM therefore refuses a call-home change while monitoring (`f35845d`). + +**Measured, also:** +- A stop with call-home on started a call-in **after** the stop's ack. SFM hung + up within about 1 s, and the call **reached THOR**: the session's histogram + arrived. (2026-10-29 Run A lost the call: there the ring replaced the ack.) +- UM20147's clock read one hour ahead after daylight saving ended (16:09:25 at + 15:09:22 EST). + ⚠ Beyond the enable byte and the dial string, **the field map is not established** — only one setting was varied. Series III's offsets are a starting hypothesis, not a transfer. +#### Bench 2026-11-04: SFM's first setup push (UM20147) + +SFM's audited `POST /device/settings/change`, one send per go (Brian at the +unit). Notes: `~/bench-logs/2026-11-04-sfm-settings/`. + +**Measured:** +- **The setup push works as THOR's.** Trigger 0.6 → 0.5, then a five-field + change (Location, Client, job number + its report flag, record time), then a + full restore. Each send was THOR's seven frames, acknowledged in THOR's order + (`25 97 8C 7D 7C 8E 8D`), read back as sent, and confirmed in the unit's menu. + The setup block ended byte for byte as found, CRC included. +- **The unit's recomputed CRC equals SFM's** (`with_crc`): after the first push + the stored block equalled SFM's computed image byte for byte, CRC `ea8d` + included. +- **`schedule.dat` read on a real unit** (`0x94` → `0x6B`; `0x48` → descriptor + `04 00 … 01 … 01`, body, all-zero end). UM20147 holds a leftover THOR + schedule: repeat on, 07:00, start monitoring with + `Fay - Commercial Street - Irish Center.mmb`. The unit runs `test2.MMB`, so + SFM blocked the change, as designed. +- 🔑 **The scheduler On/Off switch is in none of the blocks SFM reads.** With + the keypad switch Off, then On (saved), these were byte for byte identical: + `0x08` prefs, `0x2E`, `0x1A`, `0x2C`, `0x41` and `schedule.dat`. The + firmware's `SysPref.bMonitorScheduler` lives elsewhere. THOR's end-of-push + `0x47` pair (`params[7]` 1 then 3; replies `04 00 … 0N … 00 01`) was only + ever captured with the switch On. **Next:** a THOR bridge recording with the + switch Off (parked for the work-hours project). +- **While monitoring**, a settings preview and a live attempt were both refused + on the run state before any block was read (409, nothing sent, 0 write frames). +- **With call-home off, a stop goes straight to idle** (`monitoring` → + `idle`): no calling-home state and no ring. +- Call-home `0x01` ↔ `0x00` was taken again, both ways. The plan's + "unobserved" warning is retired for those values. + ## What the THOR manual settles about the ACH session (2026-09-24) Source: `manuals/723U0201 THOR Operator Manual Rev 08.pdf` §6.2, §3.6. @@ -2870,6 +3010,58 @@ 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.`. + +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 @@ -2878,6 +3070,17 @@ mechanism depends on that connection existing. 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.** @@ -4113,8 +4316,110 @@ 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.** @@ -4131,12 +4436,15 @@ 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` + acks `0x69` / `0x68`. ✅ **Originated by SFM 2026-10-25** on UM20147 (4 sends, + all acked and verified) — no longer untested - **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. +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.)* - `0x1F` (advance event pointer) — non-destructive on Series III but it does move device state, so it is parked with the rest diff --git a/docs/superpowers/plans/2026-10-20-sfm-device-access-phase1a.md b/docs/superpowers/plans/2026-10-20-sfm-device-access-phase1a.md new file mode 100644 index 0000000..1034724 --- /dev/null +++ b/docs/superpowers/plans/2026-10-20-sfm-device-access-phase1a.md @@ -0,0 +1,2400 @@ +# SFM device access, phase 1a — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** SFM can identify a unit, read its status and read its settings +through one series-neutral contract. The unit is named by serial + address +and works the same for a Series 3 (`BE…`/`BA…`) or Series 4 (`UM…`) unit. +Micromates get a held session ("stay on the line"). + +**Architecture:** A new package `sfm/device_access/` sits between the +`/device/*` handlers and the two device libraries: +- The serial prefix picks a series adapter. +- A per-unit lock gives one connection per unit. +- Series-4 sessions stay open, with keep-alive, idle hang-up and ring safety. +- Every library exception becomes one of a few typed errors with a fixed HTTP + status. + +Handlers take an optional `serial`. With it they return the shared models; +without it they run exactly as today. + +**Tech Stack:** Python ≥ 3.10, FastAPI 0.135 (already used), pyserial (already +a dependency), pytest. No new dependencies. + +**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`. +This plan is phase **1a**. Event list/download (1b) and the webapp (1c) are +separate plans. + +## Global Constraints + +- **Reads only.** The Series-4 path may call only `connect()`, `get_state()`, + `get_setup()`, `get_event_count()`, `read_unsolicited()` and + `protocol.poll()`. The Series-3 path may call only `connect()`, `poll()` and + `get_monitor_status()`. Nothing that changes a unit is sent in this phase. +- **Never put Series-3 bytes on a Micromate's wire.** Nothing under + `sfm/device_access/s4.py` may import `minimateplus.protocol`, + `minimateplus.framing` or `minimateplus.client`. `SESSION_RESET` (`41 03`) + has never been sent to a Micromate. Only `minimateplus.transport` is shared. +- **Requests without `serial` behave exactly as today.** The legacy Series-3 + code path in each handler is left untouched. +- Serial prefixes: `UM` → Series 4; `BE`, `BA` → Series 3; anything else → + 422. Serials are compared after `.strip().upper()`. +- Timings (spec): lock wait **20 s**, keep-alive **60 s**, idle hang-up + **300 s**, reaper tick **5 s**. +- Error statuses (spec): + + | status | when | + |---|---| + | 503 | could not connect / connection lost / unit started calling home | + | 504 | connected, the unit did not answer | + | 423 | unit busy | + | 409 | wrong unit | + | 422 | bad input | + | 502 | malformed reply | + | 501 | not supported yet | + +- Default serial baud when the caller gives none: Series 3 **38400**, Series 4 + **115200**. +- ⚠ **Handlers are called directly in tests.** Their FastAPI `Query(...)` + defaults are `FieldInfo` objects, not values, so every test call must pass + every parameter explicitly. The same applies to one handler calling + another. `httpx` is not installed, so `TestClient` tests are skipped + silently; do not use them. +- Feature branch: do **not** edit `CHANGELOG.md` (it is written on `dev` at + merge). +- Every commit message ends with: + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 + ``` +- Run tests with `.venv/bin/python -m pytest`. The full suite currently + reports **16 failed, 541 passed, 46 skipped**: the 16 failures are + pre-existing, in `test_bw_ascii_report.py` (15) and `test_event_file_io.py` + (1). That baseline must not change except by new passing tests. + +## Review Focus + +1. **A serial typed in lower case or with spaces** (`" um20147"`) is accepted + and treated as `UM20147`, never rejected → Task 3. +2. **Two requests for the same unit at once** (the webapp fires three): the + second waits, then gets 423. A second connection is never opened → Tasks 4 + and 8. +3. **The modem dropped an idle line** (2-minute TCP idle timeout): the next + request calls up again quietly instead of failing → Task 8. +4. **A different unit answers at the address** (moved modem, stale IP): 409, + the connection is closed, and nothing further is sent → Tasks 5 and 6. +5. **`RADIO RING` arrives mid-request or while idle**: the line is released at + once, the caller gets a clear 503, and the next request calls up fresh → + Tasks 6 and 8. + +--- + +## File Structure + +| path | responsibility | +|---|---| +| `micromate/client.py` (modify) | fix `is_open()`; add `get_event_count()` and `read_unsolicited()` | +| `sfm/device_access/__init__.py` | public exports | +| `sfm/device_access/errors.py` | typed errors with HTTP statuses; `translate()` | +| `sfm/device_access/series.py` | serial normalisation; prefix → series | +| `sfm/device_access/models.py` | `UnitAddress`, `UnitInfo`, `UnitStatus`, `UnitSettings` | +| `sfm/device_access/locks.py` | per-unit lock with timeout | +| `sfm/device_access/s3.py` | Series-3 adapter (connect-per-request) | +| `sfm/device_access/s4.py` | `RingWatchTransport`, `Series4Session`, Series-4 operations | +| `sfm/device_access/access.py` | `DeviceAccess`: dispatch, sessions, hang-up, reaper | +| `sfm/server.py` (modify) | `serial` on `/device/info`, `/device/connect`, `/device/monitor/status`; new `GET /device/settings`, `POST /device/hangup` | +| `tests/device_access_fakes.py` | test-only fakes of both clients | +| `tests/test_device_access_core.py` | errors, series, models, locks | +| `tests/test_device_access_s3.py` | Series-3 adapter | +| `tests/test_device_access_s4.py` | ring watch, session, Series-4 operations | +| `tests/test_device_access.py` | `DeviceAccess` + contract tests | +| `tests/test_server_device_access.py` | handlers | + +--- + +### Task 1: Fix `MicromateClient.is_open()` + +`is_connected` is a **property** on `BaseTransport` (`minimateplus/transport.py:59`). +`MicromateClient.is_open()` *calls* it, so on every real transport it raises +`TypeError: 'bool' object is not callable`. The test double in +`tests/test_micromate_client.py` defines `is_connected` as a **method**, +which is why no test caught it. Sessions depend on `is_open()`. + +**Files:** +- Modify: `micromate/client.py` (`is_open`, around line 130) +- Modify: `tests/test_micromate_client.py` (`ScriptedTransport`, around line 112; the test around line 406) + +**Interfaces:** +- Produces: `MicromateClient.is_open() -> bool`, now correct on real transports. + +- [ ] **Step 1: Make the test double match the real interface, and add a real-transport test** + +In `tests/test_micromate_client.py`, change `ScriptedTransport.is_connected` to a property: + +```python + @property + def is_connected(self) -> bool: + return self._connected +``` + +In `test_the_client_owns_the_transport` (around line 406), change +`t.is_connected()` to `t.is_connected`. + +Then run `grep -n "is_connected" tests/test_micromate_*.py` and convert any +other method-style `is_connected` in those test doubles the same way. + +Append this test: + +```python +def test_is_open_works_on_a_real_transport(): + """`is_connected` is a PROPERTY on BaseTransport. is_open() used to call + it, which raised TypeError on every real transport -- hidden because the + test double defined it as a method.""" + from minimateplus.transport import TcpTransport + + mm = MicromateClient(TcpTransport("127.0.0.1", port=9)) # never connected + assert mm.is_open() is False +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_micromate_client.py -q` +Expected: `test_is_open_works_on_a_real_transport` and +`test_the_client_owns_the_transport` FAIL with +`TypeError: 'bool' object is not callable`. + +- [ ] **Step 3: Fix `is_open`** + +In `micromate/client.py`: + +```python + 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) +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_micromate_*.py -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add micromate/client.py tests/test_micromate_client.py +git commit -m "fix(micromate): is_open() called a property -- TypeError on every real transport" -m "Hidden because the test double defined is_connected as a method; it is now a property, matching BaseTransport." -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 2: Client additions for status and sessions + +Two reads move into the client: +- `get_event_count()`. `0x06` content[0:4] is the event count: 3/3 against + the chain walk, and THOR's own `ReadEventRecordCount` agrees. Until now it + was decoded only in `bridges/mm_client_check.py`. +- `read_unsolicited()`. It reads whatever the unit sent unprompted, **sending + nothing**. The session uses it to notice `RADIO RING` while idle. + +**Files:** +- Modify: `micromate/client.py` (constants near the other `_MS_*` constants; methods next to `get_state`) +- Test: `tests/test_micromate_client.py` + +**Interfaces:** +- Produces: + - `MicromateClient.get_event_count() -> int`; raises `ProtocolError` if the content is under 4 bytes. + - `MicromateClient.read_unsolicited() -> bytes`; one transport read, nothing written. + +- [ ] **Step 1: Capture a real `0x06` read from UM20147 (read-only)** + +The bench unit is on `/dev/ttyACM0`; `dialout` needs `sg`. This sends only +reads. + +```bash +cat > /tmp/mm_capture_0x06.py <<'EOF' +import sys +sys.path.insert(0, ".") +from minimateplus.transport import SerialTransport +from micromate.client import MicromateClient + +with MicromateClient(SerialTransport("/dev/ttyACM0", 115200)) as mm: + mm.connect() + data = mm.protocol.read_storage_range() + refs = mm.list_events(with_records=False) + print("DATA_HEX =", data.hex()) + print("CHAIN_WALK_COUNT =", len(refs)) +EOF +sg dialout -c ".venv/bin/python /tmp/mm_capture_0x06.py" +``` + +Record both printed values. The expected count in the test is +`CHAIN_WALK_COUNT`: the chain walk is an independent count, never this +method's own output. + +- [ ] **Step 2: Write the failing tests** + +Append to `tests/test_micromate_client.py`. Paste the captured hex and count +where marked; both are values from Step 1, not choices. + +```python +# ── get_event_count() / read_unsolicited() ──────────────────────────────────── + +# 0x06 response data captured from UM20147 (11.0BD) by Task 2, Step 1. The +# expected count is that session's independent chain-walk count. +SR_UM20147 = bytes.fromhex("PASTE DATA_HEX FROM STEP 1") +SR_UM20147_CHAIN_WALK_COUNT = 0 # replace 0 with CHAIN_WALK_COUNT from Step 1 + + +def test_event_count_is_content_0_4_and_matches_the_chain_walk(): + mm, t = client([frame(0xF9, SR_UM20147, flags=FLAGS_THOR)]) + assert mm.get_event_count() == SR_UM20147_CHAIN_WALK_COUNT + assert [w[5] for w in t.written] == [0x06] + + +def test_a_truncated_storage_range_raises(): + mm, _ = client([frame(0xF9, bytes(CONTENT) + b"\x00\x05", flags=FLAGS_THOR)]) + with pytest.raises(ProtocolError, match="storage range"): + mm.get_event_count() + + +def test_read_unsolicited_sends_nothing_and_returns_what_arrived(): + """Used to spot RADIO RING on an idle session. It must never write.""" + mm, t = client([b"\r\nRADIO RING\r\n"]) + assert mm.read_unsolicited() == b"\r\nRADIO RING\r\n" + assert t.written == [] +``` + +- [ ] **Step 3: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_micromate_client.py -q -k "event_count or storage_range or unsolicited"` +Expected: FAIL with `AttributeError: 'MicromateClient' object has no attribute 'get_event_count'` +(and the same for `read_unsolicited`). + +- [ ] **Step 4: Implement** + +In `micromate/client.py`, next to the `_MS_*` constants: + +```python +# 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) +``` + +And these methods, after `get_state`: + +```python + 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) +``` + +- [ ] **Step 5: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_micromate_*.py -q` +Expected: all pass. + +- [ ] **Step 6: Commit** + +```bash +git add micromate/client.py tests/test_micromate_client.py +git commit -m "feat(micromate): get_event_count() and read_unsolicited()" -m "0x06 content[0:4] moves from the bench tool into the client, tested against a real UM20147 read and its chain-walk count. read_unsolicited() reads without sending, for spotting RADIO RING on an idle session." -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 3: Core types — errors, series, models + +**Files:** +- Create: `sfm/device_access/__init__.py`, `sfm/device_access/errors.py`, `sfm/device_access/series.py`, `sfm/device_access/models.py` +- Test: `tests/test_device_access_core.py` + +**Interfaces:** +- Produces: + - `errors.py`: `DeviceError` (base, `.http_status`); subclasses `BadRequest` 422, `NotSupported` 501, `WrongUnit` 409, `UnitBusy` 423, `ConnectFailed` 503, `CallHomeInProgress` 503, `NoAnswer` 504, `MalformedReply` 502; and `translate(exc: BaseException, *, connecting: bool) -> DeviceError`. + - `series.py`: `normalise_serial(serial: str) -> str`; `series_for_serial(serial: str) -> int` (raises `BadRequest`). + - `models.py`: `UnitAddress(host: Optional[str], tcp_port: Optional[int], port: Optional[str], baud: Optional[int])` (frozen; `.key -> str`; raises `BadRequest` if neither host nor port); dataclasses `UnitInfo`, `UnitStatus`, `UnitSettings` (fields below). + +- [ ] **Step 1: Write the failing tests** + +Create `tests/test_device_access_core.py`: + +```python +"""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" +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q` +Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access'`. + +- [ ] **Step 3: Implement** + +`sfm/device_access/errors.py`: + +```python +"""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 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 + + +_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}") +``` + +`sfm/device_access/series.py`: + +```python +"""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)" + ) +``` + +`sfm/device_access/models.py`: + +```python +"""Series-neutral models. Every operation returns the same shape for both +series; anything only one series has goes under `detail`.""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Dict, 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) +``` + +`sfm/device_access/__init__.py`: + +```python +"""One door for every device request -- see the 2026-10-20 parity spec.""" +from .errors import ( + BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, MalformedReply, + NoAnswer, NotSupported, UnitBusy, WrongUnit, translate, +) +from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus +from .series import normalise_serial, series_for_serial +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add sfm/device_access/ tests/test_device_access_core.py +git commit -m "feat(sfm): device_access core -- typed errors, series by serial prefix, shared models" -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 4: One connection per unit — the per-unit lock + +**Files:** +- Create: `sfm/device_access/locks.py` +- Test: `tests/test_device_access_core.py` (append) + +**Interfaces:** +- Consumes: `UnitBusy` (Task 3). +- Produces: `UnitLocks(timeout: float = 20.0)` with + - `hold(key: str, timeout: Optional[float] = None)`, a context manager that raises `UnitBusy` on timeout; + - `try_hold(key: str)`, a non-blocking context manager that yields `bool`. + +- [ ] **Step 1: Write the failing tests** + +Append to `tests/test_device_access_core.py`: + +```python +# ── 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 +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q` +Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.locks'`. + +- [ ] **Step 3: Implement** `sfm/device_access/locks.py`: + +```python +"""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() +``` + +Add to `sfm/device_access/__init__.py`: `from .locks import UnitLocks` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_device_access_core.py -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add sfm/device_access/locks.py sfm/device_access/__init__.py tests/test_device_access_core.py +git commit -m "feat(sfm): per-unit lock -- one connection per unit, 423 when busy" -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 5: The Series-3 adapter + +Connect-per-request, as today. The TCP cold-boot retry-once from +`server._run_with_retry` is kept, but **narrowed to "no answer"**, the +cold-boot symptom. The legacy path retries any protocol error, which here +would also retry the adapter's own "no settings block" error. When the serial is already in +hand (`connect()` reads it), a mismatch is refused with 409. No extra round +trip is added just to check it. + +**Files:** +- Create: `sfm/device_access/s3.py`, `tests/device_access_fakes.py` +- Test: `tests/test_device_access_s3.py` + +**Interfaces:** +- Consumes: `UnitAddress`, `UnitInfo`, `UnitStatus`, `UnitSettings`, the errors and `translate` (Task 3). +- Produces: + - `Series3Adapter(client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory)` with `identify(address, serial) -> UnitInfo`, `status(address, serial) -> UnitStatus` and `settings(address, serial) -> UnitSettings`. `serial` is already normalised. + - `default_s3_client_factory(address, timeout=10.0) -> MiniMateClient`. + - `tests/device_access_fakes.py`: `FakeMiniMateClient`, `FakeMicromateClient` (the latter is used from Task 6). + +- [ ] **Step 1: Write the test fakes** + +Create `tests/device_access_fakes.py`. These are test utilities, never +imported by production code. They return the **real** model dataclasses, and +the Micromate fake's setup comes from a real fixture read: + +```python +"""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 datetime +from pathlib import Path + +from micromate.models import MicromateDeviceInfo, MicromateState +from micromate.setup_block import decode_setup +from minimateplus.models import ComplianceConfig, DeviceInfo, MonitorStatus + +SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin" + + +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 + + +class FakeMiniMateClient(_Base): + def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", **kw): + super().__init__(**kw) + self.serial = serial + self.monitoring = monitoring + 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 + + 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 get_monitor_status(self) -> MonitorStatus: + self._step("get_monitor_status") + return MonitorStatus( + is_monitoring=self.monitoring, battery_v=6.8, + memory_total=983026, memory_free=900000, + ) + + +class _FakeProtocol: + def __init__(self, owner): + self._owner = owner + + def poll(self): + self._owner._step("poll") + + +class FakeMicromateClient(_Base): + def __init__(self, serial="UM20147", *, monitoring=False, events=5, + unsolicited=b"", **kw): + super().__init__(**kw) + self.serial = serial + self.monitoring = monitoring + self.events = events + self.unsolicited = unsolicited + self.protocol = _FakeProtocol(self) + + def is_open(self) -> bool: + return self._open + + def connect(self) -> MicromateDeviceInfo: + self._step("connect") + return MicromateDeviceInfo( + serial=self.serial, manufacturer="Instantel", model="MM/ISEE/S", + firmware_line="thor", monitoring=self.monitoring, active_setup="test2.MMB", + ) + + 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 +``` + +- [ ] **Step 2: Write the failing tests** + +Create `tests/test_device_access_s3.py`: + +```python +"""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 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") +``` + +- [ ] **Step 3: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_device_access_s3.py -q` +Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.s3'`. + +- [ ] **Step 4: Implement** `sfm/device_access/s3.py`: + +```python +"""Series-3 adapter. Connect-per-request, as SFM has always done for +MiniMates -- a held session waits for the bench test in the spec.""" +from __future__ import annotations + +import logging +from typing import Any, Callable + +from minimateplus import MiniMateClient +from minimateplus.transport import TcpTransport + +from .errors import DeviceError, MalformedReply, NoAnswer, WrongUnit, translate +from .models import 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"} + + +def default_s3_client_factory(address: UnitAddress, timeout: float = 10.0) -> MiniMateClient: + if address.host: + return MiniMateClient(transport=TcpTransport(address.host, port=address.tcp_port), timeout=timeout) + return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD) + + +def _close(client: Any) -> None: + try: + client.close() + except Exception: # noqa: BLE001 + log.debug("close failed", exc_info=True) + + +class Series3Adapter: + def __init__(self, client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory) -> None: + self._factory = client_factory + + def _run(self, address: UnitAddress, fn: Callable[[Any], Any]) -> Any: + def attempt() -> Any: + client = self._factory(address) + try: + client.open() + except BaseException as exc: + _close(client) + raise translate(exc, connecting=True) from exc + try: + return fn(client) + except DeviceError: + raise + except BaseException as exc: + raise translate(exc, connecting=False) from exc + finally: + _close(client) + + try: + return attempt() + except NoAnswer: + # A MiniMate that has just had its serial lines asserted can take + # 5-10 s to boot, and shows it as silence; one retry covers it. TCP + # only -- on a serial cable a silence is a real fault. Narrower than + # server._run_with_retry (any protocol error): retrying a + # MalformedReply would also retry "no settings block", which a + # reconnect cannot fix. + if not address.host: + raise + log.info("Series 3 at %s: no clean answer, retrying once (unit may be cold)", address.key) + return attempt() + + @staticmethod + def _check(serial_reported: str, serial: str, address: UnitAddress) -> None: + if (serial_reported or "").strip().upper() != serial: + raise WrongUnit(f"asked for {serial} but {serial_reported} answered at {address.key}") + + def identify(self, address: UnitAddress, serial: str) -> UnitInfo: + def op(client: Any) -> UnitInfo: + info = client.connect() + self._check(info.serial, serial, address) + cc = info.compliance_config + return UnitInfo( + serial=info.serial, series=3, model=info.model, firmware=info.firmware_version, + monitoring=None, active_setup=cc.setup_name if cc else None, + detail={"manufacturer": info.manufacturer, "dsp_version": info.dsp_version}, + ) + return self._run(address, op) + + def status(self, address: UnitAddress, serial: str) -> UnitStatus: + def op(client: Any) -> UnitStatus: + client.poll() + ms = client.get_monitor_status() + return UnitStatus( + serial=serial, series=3, monitoring=ms.is_monitoring, + battery_volts=round(ms.battery_v, 2) if ms.battery_v is not None else None, + memory_total_bytes=ms.memory_total, memory_free_bytes=ms.memory_free, + device_time=None, event_count=None, + ) + 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) +``` + +- [ ] **Step 5: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_device_access_s3.py -q` +Expected: all pass. + +- [ ] **Step 6: Commit** + +```bash +git add sfm/device_access/s3.py tests/device_access_fakes.py tests/test_device_access_s3.py +git commit -m "feat(sfm): Series-3 adapter -- identify, status, settings into the shared models" -m "Connect-per-request with the TCP cold-boot retry kept; a different unit answering is refused (409) whenever the serial is already in hand." -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 6: Series-4 session — stay on the line, ring safety + +**Files:** +- Create: `sfm/device_access/s4.py` (session part) +- Test: `tests/test_device_access_s4.py` + +**Interfaces:** +- Consumes: errors and `translate`, `normalise_serial`, `UnitAddress` (Task 3); `MicromateClient.is_open()` (Task 1); `read_unsolicited()` (Task 2); `FakeMicromateClient` (Task 5). +- Produces: + - `RingDetected(Exception)`. + - `RingWatchTransport(inner: BaseTransport)`, a `BaseTransport` whose `read()` raises `RingDetected` on `b"RADIO RING"`, including when it is split across reads. + - `Series4Session(address, serial, client_factory, clock=time.monotonic)` with: + - `call_up() -> MicromateDeviceInfo` (raises `WrongUnit` and `CallHomeInProgress`); + - `run(op: Callable[[client], T]) -> T` (a user request; calls up first if needed); + - `keepalive()`, which is a POLL and does not count as use; + - `listen()`, which reads only and does not count as use; + - `hang_up()`; + - properties `is_open`, `last_used`, `last_traffic`. + - `default_s4_client_factory(address, recv_timeout=10.0) -> MicromateClient`, with its transport wrapped in `RingWatchTransport`. + +- [ ] **Step 1: Write the failing tests** + +Create `tests/test_device_access_s4.py`: + +```python +"""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 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 +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q` +Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.s4'`. + +- [ ] **Step 3: Implement** `sfm/device_access/s4.py` (session part): + +```python +"""Series-4 sessions: call up once, stay on the line, hang up when idle. + +⚠ 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 minimateplus.transport import BaseTransport, SerialTransport, TcpTransport + +from .errors import CallHomeInProgress, WrongUnit, translate +from .models import UnitAddress +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, + including when it is split across two reads.""" + + def __init__(self, inner: BaseTransport) -> None: + self._inner = inner + self._tail = b"" + + 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: + self._inner.write(data) + + def read(self, n: int) -> bytes: + data = self._inner.read(n) + if data: + window = self._tail + data + if RING in window: + self._tail = b"" + raise RingDetected("RADIO RING") + self._tail = window[-(len(RING) - 1):] + 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 = ("the unit started calling home; SFM hung up so the call can " + "reach THOR -- try again in a few minutes") + + +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. + """ + + 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: + return self._client is not None and self._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 BaseException 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 BaseException 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) +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add sfm/device_access/s4.py tests/test_device_access_s4.py +git commit -m "feat(sfm): Series-4 session -- call up once, stay on the line, release on RADIO RING" -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 7: Series-4 operations — identify, status, settings + +**Files:** +- Modify: `sfm/device_access/s4.py` (append) +- Test: `tests/test_device_access_s4.py` (append) + +**Interfaces:** +- Consumes: `UnitInfo`, `UnitStatus`, `UnitSettings` (Task 3); client methods from Tasks 1 and 2 and `get_setup()`. +- Produces, each run inside `Series4Session.run`: + - `s4_identify(client, serial: str) -> UnitInfo` + - `s4_status(client, serial: str) -> UnitStatus` + - `s4_settings(client, serial: str) -> UnitSettings` + +- [ ] **Step 1: Write the failing tests** + +Append to `tests/test_device_access_s4.py`. The settings values are what the +operator read off UM20147's screen for `um20147_baseline` (see +`tests/test_micromate_setup.py`): + +```python +# ── 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_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) +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q` +Expected: collection ERROR, `ImportError: cannot import name 's4_identify'`. + +- [ ] **Step 3: Implement** + +Append to `sfm/device_access/s4.py`, and add `UnitInfo, UnitSettings, UnitStatus` +to its `.models` import: + +```python +# ── 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) -> UnitStatus: + st = client.get_state() + count = client.get_event_count() + 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, + ) + + +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, + }, + ) +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_device_access_s4.py -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add sfm/device_access/s4.py tests/test_device_access_s4.py +git commit -m "feat(sfm): Series-4 identify, status and settings into the shared models" -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 8: `DeviceAccess` — one door, sessions, the reaper + +**Files:** +- Create: `sfm/device_access/access.py` +- Test: `tests/test_device_access.py` + +**Interfaces:** +- Consumes: everything from Tasks 3–7. +- Produces: `DeviceAccess(*, s3_client_factory=default_s3_client_factory, s4_client_factory=default_s4_client_factory, clock=time.monotonic, lock_timeout=20.0, keepalive_s=60.0, idle_hangup_s=300.0, reaper_interval_s=5.0, start_reaper=True)` with: + - `identify(address: UnitAddress, serial: str) -> UnitInfo` + - `status(address, serial) -> UnitStatus` + - `settings(address, serial) -> UnitSettings` + - `hang_up(address) -> bool`, True if a held line was closed + - `tick(now: Optional[float] = None) -> None`, for tests; the reaper thread calls it. + +- [ ] **Step 1: Write the failing tests** + +Create `tests/test_device_access.py`: + +```python +"""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 +from sfm.device_access.errors import BadRequest, CallHomeInProgress, UnitBusy # 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) + + +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_the_same_address_hangs_up_the_old_line(): + first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947") + da = access(s4=[first, second]) + da.status(ADDR, "UM20147") + da.status(ADDR, "UM12947") + assert first.closed == 1 and 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 + + +# ── 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 +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_device_access.py -q` +Expected: collection ERROR, `ModuleNotFoundError: No module named 'sfm.device_access.access'`. + +- [ ] **Step 3: Implement** `sfm/device_access/access.py`: + +```python +"""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 DeviceError +from .locks import UnitLocks +from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus +from .s3 import Series3Adapter, default_s3_client_factory +from .s4 import ( + Series4Session, default_s4_client_factory, s4_identify, 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, + ) -> None: + 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) -> UnitStatus: + return self._dispatch(address, serial, self._s3.status, s4_status) + + def settings(self, address: UnitAddress, serial: str) -> UnitSettings: + return self._dispatch(address, serial, self._s3.settings, s4_settings) + + 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]) -> 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: + return s3_op(address, serial) + session = self._session_for(address, serial) + try: + return session.run(lambda client: s4_op(client, serial)) + except DeviceError: + if not session.is_open: + with self._sessions_guard: + if self._sessions.get(address.key) is session: + del self._sessions[address.key] + raise + + 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: + session.hang_up() + 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") +``` + +Add to `sfm/device_access/__init__.py`: `from .access import DeviceAccess` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_device_access*.py -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add sfm/device_access/access.py sfm/device_access/__init__.py tests/test_device_access.py +git commit -m "feat(sfm): DeviceAccess -- one door, held Series-4 lines, a reaper, and the same answer shape for both series" -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 9: The endpoints + +`serial` routes a request through `DeviceAccess`. Without it, every handler +runs exactly as today. + +**Files:** +- Modify: `sfm/server.py`: + - imports; + - module docstring; + - `device_info` (~line 405), `device_connect` (~line 460) and `device_monitor_status` (~line 1100); + - two new handlers after `device_monitor_status`. +- Test: `tests/test_server_device_access.py` + +**Interfaces:** +- Consumes: `DeviceAccess`, `UnitAddress`, `DeviceError` (Tasks 3, 8). +- Produces: + - query parameter `serial` on `GET /device/info`, `POST /device/connect` and `GET /device/monitor/status`; + - `GET /device/settings` (`serial` required); + - `POST /device/hangup`; + - module-level `_device_access() -> DeviceAccess` and the `_device_access_instance` singleton, so tests can monkeypatch them. + +- [ ] **Step 1: Write the failing tests** + +Create `tests/test_server_device_access.py`: + +```python +"""Handlers called directly -- every parameter passed explicitly, because +FastAPI Query() defaults are FieldInfo objects, not values.""" +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 fastapi import HTTPException # noqa: E402 + +import sfm.server as srv # noqa: E402 +from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402 +from sfm.device_access.access import DeviceAccess # noqa: E402 +from sfm.device_access.errors import ( # noqa: E402 + BadRequest, CallHomeInProgress, ConnectFailed, MalformedReply, NoAnswer, + NotSupported, UnitBusy, WrongUnit, +) + +TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034) + + +@pytest.fixture +def da(monkeypatch): + s3q = [FakeMiniMateClient() for _ in range(5)] + s4q = [FakeMicromateClient() for _ in range(5)] + access = DeviceAccess(s3_client_factory=lambda a: s3q.pop(0), + s4_client_factory=lambda a: s4q.pop(0), start_reaper=False) + monkeypatch.setattr(srv, "_device_access_instance", access) + return access + + +def test_info_with_a_serial_returns_the_shared_model(da): + out = srv.device_info(force=False, serial="UM20147", **TCP) + assert out["series"] == 4 and out["serial"] == "UM20147" + assert set(out) == {"serial", "series", "model", "firmware", "monitoring", "active_setup", "detail"} + + +def test_connect_passes_the_serial_through(da): + out = srv.device_connect(serial="BE18193", **TCP) + assert out["series"] == 3 + + +def test_status_and_settings_with_a_serial(da): + assert srv.device_monitor_status(force=False, serial="UM20147", **TCP)["event_count"] == 5 + assert srv.device_settings(serial="UM20147", **TCP)["record_mode"] == "Histogram Combo" + + +def test_hangup(da): + srv.device_monitor_status(force=False, serial="UM20147", **TCP) + assert srv.device_hangup(**TCP) == {"hung_up": True} + + +@pytest.mark.parametrize( + "exc, status", + [(BadRequest("x"), 422), (NotSupported("x"), 501), (WrongUnit("x"), 409), + (UnitBusy("x"), 423), (ConnectFailed("x"), 503), (CallHomeInProgress("x"), 503), + (NoAnswer("x"), 504), (MalformedReply("x"), 502)], +) +def test_typed_errors_become_their_http_status(monkeypatch, exc, status): + class Raising: + def identify(self, address, serial): + raise exc + monkeypatch.setattr(srv, "_device_access_instance", Raising()) + with pytest.raises(HTTPException) as ei: + srv.device_info(force=False, serial="UM20147", **TCP) + assert ei.value.status_code == status + + +def test_a_missing_address_is_a_422(da): + with pytest.raises(HTTPException) as ei: + srv.device_settings(serial="UM20147", port=None, baud=None, host=None, tcp_port=9034) + assert ei.value.status_code == 422 + + +def test_without_a_serial_the_legacy_path_runs_unchanged(monkeypatch): + """No serial: today's Series-3 code path, today's response shape. + DeviceAccess must not be touched.""" + class Untouchable: + def __getattr__(self, name): + raise AssertionError("DeviceAccess used on the legacy path") + + class Cache: + def get_device_info(self, key): + return {"serial": "BE18193", "firmware_version": "S338.17"} + + monkeypatch.setattr(srv, "_device_access_instance", Untouchable()) + monkeypatch.setattr(srv, "get_cache", lambda: Cache()) + out = srv.device_info(force=False, serial=None, **TCP) + assert out == {"serial": "BE18193", "firmware_version": "S338.17", "_cached": True} +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q` +Expected: FAIL. `device_info() got an unexpected keyword argument 'serial'`, +and `module 'sfm.server' has no attribute 'device_settings'`. + +- [ ] **Step 3: Implement** + +In `sfm/server.py`, after the existing `from sfm import db_snapshot` import: + +```python +import dataclasses +from sfm.device_access import DeviceAccess, DeviceError, UnitAddress +``` + +After `_run_with_retry` (the "Transport factory" section): + +```python +# ── 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). + +_device_access_instance: Optional[DeviceAccess] = None + + +def _device_access() -> DeviceAccess: + global _device_access_instance + if _device_access_instance is None: + _device_access_instance = 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 + + +_SERIAL_DOC = "Unit serial -- UM... (Series 4) or BE.../BA... (Series 3). Returns the shared model." +``` + +`device_info`: +- change `baud: int = Query(38400, ...)` to + `baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)")`; +- add `serial: Optional[str] = Query(None, description=_SERIAL_DOC)` as the last parameter; +- make these the first lines of the body, before the existing `log.info`: + +```python + 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 +``` + +`device_connect`: the same `baud` change, add the same `serial` parameter, and +replace its body with: + +```python + # 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) +``` + +`device_monitor_status`: the same `baud` change, add `serial` as the last +parameter, and make these the first lines of the body: + +```python + if serial: + return _via_device_access( + lambda: _device_access().status(_unit_address(port, baud, host, tcp_port), serial)) + baud = 38400 if baud is None else baud +``` + +Add after `device_monitor_status`: + +```python +@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/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))}) +``` + +In the module docstring's endpoint list, add: + +``` +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. +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q` +Expected: all pass. + +- [ ] **Step 5: Run the full suite** + +Run: `.venv/bin/python -m pytest tests -q` +Expected: the baseline plus the new tests. Still exactly **16 failed**, the +same two files (`test_bw_ascii_report.py` 15, `test_event_file_io.py` 1). +More passed. + +- [ ] **Step 6: Commit** + +```bash +git add sfm/server.py tests/test_server_device_access.py +git commit -m "feat(sfm): serial-named /device/info, /status, /settings and /hangup for both series" -m "With serial: one contract for Series 3 and 4 through sfm.device_access. Without it: the legacy Series-3 path, unchanged." -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` + +--- + +### Task 10: Bench check on UM20147, and the record + +Read-only, on the real unit, through the real server. + +**Files:** +- Modify: `CLAUDE.md` (the Series-4 config bullet in "Where things stand") + +- [ ] **Step 1: Start SFM with access to the unit's port** + +```bash +sg dialout -c ".venv/bin/python -m uvicorn sfm.server:app --port 8299" & +sleep 3 +``` + +- [ ] **Step 2: Identify, status, settings by serial, then hang up** + +```bash +Q="port=/dev/ttyACM0&serial=UM20147" +curl -s "localhost:8299/device/info?$Q" | python3 -m json.tool +curl -s "localhost:8299/device/monitor/status?$Q" | python3 -m json.tool +curl -s "localhost:8299/device/settings?$Q" | python3 -m json.tool +curl -s -X POST "localhost:8299/device/hangup?port=/dev/ttyACM0" ; echo +``` + +Expected: +- `series: 4`, `serial: "UM20147"`. +- The settings match `bridges/mm_client_check.py`'s output and the unit's + screen. On 2026-10-20: Histogram Combo, 2048 sps, record time 11 s, + pre-trigger 0.25 s, geophone trigger 0.6 in/s, mic 140 dB, job number 1234 + (off), Location BENCH01. +- `event_count` equals the chain-walk count from Task 2. +- The server log shows **one** call-up for the three requests, then a + hang-up. +- The hang-up response is `{"hung_up": true}`. + +- [ ] **Step 3: Ask for the wrong serial** + +```bash +curl -s -w "\n%{http_code}\n" "localhost:8299/device/info?port=/dev/ttyACM0&serial=UM12947" +``` + +Expected: `409`, with "asked for UM12947 but UM20147 answered". + +- [ ] **Step 4: Stop the server** + +```bash +kill %1 +``` + +- [ ] **Step 5: Record it in CLAUDE.md** + +In "Where things stand", in the Series-4 config bullet, add this after the +`get_setup()` line: + +``` + ✅ **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. Next: 1b (events), 1c (webapp). +``` + +- [ ] **Step 6: Commit** + +```bash +git add CLAUDE.md +git commit -m "docs(claude): SFM speaks Series 4 by serial -- phase 1a done, bench-checked on UM20147" -m "Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44" +``` diff --git a/docs/superpowers/plans/2026-10-21-sfm-device-access-phase1b.md b/docs/superpowers/plans/2026-10-21-sfm-device-access-phase1b.md new file mode 100644 index 0000000..e9963a9 --- /dev/null +++ b/docs/superpowers/plans/2026-10-21-sfm-device-access-phase1b.md @@ -0,0 +1,1879 @@ +# SFM device access, phase 1b — events for both series — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** List a unit's events and download one, by serial, through the same contract for a MiniMate (Series 3) and a Micromate (Series 4). A download is stored in SFM's database. + +**Architecture:** Two device-side operations join `DeviceAccess`: `list_events` and `download_event`. Each runs through the existing dispatch: series by serial prefix, per-unit lock, the held Micromate line, typed errors. +- The device side (`sfm/device_access/`) returns a `DownloadedEvent` and stores nothing. +- A new SDM module, `sfm/event_ingest.py`, stores it through the same waveform-store and `insert_events` calls every other ingest path uses. +- MiniMate listing switches from "download every event" to a header-only walk, built from the bypass `get_events()` already has. +- An `event_id` carries serial, key and timestamp, so a stale id fails loudly. + +**Tech Stack:** Python 3, FastAPI, pytest. `minimateplus/` (Series 3), `micromate/` (Series 4), `sfm/` (server, store, DB). + +**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`: the parity rows 4–5, and the "1b" decisions under *Build phases*. + +## Global Constraints + +- **Read-only on every unit.** Listing and downloading only. No new command reaches the wire: the MiniMate header walk sends only `0A`, `1E`, `0C`, `1F` (already sent by `get_events()` on every event), and the Micromate path only what `iter_events()` / `download_event()` already send. +- **Never send Series-3 bytes to a Micromate.** `sfm/device_access/s4.py` imports nothing from `minimateplus` except `transport`. +- **Requests without `serial` behave exactly as today.** The legacy body of `GET /device/events` is untouched except that `baud` becomes `Optional[int] = Query(None)`, defaulted to 38400 at the top of the legacy path, as phase 1a did for the other handlers. +- **Tiers:** `sfm/device_access/` must not import `sfm.waveform_store`, `sfm.database` or `sfm.server`. Storing lives in `sfm/event_ingest.py`. +- **Error statuses:** 404 event not found; 409 wrong unit or stale event; 422 bad input; 423 unit busy; 502 malformed reply; 503 could not connect, connection lost or calling home; 504 no answer; 501 not supported. +- **Tests call handlers directly with every parameter explicit.** `httpx` is not installed, so `TestClient` tests are skipped. FastAPI `Query()` defaults are FieldInfo objects, not values. +- **The suite's 16 pre-existing failures** (test_bw_ascii_report.py 15, test_event_file_io.py 1, missing gitignored fixtures) stay exactly that set. Nothing else may fail. +- **Branch `feat/series4-sfm-parity`.** + - Never commit to `main` or `dev`. + - Do not edit `CHANGELOG.md`. + - **After each commit, `git push`.** +- **Hardware:** only Task 9 touches `/dev/ttyACM0` (UM20147), under `sg dialout -c "..."`. Port 8200 is in use by another SFM; never start a server there. +- **Every commit message ends with:** + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 + ``` + +## Review Focus + +The inputs the spec implies, most likely to bite first. Each has a test in the task named. + +1. **An erase or memory wrap between list and download.** The key now holds a different event, and the download must refuse with 409, never fetch it (Tasks 4, 5, 8). +2. **The same key on two Micromates** (UM12947 and UM20147 both have `055d4a81`). An `event_id` from one unit used against another must be refused before any I/O (Tasks 3, 6). +3. **A decode that disagrees with the unit's own peak.** It must never be stored: 502, and the store is untouched (Tasks 5, 8). +4. **Storing an event already stored**, by an earlier download or by THOR's watcher. The row is refreshed, never duplicated, and the same `db_event_id` comes back (Task 7). +5. **RADIO RING mid-download.** The line is released, the request answers 503, and nothing is stored (Tasks 6, 8). + +--- + +## File map + +| file | change | +|---|---| +| `minimateplus/client.py` | `get_events(headers_only=, only_key=)`; new `list_event_headers()`, `download_event_by_key()` | +| `micromate/client.py` | new `fetch_event()` returning `(bytes, result)`; `get_event()` delegates to it | +| `sfm/device_access/models.py` | `EventRef`, `EventList`, `EventDownload`, `DownloadedEvent` | +| `sfm/device_access/errors.py` | `EventNotFound` (404), `StaleEvent` (409) | +| `sfm/device_access/events.py` | **new**: `event_id` make/parse, timestamp helpers | +| `sfm/device_access/s3.py` | `list_events`, `download_event`; factory and `_run` take a timeout | +| `sfm/device_access/s4.py` | `s4_list_events`, `s4_download_event` | +| `sfm/device_access/access.py` | `DeviceAccess.list_events`, `.download_event` | +| `sfm/device_access/__init__.py` | exports | +| `sfm/event_ingest.py` | **new**: `persist_download`, `backfill_series3_event` | +| `sfm/server.py` | `serial` on `GET /device/events`; new `POST /device/events/download`; guard paths; the legacy `blastware_file` route calls `backfill_series3_event` | +| `tests/device_access_fakes.py` | event support in both fakes | +| tests | `test_minimate_event_headers.py`, `test_device_access_events.py`, `test_device_access_s3_events.py`, `test_device_access_s4_events.py`, `test_device_access_event_dispatch.py`, `test_event_ingest.py`; additions to `test_micromate_events.py` and `test_server_device_access.py` | +| docs | `CLAUDE.md`, `README.md`, `docs/micromate_protocol_reference.md` (Task 9) | + +--- + +### Task 1: MiniMate header-only walk + +**Files:** +- Modify: `minimateplus/client.py`: `get_events` (line 453), and two new methods inserted before `def download_waveform` (line 744) +- Test: `tests/test_minimate_event_headers.py` (new) + +**Interfaces:** +- Produces: + - `MiniMateClient.list_event_headers() -> list[Event]`: no `_a5_frames`. + - `MiniMateClient.download_event_by_key(key4: bytes) -> Optional[Event]`: with `_a5_frames`. + - `get_events(..., headers_only: bool = False, only_key: Optional[bytes] = None)`. + +- [ ] **Step 1: Write the failing tests** in `tests/test_minimate_event_headers.py`: + +```python +"""MiniMateClient's header-only walk: list without 5A, download one without the rest.""" +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.client as mc # noqa: E402 +from minimateplus.client import MiniMateClient # noqa: E402 +from minimateplus.models import Timestamp # noqa: E402 + +END = b"\x00" * 8 +KEYS = [bytes.fromhex(k) for k in ("01110000", "0111245a", "01114290")] +STAMPS = { + KEYS[0]: (2026, 10, 1, 8, 0, 0), + KEYS[1]: (2026, 10, 2, 9, 30, 15), + KEYS[2]: (2026, 10, 3, 17, 45, 59), +} + + +class FakeProto: + """Records every call; serves a three-event chain the way the unit does.""" + + def __init__(self, keys=KEYS, partial=()): + self.keys = list(keys) + self.partial = set(partial) + self.calls: list[tuple] = [] + self._pos = 0 + + def _entry(self, i): + if i >= len(self.keys): + return b"\x00\x00\x00\x00", END + return self.keys[i], self.keys[i] + b"\x00\x00\x00\x46" + + def read_event_first(self, token=0): + self.calls.append(("1E", token)) + if token == 0: + self._pos = 0 + return self._entry(self._pos) + + def read_waveform_header(self, key4): + self.calls.append(("0A", key4)) + return b"", (0x2C if key4 in self.partial else 0x46) + + def read_waveform_record(self, key4): + self.calls.append(("0C", key4)) + return key4 # decoded by the patched decoder below + + def advance_event(self, browse=False): + self.calls.append(("1F", "browse" if browse else "arm")) + if browse: + self._pos += 1 + return self._entry(self._pos) + return self._entry(self._pos + 1) + + def poll(self): + self.calls.append(("POLL",)) + + def read_bulk_waveform_stream(self, key4, **kw): + self.calls.append(("5A", key4)) + return ["frame"] + + +@pytest.fixture +def client(monkeypatch): + def decode_record(record, ev): + y, mo, d, h, mi, s = STAMPS[record] + ev.timestamp = Timestamp(raw=b"", flag=0x10, year=y, unknown_byte=0, + month=mo, day=d, hour=h, minute=mi, second=s) + ev.record_type = "Waveform" + monkeypatch.setattr(mc, "_decode_waveform_record_into", decode_record) + monkeypatch.setattr(mc, "_decode_a5_metadata_into", lambda frames, ev: None) + monkeypatch.setattr(mc, "_decode_a5_waveform", lambda frames, ev: None) + + def make(proto): + c = MiniMateClient(port="/dev/null") + c._proto = proto + return c + return make + + +def _subs(proto): + return [c[0] for c in proto.calls] + + +def test_listing_headers_never_starts_a_5a(client): + proto = FakeProto() + events = client(proto).list_event_headers() + assert [e._waveform_key for e in events] == KEYS + assert "5A" not in _subs(proto) and "POLL" not in _subs(proto) + assert ("1F", "arm") not in proto.calls + assert all(e._a5_frames is None for e in events) + + +def test_listing_headers_sends_only_the_commands_get_events_already_sends(client): + proto = FakeProto() + client(proto).list_event_headers() + assert _subs(proto) == ["1E"] + ["0A", "1E", "0C", "1F"] * len(KEYS) + + +def test_listed_events_carry_their_timestamps(client): + events = client(FakeProto()).list_event_headers() + assert (events[1].timestamp.day, events[1].timestamp.second) == (2, 15) + + +def test_downloading_one_event_starts_exactly_one_5a(client): + proto = FakeProto() + ev = client(proto).download_event_by_key(KEYS[1]) + assert ev is not None and ev._waveform_key == KEYS[1] + assert [c for c in proto.calls if c[0] == "5A"] == [("5A", KEYS[1])] + assert ev._a5_frames == ["frame"] + + +def test_downloading_one_event_stops_once_it_has_it(client): + proto = FakeProto() + client(proto).download_event_by_key(KEYS[1]) + assert ("0A", KEYS[2]) not in proto.calls + + +def test_the_events_before_it_are_walked_without_their_5a(client): + proto = FakeProto() + client(proto).download_event_by_key(KEYS[2]) + assert [c[1] for c in proto.calls if c[0] == "5A"] == [KEYS[2]] + assert proto.calls.count(("1F", "arm")) == 1 + + +def test_a_key_that_is_not_stored_returns_none(client): + assert client(FakeProto()).download_event_by_key(bytes.fromhex("0111ffff")) is None + + +def test_a_partial_record_is_skipped_by_both(client): + events = client(FakeProto(partial={KEYS[1]})).list_event_headers() + assert [e._waveform_key for e in events] == [KEYS[0], KEYS[2]] + assert client(FakeProto(partial={KEYS[1]})).download_event_by_key(KEYS[1]) is None +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_minimate_event_headers.py -q` + Expected: FAIL with `AttributeError: 'MiniMateClient' object has no attribute 'list_event_headers'`. + +- [ ] **Step 3: Implement.** In `minimateplus/client.py`: + + (a) Extend the `get_events` signature. Replace the line + ` 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]:` + with + ` 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) -> list[Event]:` + + (b) Add to the end of its docstring, just before the closing `"""` (after the `Raises:` block): + +``` + 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. +``` + + (c) Replace + +```python + expected_ts = skip_evts.get(cur_key.hex(), "") + actual_ts = _event_timestamp_iso(ev) + skip_5a = bool(expected_ts and actual_ts and expected_ts == actual_ts) + if skip_5a: + log.info( + "get_events: key=%s (key, ts=%s) match — skipping 5A bulk download", + cur_key.hex(), actual_ts, + ) +``` + + with + +```python + expected_ts = skip_evts.get(cur_key.hex(), "") + actual_ts = _event_timestamp_iso(ev) + skip_5a = bool(expected_ts and actual_ts and expected_ts == actual_ts) + if skip_5a: + log.info( + "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 +``` + + (d) Replace + +```python + events.append(ev) + idx += 1 + + # Early exit: if the caller only wants events up to a specific +``` + + with + +```python + 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 +``` + + (e) Insert immediately before ` def download_waveform(self, event: Event) -> None:`: + +```python + 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) -> 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. + """ + for ev in self.get_events(full_waveform=True, only_key=key4): + if ev._waveform_key == key4: + return ev + return None + +``` + +- [ ] **Step 4: Run the tests and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_minimate_event_headers.py -q` + Expected: 8 passed. + +- [ ] **Step 5: Commit and push.** + +```bash +git add minimateplus/client.py tests/test_minimate_event_headers.py +git commit -m "feat(minimateplus): list events from headers, download one without the rest + +" +git push +``` + +--- + +### Task 2: Micromate `fetch_event` (bytes + checked decode) + +**Files:** +- Modify: `micromate/client.py`: `get_event` (line 530) +- Test: `tests/test_micromate_events.py` (append) + +**Interfaces:** +- Produces: `MicromateClient.fetch_event(ref, *, verify=True, tolerance=0.01, chunk_size=None) -> tuple[bytes, IdfReadResult]`. It raises `DecodeMismatch` exactly as `get_event` does. `get_event` keeps its signature and behaviour. + +- [ ] **Step 1: Write the failing tests.** Append to `tests/test_micromate_events.py`: + +```python +# ── fetch_event: the bytes and the checked decode together ─────────────────── + +import math # noqa: E402 + +UM20147_W = Path(__file__).parent / "fixtures" / "thor-idf" / "UM20147_20250531135901.IDFW" + + +def _our_pvs(result): + from micromate.idf_file import geo_count_to_ips + ch = {k.lower(): v for k, v in result.samples.items()} + t, v, l = ch["tran"], ch["vert"], ch["long"] + return max(math.sqrt(geo_count_to_ips(t[i]) ** 2 + geo_count_to_ips(v[i]) ** 2 + + geo_count_to_ips(l[i]) ** 2) + for i in range(min(len(t), len(v), len(l)))) + + +def _fixture_client(monkeypatch, blob): + mm, _t = client([]) + monkeypatch.setattr(mm, "download_event", lambda ref, chunk_size=None: blob) + return mm + + +def _w_ref(pvs): + return MicromateEventRef( + index=0, key=bytes.fromhex("055d4a81"), size=UM20147_W.stat().st_size, + serial="UM20147", record_type="waveform", + timestamp=datetime.datetime(2025, 5, 31, 13, 59, 1), peak_vector_sum_ips=pvs) + + +def test_fetch_event_returns_the_downloaded_bytes_with_the_decode(monkeypatch): + blob = UM20147_W.read_bytes() + mm = _fixture_client(monkeypatch, blob) + probe = mm.fetch_event(_w_ref(None), verify=False)[1] + got, result = mm.fetch_event(_w_ref(_our_pvs(probe))) + assert got == blob and result.samples + + +def test_fetch_event_refuses_a_decode_that_disagrees_with_the_unit(monkeypatch): + mm = _fixture_client(monkeypatch, UM20147_W.read_bytes()) + probe = mm.fetch_event(_w_ref(None), verify=False)[1] + with pytest.raises(DecodeMismatch): + mm.fetch_event(_w_ref(_our_pvs(probe) * 1.05)) + + +def test_get_event_is_fetch_event_without_the_bytes(monkeypatch): + mm = _fixture_client(monkeypatch, UM20147_W.read_bytes()) + assert mm.get_event(_w_ref(None), verify=False).samples +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_micromate_events.py -q -k fetch_event` + Expected: FAIL with `AttributeError: ... 'fetch_event'`. + +- [ ] **Step 3: Implement.** In `micromate/client.py`, `get_event` keeps its docstring. Replace its body: everything from ` if not ref.record_type:` through the ` return result` that ends the method. + +```python + 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 " + f"cannot be dispatched. Use list_events(with_records=True)." + ) + blob = self.download_event(ref, chunk_size=chunk_size) + + import tempfile + from .idf_file import read_idf_file + + # read_idf_file dispatches on the suffix, so the bytes need a name. + with tempfile.NamedTemporaryFile(suffix=ref.suffix, delete=False) as f: + f.write(blob) + tmp = f.name + try: + result = read_idf_file(tmp) + finally: + os.unlink(tmp) + + if verify and not ref.is_histogram: + err = self.decode_error(ref, result) + if err is not None and abs(err) > tolerance: + raise DecodeMismatch( + f"event {ref.uid}: decoded peak vector sum differs from the " + f"device's own by {100 * err:+.3f}% (tolerance " + f"{100 * tolerance:.1f}%) — the decode is suspect, not the " + f"device. Stored {ref.peak_vector_sum_ips:.5f} in/s." + ) + if err is not None: + log.debug("event %s: PVS agrees to %+.4f%%", ref.uid, 100 * err) + return blob, result +``` + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_micromate_events.py -q` + Expected: all pass. The two replay tests may skip on a fresh clone; on the dev box they run and must still pass. + +- [ ] **Step 5: Commit and push.** Message: `feat(micromate): fetch_event returns the bytes with the checked decode`. + +--- + +### Task 3: Event models, errors and `event_id` + +**Files:** +- Modify: `sfm/device_access/models.py`, `sfm/device_access/errors.py`, `sfm/device_access/__init__.py` +- Create: `sfm/device_access/events.py` +- Test: `tests/test_device_access_events.py` (new) + +**Interfaces:** +- Produces: + - **Models:** `EventRef`, `EventList`, `EventDownload`, `DownloadedEvent` (fields below). + - **Errors:** `EventNotFound` (404), `StaleEvent` (409). + - **`events.py`:** + - `make_event_id(serial, key: bytes, stamp: Optional[str]) -> str` + - `parse_event_id(event_id, serial) -> tuple[bytes, Optional[str]]` + - `stamp_of(dt) -> Optional[str]` (`YYYYmmddHHMMSS`) + - `iso_of(dt) -> Optional[str]` + +- [ ] **Step 1: Write the failing tests** in `tests/test_device_access_events.py`: + +```python +"""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) +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_device_access_events.py -q` + Expected: FAIL with `ImportError` (`EventNotFound`, `sfm.device_access.events`). + +- [ ] **Step 3: Implement.** + + `sfm/device_access/errors.py`: add after `class MalformedReply`: + +```python +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 +``` + + `sfm/device_access/models.py`: change `from typing import Any, Dict, Optional` to `from typing import Any, Dict, List, Optional`, and append: + +```python +@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: int + sha256: Optional[str] + inserted: bool # False: already stored; the row was refreshed + 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.""" + 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) + detail: Dict[str, Any] = field(default_factory=dict) +``` + + Create `sfm/device_access/events.py`: + +```python +"""Event identity. An `event_id` is `::`. + +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) +``` + + `sfm/device_access/__init__.py`: add `EventNotFound, StaleEvent` to the errors import, and `EventDownload, EventList, EventRef, DownloadedEvent` to the models import. + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_device_access_events.py -q` + Expected: 11 passed. + +- [ ] **Step 5: Commit and push.** Message: `feat(sfm): event models and event_id -- serial, key and timestamp`. + +--- + +### Task 4: Series-3 adapter: list and download + +**Files:** +- Modify: `sfm/device_access/s3.py`, `tests/device_access_fakes.py` +- Test: `tests/test_device_access_s3_events.py` (new) + +**Interfaces:** +- Consumes: + - Task 1's `list_event_headers()` and `download_event_by_key()`. + - Task 3's models, errors and `events.py`. +- Produces: + - `Series3Adapter.list_events(address, serial) -> EventList` + - `Series3Adapter.download_event(address, serial, key: bytes, stamp: Optional[str]) -> DownloadedEvent` + - `default_s3_client_factory(address, timeout: Optional[float] = None)` + - `Series3Adapter._run(address, fn, timeout=None)`. With a timeout, the factory is called as `factory(address, timeout=...)`. + - `S3_EVENT_TIMEOUT = 120.0` + - In the fakes: `s3_event(...)`, `default_s3_events()`, and `FakeMiniMateClient(events=...)` with `list_event_headers` / `download_event_by_key`. + +- [ ] **Step 1: Extend the fakes.** In `tests/device_access_fakes.py`: + - Add `import copy` to the imports. + - Change the minimateplus import to `from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp`. + - Add these module-level helpers before `class FakeMiniMateClient`: + +```python +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 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), record_type="Histogram"), + ] +``` + + - Change the signature of `FakeMiniMateClient.__init__` to `def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None, **kw):`, and add `self.events = default_s3_events() if events is None else events` at the end of `__init__`. + - Add these methods to `FakeMiniMateClient`: + +```python + 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): + self._step("download_event_by_key") + for ev in self.events: + if ev._waveform_key == key4: + return ev + return None +``` + +- [ ] **Step 2: Write the failing tests** in `tests/test_device_access_s3_events.py`: + +```python +"""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, e.record_type) == (1, "2026-10-02T09:30:15", "histogram") + 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_long_timeout(): + 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 == [{"timeout": 120.0}] + assert fake.closed == 1 + + +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", None) + assert dl.event is fake.events[0] and dl.a5_frames == ["frame"] + assert dl.compliance is fake.compliance and dl.filename.startswith("T193") + + +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(): + with pytest.raises(StaleEvent, match="20261001080000"): + adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, "20250101000000") + + +def test_an_id_without_a_timestamp_skips_the_check(): + dl = adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, None) + assert dl.event_id == "BE18193:01110000:20261001080000" + + +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_the_64k_page_bug_is_named_not_a_bare_500(): + fake = FakeMiniMateClient() + + def boom(key4): + raise struct.error("argument out of range") + fake.download_event_by_key = boom + with pytest.raises(MalformedReply, match="64 KB"): + adapter(fake).download_event(TCP, "BE18193", FIRST, None) +``` + +- [ ] **Step 3: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_device_access_s3_events.py -q` + Expected: FAIL with `AttributeError: 'Series3Adapter' object has no attribute 'list_events'`. + +- [ ] **Step 4: Implement.** In `sfm/device_access/s3.py`: + + Imports: change `from typing import Any, Callable` to `from typing import Any, Callable, Optional`, and add: + +```python +import datetime +import struct + +from minimateplus.blastware_file import blastware_filename + +from .events import iso_of, make_event_id, stamp_of +from .models import DownloadedEvent, EventList, EventRef +``` + + Also extend the errors import with `EventNotFound, StaleEvent`. + + Replace `default_s3_client_factory` with: + +```python +S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use + + +def default_s3_client_factory(address: UnitAddress, timeout: Optional[float] = None) -> MiniMateClient: + if address.host: + return MiniMateClient(transport=TcpTransport(address.host, port=address.tcp_port), + timeout=10.0 if timeout is None else timeout) + if timeout is None: + return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD) + return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD, timeout=timeout) +``` + + In `Series3Adapter._run`: + - change the signature to `def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any:`; + - change `client = self._factory(address)` to `client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)`. + + Add module-level helpers after `_close`: + +```python +def _s3_dt(ev: Any) -> Optional[datetime.datetime]: + ts = getattr(ev, "timestamp", None) + if ts is None or ts.hour is None: + return None + try: + return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) + except (TypeError, ValueError): + return None + + +def _s3_filename(ev: Any, serial: str) -> Optional[str]: + try: + return blastware_filename(ev, serial) + except Exception: # noqa: BLE001 + return None + + +def _s3_ref(ev: Any, serial: str) -> EventRef: + dt = _s3_dt(ev) + pv = ev.peak_values + peaks = {} + if pv is not None: + peaks = {k: v for k, v in (("tran", pv.tran), ("vert", pv.vert), ("long", pv.long)) + if v is not None} + return EventRef( + event_id=make_event_id(serial, ev._waveform_key, stamp_of(dt)), + serial=serial, series=3, index=ev.index, timestamp=iso_of(dt), + record_type=ev.record_type.lower() if ev.record_type else None, + peak_vector_sum_ips=pv.peak_vector_sum if pv is not None else None, + peaks_ips=peaks, filename=_s3_filename(ev, serial), + detail={"mic_psi": pv.micl if pv is not None else None}, + ) +``` + + Add the methods to `Series3Adapter`, after `settings`: + +```python + def list_events(self, address: UnitAddress, serial: str) -> EventList: + def op(client: Any) -> EventList: + info = client.connect() + self._check(info.serial, serial, address) + return EventList(serial=serial, series=3, + events=[_s3_ref(ev, serial) for ev in client.list_event_headers()]) + return self._run(address, op, timeout=S3_EVENT_TIMEOUT) + + def download_event(self, address: UnitAddress, serial: str, key: bytes, + stamp: Optional[str]) -> DownloadedEvent: + def op(client: Any) -> DownloadedEvent: + info = client.connect() + self._check(info.serial, serial, address) + try: + ev = client.download_event_by_key(key) + except struct.error as exc: + # 🔶 Inferred: the known 5A page bug. An event past the unit's + # first 64 KB drives TERM's offset negative, and struct.pack + # rejects it (CLAUDE.md, "KNOWN BUG"). + raise MalformedReply( + f"event {key.hex()}: its download could not be assembled ({exc}) -- most " + "likely the known bug with events past the unit's first 64 KB; not saved" + ) from exc + if ev is None: + raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again") + found = stamp_of(_s3_dt(ev)) + if stamp is not None and found != stamp: + raise StaleEvent( + f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- " + "the unit was erased or wrapped since the list was read; list again") + if not ev._a5_frames: + raise MalformedReply(f"event {key.hex()}: no waveform data received (the 5A download failed)") + filename = _s3_filename(ev, serial) + if filename is None: + raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored") + return DownloadedEvent( + event_id=make_event_id(serial, key, found), serial=serial, series=3, + filename=filename, verified=None, event=ev, a5_frames=ev._a5_frames, + compliance=info.compliance_config, detail={"a5_frames": len(ev._a5_frames)}, + ) + return self._run(address, op, timeout=S3_EVENT_TIMEOUT) +``` + +- [ ] **Step 5: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_device_access_s3_events.py tests/test_device_access_s3.py -q` + Expected: all pass. The existing S3 tests use `lambda address:` factories, and those calls pass no timeout. + +- [ ] **Step 6: Commit and push.** Message: `feat(sfm): Series-3 events -- header list, one-event download, stale ids refused`. + +--- + +### Task 5: Series-4 operations: list and download + +**Files:** +- Modify: `sfm/device_access/s4.py`, `tests/device_access_fakes.py` +- Test: `tests/test_device_access_s4_events.py` (new) + +**Interfaces:** +- Consumes: + - Task 2's `fetch_event`. + - Task 3's models, errors and `events.py`. +- Produces: + - `s4_list_events(client, serial) -> EventList` + - `s4_download_event(client, serial, key: bytes, stamp: Optional[str]) -> DownloadedEvent` + - In the fakes: `s4_ref(...)`, `default_s4_refs()`, and `FakeMicromateClient(event_refs=...)` with `list_events`, `iter_events`, `fetch_event` and `decode_error`. + +- [ ] **Step 1: Extend the fakes.** In `tests/device_access_fakes.py`: + - Add `from micromate.models import MicromateEventRef` (extend the existing micromate import). + - Add `THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"` after `SETUP_FIXTURE`. + - Add these module-level helpers before `class _FakeProtocol`: + +```python +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"), + ] +``` + + - Change the signature of `FakeMicromateClient.__init__` to `def __init__(self, serial="UM20147", *, monitoring=False, events=5, unsolicited=b"", event_refs=None, **kw):`. + - Add to the end of `__init__`: + +```python + self.event_refs = default_s4_refs() if event_refs is None else event_refs + self.cursor = None + self.fetched: list = [] +``` + + - Add these methods to `FakeMicromateClient`: + +```python + 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 +``` + +- [ ] **Step 2: Write the failing tests** in `tests/test_device_access_s4_events.py`: + +```python +"""Series-4 events: the chain walk mapped into the shared shape; download at the cursor.""" +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 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_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) +``` + +- [ ] **Step 3: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_device_access_s4_events.py -q` + Expected: FAIL with `ImportError: cannot import name 's4_download_event'`. + +- [ ] **Step 4: Implement.** In `sfm/device_access/s4.py`, add these imports (`micromate.protocol` is Series 4's own package, so the module-header rule holds): + +```python +from micromate.protocol import THOR_CHUNK_SIZE + +from .errors import EventNotFound, MalformedReply, StaleEvent +from .events import iso_of, make_event_id, stamp_of +from .models import DownloadedEvent, EventList, EventRef +``` + + Merge these into the existing `.errors` and `.models` import lines. Then append at the end of the file: + +```python +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 != 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, detail={"size_bytes": ref.size, "pvs_error": err}, + ) + raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again") +``` + +- [ ] **Step 5: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_device_access_s4_events.py tests/test_device_access_s4.py -q` + Expected: all pass. + +- [ ] **Step 6: Commit and push.** Message: `feat(sfm): Series-4 events -- chain-walk list, download at THOR's cursor`. + +--- + +### Task 6: `DeviceAccess.list_events` / `download_event` + +**Files:** +- Modify: `sfm/device_access/access.py`, and `sfm/device_access/s4.py` (`Series4Session._exchange`) +- Test: `tests/test_device_access_event_dispatch.py` (new) + +**Interfaces:** +- Consumes: Tasks 3–5. +- Produces: + - `DeviceAccess.list_events(address, serial) -> EventList` + - `DeviceAccess.download_event(address, serial, event_id) -> DownloadedEvent` + +- [ ] **Step 1: Write the failing tests** in `tests/test_device_access_event_dispatch.py`: + +```python +"""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. + 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 == set(), (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 == ["frame"] + + +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_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" +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_device_access_event_dispatch.py -q` + Expected: FAIL with `AttributeError: 'DeviceAccess' object has no attribute 'list_events'`. + +- [ ] **Step 3: Implement.** In `sfm/device_access/access.py`: + - Imports: add `DownloadedEvent, EventList` to the `.models` import, `s4_download_event, s4_list_events` to the `.s4` import, and `from .events import parse_event_id`. + - Add after `settings`: + +```python + 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)) +``` + + - In `_dispatch`, replace the comment line `# Call up fresh and retry ONCE. Safe only because phase 1a` and the next line `# operations are reads (idempotent); writes (phase 3) must NOT` with: + +```python + # Call up fresh and retry ONCE. Safe only because every operation + # here is a read (identify, status, settings, list, download -- all + # idempotent); writes (phase 3) must NOT +``` + + Leave the comment's last line, `# inherit this -- a write whose ack was lost must never be sent twice.`, as it is. + + In `sfm/device_access/s4.py`, add `DeviceError` to the `.errors` import. In `Series4Session._exchange`, add a clause between the `except RingDetected` block and the `except Exception` block: + +```python + 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 +``` + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_device_access_event_dispatch.py tests/test_device_access.py -q` + Expected: all pass. + +- [ ] **Step 5: Commit and push.** Message: `feat(sfm): DeviceAccess lists and downloads events for both series`. + +--- + +### Task 7: SDM ingest: `sfm/event_ingest.py` + +**Files:** +- Create: `sfm/event_ingest.py` +- Modify: `sfm/server.py`. The legacy `device_event_blastware_file` calls `backfill_series3_event` instead of its inline copy; behaviour is identical. +- Test: `tests/test_event_ingest.py` (new) + +**Interfaces:** +- Consumes: + - Task 3's `DownloadedEvent` and `EventDownload`. + - `WaveformStore.save()` / `.save_imported_idf()`. + - `SeismoDb.insert_events()` / `.query_events()`. +- Produces: + - `persist_download(dl, *, store, db) -> EventDownload` + - `backfill_series3_event(ev, cc) -> None` + - `IngestError` + +- [ ] **Step 1: Write the failing tests** in `tests/test_event_ingest.py`: + +```python +"""Storing a downloaded event: the same store + DB writes every ingest path makes.""" +from __future__ import annotations + +import datetime +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 device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402 +from sfm.database import SeismoDb # noqa: E402 +from sfm.device_access.models import DownloadedEvent # noqa: E402 +from sfm.event_ingest import backfill_series3_event, persist_download # noqa: E402 +from sfm.waveform_store import WaveformStore # noqa: E402 + +THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf" + + +@pytest.fixture +def sdm(tmp_path): + return WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo.db") + + +def s4_download(name, verified=True): + return DownloadedEvent(event_id=f"UM20147:055d4a81:{name[8:22]}", serial="UM20147", series=4, + filename=name, verified=verified, idf_bytes=(THOR_IDF / name).read_bytes()) + + +def test_a_series4_waveform_is_stored_and_findable(sdm): + store, db = sdm + out = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db) + assert out.stored_filename == "UM20147_20250531135901.IDFW" and out.inserted + assert (store.root / "UM20147" / out.stored_filename).exists() + row = db.get_event(out.db_event_id) + assert row["serial"] == "UM20147" and row["device_family"] == "series4" + assert out.verified is True and out.sha256 + + +def test_a_series4_histogram_is_stored(sdm): + store, db = sdm + out = persist_download(s4_download("UM20147_20250330070110.IDFH", verified=None), store=store, db=db) + assert out.inserted and out.db_event_id and out.verified is None + + +def test_storing_the_same_event_twice_refreshes_rather_than_duplicates(sdm): + store, db = sdm + first = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db) + again = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db) + assert (first.inserted, again.inserted) == (True, False) + assert again.db_event_id == first.db_event_id + assert len(db.query_events(serial="UM20147")) == 1 + + +class RecordingStore: + def __init__(self): + self.saved = [] + + def save(self, ev, serial, a5_frames, *, geo_range="normal", source_kind="sfm-live"): + self.saved.append((ev, serial, a5_frames, geo_range)) + return {"filename": "T193LQ9K.OE0", "filesize": 8708, "sha256": "ab" * 32} + + +def test_a_series3_event_is_backfilled_then_stored_as_series3(tmp_path): + db = SeismoDb(tmp_path / "seismo.db") + store = RecordingStore() + fake = FakeMiniMateClient() + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)) + dl = DownloadedEvent(event_id="BE18193:01110000:20261001080000", serial="BE18193", series=3, + filename="T193LQ9K.OE0", verified=None, event=ev, a5_frames=["frame"], + compliance=fake.compliance) + out = persist_download(dl, store=store, db=db) + saved_ev, serial, frames, geo_range = store.saved[0] + assert (serial, frames, geo_range) == ("BE18193", ["frame"], 0) + assert saved_ev.sample_rate == 1024 and saved_ev.rectime_seconds == 3.0 + assert db.get_event(out.db_event_id)["device_family"] == "series3" + assert out.stored_filename == "T193LQ9K.OE0" + + +def test_backfill_derives_total_samples_only_when_the_decoded_one_is_implausible(): + cc = FakeMiniMateClient().compliance # 1024 sps, 3.0 s + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1)) + ev.total_samples = 40_000 + backfill_series3_event(ev, cc) + assert ev.total_samples == 3072 + ev.total_samples = 3000 + backfill_series3_event(ev, cc) + assert ev.total_samples == 3000 + + +def test_backfill_without_settings_changes_nothing(): + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1)) + backfill_series3_event(ev, None) + assert ev.sample_rate is None +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_event_ingest.py -q` + Expected: FAIL with `ModuleNotFoundError: No module named 'sfm.event_ingest'`. + +- [ ] **Step 3: Implement.** Create `sfm/event_ingest.py`: + +```python +"""Store an event SFM downloaded from a unit -- the SDM side of +POST /device/events/download. + +Both series end in the two writes every other ingest path makes: the waveform +store (file + sidecar + .h5) and SeismoDb.insert_events(). The database matches +rows on (serial, timestamp), so storing an event already there -- by an earlier +download, or by THOR's watcher -- refreshes the row instead of duplicating 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 persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload: + if dl.series == 4: + ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename), + serial_hint=dl.serial) + family = "series4" + else: + ev = dl.event + 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), + ) +``` + + In `sfm/server.py`: + - Add `from sfm.event_ingest import backfill_series3_event, persist_download` after `from sfm import db_snapshot`. + - In `device_event_blastware_file`, replace this block: + +```python + cc = info.compliance_config + # 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 +``` + + with + +```python + cc = info.compliance_config + backfill_series3_event(ev, cc) +``` + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_event_ingest.py -q` + Expected: 6 passed. + +- [ ] **Step 5: Commit and push.** Message: `feat(sfm): store a downloaded event -- one ingest for both series`. + +--- + +### Task 8: The endpoints + +**Files:** +- Modify: `sfm/server.py`: `_SERIAL_AWARE_PATHS`, `device_events`, new `device_events_download` +- Modify: `tests/test_server_device_access.py` + +**Interfaces:** +- Consumes: Tasks 6–7. +- Produces: + - `GET /device/events?serial=…` → `EventList` as JSON. + - `POST /device/events/download?serial=…&event_id=…` → `EventDownload` as JSON. + +- [ ] **Step 1: Write the failing tests.** In `tests/test_server_device_access.py`: + - Change the `da` fixture's factories to `lambda a, **kw: s3q.pop(0)` and `lambda a, **kw: s4q.pop(0)`. + - Add `"/device/events", "/device/events/download"` to the path list of `test_guard_allows_um_serial_on_serial_aware_routes_and_hangup`. + - Append: + +```python +# ── events ──────────────────────────────────────────────────────────────────── + +from sfm.database import SeismoDb # noqa: E402 +from sfm.waveform_store import WaveformStore # noqa: E402 + +W_ID = "UM20147:055d4a81:20250531135901" + + +@pytest.fixture +def sdm(tmp_path, monkeypatch): + db = SeismoDb(tmp_path / "seismo.db") + store = WaveformStore(tmp_path / "waveforms") + monkeypatch.setattr(srv, "_get_db", lambda: db) + monkeypatch.setattr(srv, "_get_store", lambda: store) + return store, db + + +EV = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034) + + +@pytest.mark.parametrize("serial,series", [("UM20147", 4), ("BE18193", 3)]) +def test_events_with_a_serial_return_the_shared_list(da, serial, series): + out = srv.device_events(debug=False, force=False, serial=serial, **EV) + assert (out["serial"], out["series"], len(out["events"])) == (serial, series, 2) + assert set(out["events"][0]) == {"event_id", "serial", "series", "index", "timestamp", + "record_type", "peak_vector_sum_ips", "peaks_ips", + "filename", "detail"} + + +def test_events_without_a_serial_run_the_legacy_path(monkeypatch): + class Legacy(Exception): + pass + + def untouchable(): + raise AssertionError("DeviceAccess must not be used without a serial") + + def legacy_cache(): + raise Legacy() + monkeypatch.setattr(srv, "_device_access", untouchable) + monkeypatch.setattr(srv, "get_cache", legacy_cache) + with pytest.raises(Legacy): + srv.device_events(debug=False, force=False, serial=None, **EV) + + +def test_download_stores_the_event_and_says_where(da, sdm): + out = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) + assert out["inserted"] is True and out["verified"] is True + assert out["stored_filename"] == "UM20147_20250531135901.IDFW" + _store, db = sdm + assert db.get_event(out["db_event_id"])["serial"] == "UM20147" + + +def test_downloading_it_again_refreshes_the_same_row(da, sdm): + first = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) + again = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) + assert again["inserted"] is False and again["db_event_id"] == first["db_event_id"] + + +@pytest.mark.parametrize("event_id,status", [ + ("UM12947:055d4a81:20250531135901", 422), # another unit's event + ("garbage", 422), + ("UM20147:055d4a81:20240101000000", 409), # stale: erased since listed + ("UM20147:deadbeef:-", 404), +]) +def test_download_errors_have_their_statuses(da, sdm, event_id, status): + with pytest.raises(HTTPException) as ei: + srv.device_events_download(serial="UM20147", event_id=event_id, **EV) + assert ei.value.status_code == status + assert sdm[1].query_events(serial="UM20147") == [] + + +def test_a_decode_that_disagrees_is_502_and_nothing_is_stored(da, sdm, monkeypatch): + from micromate.client import DecodeMismatch + + def mismatch(*a, **kw): + raise DecodeMismatch("decoded PVS differs by +5%") + fake = FakeMicromateClient() + fake.fetch_event = mismatch + monkeypatch.setattr(da, "_s4_factory", lambda a, **kw: fake) + with pytest.raises(HTTPException) as ei: + srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) + assert ei.value.status_code == 502 + assert sdm[1].query_events(serial="UM20147") == [] + + +def test_a_store_failure_is_500_and_names_what_was_downloaded(da, monkeypatch): + class BrokenStore: + def save_imported_idf(self, *a, **kw): + raise OSError("disk full") + monkeypatch.setattr(srv, "_get_store", lambda: BrokenStore()) + with pytest.raises(HTTPException) as ei: + srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) + assert ei.value.status_code == 500 + assert "UM20147_20250531135901.IDFW" in ei.value.detail and "disk full" in ei.value.detail +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q` + Expected: FAIL with `TypeError: device_events() got an unexpected keyword argument 'serial'`, and `AttributeError ... device_events_download`. + +- [ ] **Step 3: Implement.** In `sfm/server.py`: + + `_SERIAL_AWARE_PATHS` becomes: + +```python +_SERIAL_AWARE_PATHS = frozenset({ + "/device/info", "/device/connect", "/device/monitor/status", "/device/settings", + "/device/events", "/device/events/download", +}) +``` + + `device_events`: + - Change the `baud` line to ` baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),`. + - Add ` serial: Optional[str] = Query(None, description=_SERIAL_DOC),` as the last parameter. + - Add this paragraph at the top of its docstring: + +``` + **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. +``` + + - Insert as the first statements after the docstring, before the `log.info(...)` line: + +```python + 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 +``` + + Add the new handler right after `device_settings`: + +```python +@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}/... . Storing an event that is already stored + refreshes its row (`inserted: false`). 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) +``` + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q` + Expected: all pass. + +- [ ] **Step 5: Run the full suite.** + Run: `.venv/bin/python -m pytest -q 2>&1 | tail -3` + Expected: exactly the 16 pre-existing failures; everything else passes. + +- [ ] **Step 6: Commit and push.** Message: `feat(sfm): list and download events by serial for both series`. + +--- + +### Task 9: Bench check on UM20147, and the record + +**Files:** +- Modify: `CLAUDE.md`, `README.md`, `docs/micromate_protocol_reference.md` +- Scratch (not committed): a launcher and a probe script in the session scratchpad + +Read-only throughout. UM20147 is on `/dev/ttyACM0`, which needs `sg dialout -c "..."`. The server runs on **port 8299** with a **scratch database**, never the dev DB and never port 8200. Start the server, query it and stop it **within one Bash command**: shell state does not persist between calls. + +- [ ] **Step 1: Write the launcher** at `/sfm_bench.py`: + +```python +import sys +from pathlib import Path + +sys.path.insert(0, "/home/serversdown/seismo-relay") +import uvicorn # noqa: E402 +import sfm.server as srv # noqa: E402 + +srv._DEFAULT_DB_PATH = Path(sys.argv[1]) # scratch DB, created on first use +uvicorn.run(srv.app, host="127.0.0.1", port=8299, log_level="info") +``` + +- [ ] **Step 2: One command.** It must: + - start the launcher under `sg dialout`, with the DB at `/bench1b/seismo.db` and the log at `/bench1b/server.log`; + - wait for `GET /health`; + - run the calls below; + - kill the server by PID (`pgrep -f sfm_bench.py`) and confirm it is gone. + +```bash +B="http://127.0.0.1:8299"; U="serial=UM20147&port=/dev/ttyACM0" +curl -s "$B/device/monitor/status?$U" # event_count +curl -s "$B/device/events?$U" > /bench1b/events.json # the list +# pick the first waveform's and the first histogram's event_id from events.json (python -c ...) +curl -s -X POST "$B/device/events/download?$U&event_id=" +curl -s -X POST "$B/device/events/download?$U&event_id=" # again: inserted false, same db_event_id +curl -s -X POST "$B/device/events/download?$U&event_id=" +curl -s -o /bench1b/w.bin "$B/db/events//blastware_file" +curl -s -o /dev/null -w "%{http_code}\n" -X POST "$B/device/events/download?$U&event_id=" # 409 +curl -s -X POST "$B/device/hangup?port=/dev/ttyACM0" +``` + + Check each of these, and report every one: + - the list's length equals status's `event_count`; + - every event has a non-null timestamp, record_type and filename; + - the waveform download has `verified: true`, and the histogram `verified: null`; + - the second download has `inserted: false` with the same `db_event_id`; + - the size of `w.bin` equals that event's `detail.size_bytes`; + - the altered id gives 409; + - the server log shows ONE call-up for the whole sequence, then a hang-up. + +- [ ] **Step 3: Measure direct-by-key download (a read; protocol finding).** With the server stopped, run a scratch script under `sg dialout`: + - `MicromateClient` over `SerialTransport("/dev/ttyACM0", 115200)`, then `open()` and `connect()`; + - `refs = list_events()`; + - for the same waveform, `direct = download_event(ref, chunk_size=1024)` with the cursor parked at the end of the chain; + - `walked = ` the same bytes via `iter_events()` at the cursor; + - compare `direct == walked` and both against `w.bin`. + + Record the result in `docs/micromate_protocol_reference.md`, in the section on event download (find "iter_events" or "cursor"). Use a dated (2026-10-21+) and **graded** line: *measured on one unit over USB, N events*. Do NOT change `s4_download_event`; switching paths is a later decision. + +- [ ] **Step 4: The record.** + - `CLAUDE.md`: in the "SFM speaks Series 4 by serial" bullet, add one sentence: phase 1b lists and downloads events by serial for both series (MiniMate list from headers only, no 5A), with downloads stored in SFM's DB. ⚠ The MiniMate header walk is **unproven on a unit; a MiniMate bench check is owed before the branch merges.** + - In the "SFM REST API" live-device list, add `GET /device/events?serial=` and `POST /device/events/download`. + - `README.md`: in the device endpoints section, document both, including: + - `event_id` and the 409-on-stale behaviour; + - that downloading stores the event and returns `db_event_id`; + - that a re-download refreshes the row; + - that the unit is busy for the whole download. + +- [ ] **Step 5: Commit and push.** Message: `docs: phase 1b bench-checked on UM20147 -- events by serial for both series`. + +--- + +## Self-review notes + +- **Spec rows 4–5:** + - Tasks 1/4: S3 list and download. + - Tasks 2/5: S4. + - Task 6: one door. + - Task 7: store. + - Task 8: endpoints. + - Task 9: hardware. + - The 1b decisions in the spec map to Tasks 1 (header walk), 7 (download stores), 3 (event_id) and 5 (walk-to-event, THOR chunk size). +- **The MiniMate bench check is deliberately not a task.** No MiniMate is on the bench. Task 9 records it as owed before merge, in CLAUDE.md as well as in the spec. +- **Not in 1b:** + - event delete; + - the 64 KB page fix (only named, in Task 4); + - a byte-level verification for Series 3 (`verified` is None for Series 3: there is no self-check to run); + - caching on the serial path. diff --git a/docs/superpowers/plans/2026-10-22-sfm-series4-write-path-phase2.md b/docs/superpowers/plans/2026-10-22-sfm-series4-write-path-phase2.md new file mode 100644 index 0000000..240da39 --- /dev/null +++ b/docs/superpowers/plans/2026-10-22-sfm-series4-write-path-phase2.md @@ -0,0 +1,1135 @@ +# Series-4 write path, phase 2: encoder, opcode guard, dry run — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build every Micromate write a later phase needs as an exact, reviewable **write plan**, proven byte for byte against THOR's captured frames. Make it impossible for any code path to transmit a write opcode, or `0xA2` ever, by accident. Nothing is sent to a unit. + +**Architecture:** +- `micromate/framing.py`: `build_request()` gains an optional data section, using the same escape set and SUM8 it already applies. +- `micromate/opcodes.py` (new): one table of write SUBs and one of cross-series collisions (`0xA2`). +- **The send-side gate.** `MicromateProtocol._send()` now reads each outgoing frame's SUB. It refuses any write SUB the protocol object was not explicitly allowed, and always refuses a collision. No production caller allows anything in this phase. +- `micromate/writes.py` (new): pure functions that turn the unit's own reads into a `WritePlan`, i.e. the frames, in order, with expected acks. That plan is what each later write endpoint's `dry_run=true` returns. +- A bench tool, `bridges/mm_dry_run.py`, does the reads on a live unit and prints the plan, sending nothing else. It is step 1 of the spec's bench protocol for every first live write. + +**Tech Stack:** Python 3, pytest. `micromate/` codec + protocol (no `sfm` imports). + +**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`. The sections that apply are *The safety layer* (opcode guard), *Series-4 write path* (encoder, dry run, per-operation table, setup-push details), *Testing* (frame reproduction) and *Build phases* item 2. + +## Global Constraints + +- **Nothing but reads reaches a unit.** No task may construct `MicromateProtocol` / `MicromateClient` with a non-empty `allowed_writes` outside a test that uses a scripted transport. Task 5 (bench) sends reads only. +- **`0xA2` is never transmitted on Series 4.** The collision guard refuses it even when "allowed". Lifting that needs a spec change, not a parameter. +- **A call-home plan changes exactly bit 0 of content byte `[5]`.** Every other byte, including the unit-maintained `[118:120]`, is echoed from the read. Never write modem baud or modem type. +- **The setup-push read-modify-write sends back only what was read.** No field editing in this phase. Field encoding is phase 5. +- **Codec purity:** nothing in `micromate/` imports `sfm`. `micromate/` may import `minimateplus.transport` only, as today. +- **Never move, rename or delete `bridges/captures/`**, even temporarily: it holds irreplaceable research captures. Read it only. +- **Fixtures:** `tests/fixtures/` and `bridges/captures/` are gitignored. Fixtures cut from captures go in `tests/fixtures/micromate-writes/` and are **force-added** (`git add -f`). Tests that read `bridges/captures/` directly must `skipif` when it is absent. +- **The suite's 16 pre-existing failures** (test_bw_ascii_report.py 15, test_event_file_io.py 1; missing gitignored fixtures) stay exactly that set. +- **Branch `feat/series4-sfm-parity`.** + - Never commit to `main` or `dev`. + - Do not edit `CHANGELOG.md`. + - After each commit, run `git push`. +- **Hardware:** only Task 5 touches `/dev/ttyACM0` (UM20147), under `sg dialout -c "..."`. Never start a server on port 8200. +- **Every commit message ends with:** + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 + ``` + +## Review Focus + +These are the inputs most likely to bite, each with a test in the named task. + +1. **A write opcode reaching the wire by any path.** This includes `_exchange`, a direct `_send`, a scratch tool calling `protocol._send`, and a frame built by hand. It must be refused with nothing written to the transport (Task 2). +2. **`0xA2` in a plan or a send.** It is refused even when explicitly allowed (Tasks 2, 4). +3. **A read whose block fails its CRC, or has a size THOR's offset was never observed at.** Building a plan from it must be refused. Otherwise it would write corruption back, or use an unverified offset (Task 4). +4. **Escape bytes inside data**, including a literal `0x10` (never captured in write data) and a checksum that lands on `02/03/04/10`. The frame must still be correct (Task 1). +5. **The call-home plan must flip exactly one bit.** Every other byte must equal the read (Task 4). + +--- + +## File map + +| file | change | +|---|---| +| `micromate/framing.py` | `build_request(..., data=b"")`; new `request_sub(frame)` | +| `micromate/opcodes.py` | **new**: `WRITE_SUBS`, `CROSS_SERIES_COLLISIONS`, `OpcodeRefused`, `check_transmit()` | +| `micromate/protocol.py` | `MicromateProtocol(allowed_writes=frozenset())`; `_send` gate; docstring | +| `micromate/client.py` | docstring only ("reads only" now enforced) | +| `micromate/writes.py` | **new**: `WriteStep`, `WritePlan`, `plan_start_monitoring`, `plan_stop_monitoring`, `plan_call_home_enabled`, `plan_setup_push` | +| `scratch/mm_write_fixtures.py` | **new**: cuts fixtures out of the captures (reproducible provenance) | +| `tests/fixtures/micromate-writes/*.json` | **new, force-added**: seven captured sessions | +| `bridges/mm_dry_run.py` | **new**: live dry run, reads only | +| tests | `test_micromate_framing.py` (+), `test_micromate_opcodes.py` (new), `test_micromate_write_fixtures.py` (new), `test_micromate_writes.py` (new) | +| docs | `docs/micromate_protocol_reference.md`, `CLAUDE.md` (Task 5) | + +--- + +### Task 1: The encoder — a data section on `build_request` + +**Files:** +- Modify: `micromate/framing.py`, `build_request` (line 129) +- Test: `tests/test_micromate_framing.py` (append) + +**Interfaces:** +- Produces: + - `build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: bytes = b"") -> bytes`. The data goes after params, inside the stuffing and the checksum. + - `request_sub(frame: bytes) -> int`, the SUB of a built host→unit frame. It raises `ValueError` on anything that isn't one. + +- [ ] **Step 1: Write the failing tests.** Append to `tests/test_micromate_framing.py`: + +```python +# ── the data section (writes) ───────────────────────────────────────────────── + +from micromate.framing import request_sub, unstuff # noqa: E402 + + +def _destuffed_payload(frame: bytes) -> bytes: + body = unstuff(frame[2:-1]) + return body[:-1] # drop the checksum byte + + +def test_data_goes_after_the_params_inside_the_checksum(): + data = bytes(range(0x20, 0x40)) + f = build_request(0x7E, 0x007E, bytes(10), data) + payload = _destuffed_payload(f) + assert payload[:6] == bytes([0x10, 0x00, 0x7E, 0x00, 0x00, 0x7E]) + assert payload[6:16] == bytes(10) and payload[16:] == data + assert unstuff(f[2:-1])[-1] == sum(payload) & 0xFF + + +@pytest.mark.parametrize("b", [0x02, 0x03, 0x04, 0x10]) +def test_every_escape_byte_in_data_is_escaped_on_the_wire(b): + f = build_request(0x71, 0x082C, bytes(10), bytes([0x55, b, 0x55])) + assert bytes([0x55, DLE, b, 0x55]) in f + assert _destuffed_payload(f)[16:] == bytes([0x55, b, 0x55]) + + +def test_a_literal_0x10_in_data_round_trips(): + # Never captured in write data; params already prove `10 10` (SUB 0x5A). + data = b"\x10\x10\x00\x10" + assert _destuffed_payload(build_request(0x71, 0x082C, bytes(10), data))[16:] == data + + +def test_a_checksum_that_lands_on_an_escape_byte_is_escaped(): + # Pick the last data byte so SUM8 of the payload is exactly 0x03. + head = bytes([0x10, 0x00, 0x7E, 0x00, 0x00, 0x7E]) + bytes(10) + b"\x01\x02" + last = (0x03 - sum(head)) & 0xFF + f = build_request(0x7E, 0x007E, bytes(10), b"\x01\x02" + bytes([last])) + assert f[-3:] == bytes([DLE, 0x03, ETX]) + + +def test_without_data_the_frame_is_unchanged(): + assert build_request(0x5B, 0x0030) == build_request(0x5B, 0x0030, bytes(10), b"") + + +def test_request_sub_reads_the_sub_back_even_when_stuffed(): + assert request_sub(build_request(0x96, 0xFFFF)) == 0x96 + assert request_sub(build_request(0x10, 0x0000)) == 0x10 # SUB itself escaped + assert request_sub(build_request(0x71, 0x082C, bytes(10), b"\x03" * 5)) == 0x71 + + +@pytest.mark.parametrize("junk", [b"", b"\x41\x02\x03", b"\x02\x10\x10\x00\x96\x03", b"hello"]) +def test_request_sub_refuses_anything_that_is_not_a_request_frame(junk): + with pytest.raises(ValueError): + request_sub(junk) + + +@pytest.mark.skipif( + not _CAPTURES.is_dir(), + reason="capture directory is gitignored; present only on a dev box", +) +def test_builder_reproduces_every_captured_request_frame_including_writes(): + """251/251: the 218 reads plus the 33 data-carrying writes.""" + checked = 0 + for path in sorted(_CAPTURES.rglob("raw_bw_*.bin")): + blob = path.read_bytes() + 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 + body = bytearray() + while j < len(blob): + if blob[j] == DLE and j + 1 < len(blob): + body.append(blob[j + 1]) + j += 2 + continue + if blob[j] == ETX: + break + body.append(blob[j]) + j += 1 + payload = bytes(body[:-1]) + sub = payload[2] + offset = (payload[4] << 8) | payload[5] + assert build_request(sub, offset, payload[6:16], payload[16:]) == blob[i:j + 1], ( + f"{path.name} @0x{i:04x} SUB=0x{sub:02x}" + ) + checked += 1 + i = j + 1 + assert checked == 251, f"expected 251 request frames, checked {checked}" +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_micromate_framing.py -q` + Expected: FAIL with `ImportError: cannot import name 'request_sub'`. + +- [ ] **Step 3: Implement.** In `micromate/framing.py`: + - Change the signature to `def build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: bytes = b"") -> bytes:`. + - Add to its docstring's Args: + +``` + 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. +``` + + - Change the `payload = ...` line to: + +```python + payload = (bytes([MM_CMD, 0x00, sub, 0x00, (offset >> 8) & 0xFF, offset & 0xFF]) + + params + bytes(data)) +``` + + - Add after `build_request`: + +```python +def request_sub(frame: bytes) -> int: + """The SUB of a built host->unit frame (`41 02 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()}") + return body[2] +``` + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_micromate_framing.py -q` + Expected: all pass, including both capture-gated tests on this box (218 and 251). + +- [ ] **Step 5: Commit and push.** Message: `feat(micromate): build_request carries a data section -- reproduces all 251 THOR request frames`. + +--- + +### Task 2: The opcode table and the send-side gate + +**Files:** +- Create: `micromate/opcodes.py` +- Modify: `micromate/protocol.py`: `MicromateProtocol.__init__` (line 241), `_send` (line 511) and the module docstring. Also `micromate/client.py`, docstring line 5. +- Test: `tests/test_micromate_opcodes.py` (new) + +**Interfaces:** +- Consumes: Task 1's `request_sub`. +- Produces: + - `WRITE_SUBS: dict[int, str]` + - `CROSS_SERIES_COLLISIONS: dict[int, str]` + - `class OpcodeRefused(RuntimeError)` + - `check_transmit(sub, allowed_writes=frozenset()) -> None` + - `MicromateProtocol(transport, recv_timeout=..., strict_checksums=True, allowed_writes: frozenset = frozenset())` + +- [ ] **Step 1: Write the failing tests** in `tests/test_micromate_opcodes.py`: + +```python +"""The send-side gate: no write opcode reaches the wire unless allowed, and 0xA2 never.""" +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.framing import build_request # noqa: E402 +from micromate.opcodes import ( # noqa: E402 + CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused, check_transmit, +) +from test_micromate_protocol import frame, proto # noqa: E402 + +# THOR's captured end-call-home frame -- byte-identical to Series III's CONFIRM ERASE. +A2_WIRE = bytes.fromhex("4102101000a200ffff00000000000000000000b003") + + +def test_no_read_command_is_classed_as_a_write(): + reads = {v for k, v in vars(mm_proto).items() if k.startswith("SUB_")} + assert reads and not (reads & set(WRITE_SUBS)) + + +def test_0xa2_is_a_collision_and_a_write(): + assert 0xA2 in CROSS_SERIES_COLLISIONS and 0xA2 in WRITE_SUBS + + +def test_a_write_is_refused_unless_allowed(): + with pytest.raises(OpcodeRefused, match="0x96"): + check_transmit(0x96) + check_transmit(0x96, frozenset({0x96})) + check_transmit(0x5B) # a read needs no permission + + +def test_0xa2_is_refused_even_when_allowed(): + with pytest.raises(OpcodeRefused, match="ERASE"): + check_transmit(0xA2, frozenset({0xA2})) + + +def test_the_protocol_refuses_a_write_and_writes_nothing(): + p, t = proto([]) + with pytest.raises(OpcodeRefused): + p._exchange(0x96, offset=0xFFFF) + with pytest.raises(OpcodeRefused): + p._send(build_request(0x97, 0xFFFF)) # a direct _send is gated too + assert t.written == [] + + +def test_the_protocol_refuses_the_captured_0xa2_frame_byte_for_byte(): + p, t = proto([], allowed_writes=frozenset({0xA2})) + with pytest.raises(OpcodeRefused): + p._send(A2_WIRE) + assert t.written == [] + + +def test_an_explicitly_allowed_write_goes_out_on_a_scripted_transport(): + p, t = proto([frame(0x69, bytes(11))], allowed_writes=frozenset({0x96})) + p._exchange(0x96, offset=0xFFFF) + assert t.written == [build_request(0x96, 0xFFFF)] + + +def test_reads_are_unaffected_by_the_gate(): + p, t = proto([frame(0xA4, bytes(11))]) + p.poll() + assert len(t.written) == 1 + + +def test_a_frame_that_is_not_a_request_is_refused_not_sent(): + p, t = proto([]) + with pytest.raises(ValueError): + p._send(b"\x41\x03") + assert t.written == [] +``` + + Before running, check `tests/test_micromate_protocol.py`: + - Does `proto(responses, **kw)` forward `**kw` to `MicromateProtocol`? + - Is `frame(rsp_sub, data, ...)` the response builder? + - If either differs, adapt only the import lines and the call shape, and say so in the report. + + Also check what POLL's response SUB is: `0xFF - 0x5B = 0xA4`. + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_micromate_opcodes.py -q` + Expected: FAIL with `ModuleNotFoundError: No module named 'micromate.opcodes'`. + +- [ ] **Step 3: Implement.** Create `micromate/opcodes.py`: + +```python +"""Micromate (Series IV) opcode table: which SUBs write, and which collide. + +One place, as the parity spec requires. `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 typing import Dict, FrozenSet + +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 bytes, opposite consequence on the other series. 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", +} + + +class OpcodeRefused(RuntimeError): + """A frame was stopped before it reached the wire.""" + + +def check_transmit(sub: int, allowed_writes: FrozenSet[int] = frozenset()) -> None: + if sub in CROSS_SERIES_COLLISIONS: + raise OpcodeRefused( + f"refused to transmit SUB 0x{sub:02X}: {CROSS_SERIES_COLLISIONS[sub]}") + 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") +``` + + In `micromate/protocol.py`: + - Imports: extend `from .framing import ...` with `request_sub`, and add `from .opcodes import check_transmit`. + - `__init__`: add the parameter `allowed_writes: frozenset = frozenset(),` after `strict_checksums`, and set `self._allowed_writes = frozenset(allowed_writes)` with the other assignments. Add to the docstring: + +``` + allowed_writes: write SUBs this connection may transmit. Empty by + default -- every write opcode in `micromate.opcodes` is refused + at `_send`, and `0xA2` is refused whatever this says. +``` + + - `_send`: + +```python + def _send(self, frame: bytes) -> None: + # The gate sees the bytes that are about to go out, not the caller's + # intent: every transmit in this package passes through here. + check_transmit(request_sub(frame), self._allowed_writes) + log.debug("TX %d bytes: %s", len(frame), frame.hex()) + self._transport.write(frame) +``` + + - Module docstring: replace the paragraph that begins `Scope: **reads only.**` up to `...not a side effect of a client that grew a method.` with: + +``` +Scope: **reads only on the wire, enforced.** Every outgoing frame passes +`micromate.opcodes.check_transmit()` in `_send`: a write opcode is refused +unless this connection was constructed with it in `allowed_writes` (nothing in +the codebase does so yet), and `0xA2` -- CONFIRM ERASE on Series III -- is +refused always. 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. +``` + + In `micromate/client.py`, change the docstring line saying reads only, at line 5, to say reads only, enforced by the protocol's opcode gate (`micromate.opcodes`). + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_micromate_opcodes.py tests/test_micromate_protocol.py tests/test_micromate_client.py tests/test_micromate_events.py -q` + Expected: all pass, including the THOR replay tests on this box. If a replay test now raises `OpcodeRefused`, it was transmitting a captured write through the protocol. STOP and report it; do not allow writes to make it pass. + +- [ ] **Step 5: Full suite.** Run `.venv/bin/python -m pytest -q 2>&1 | tail -3`. Only the 16 pre-existing failures are allowed. + +- [ ] **Step 6: Commit and push.** Message: `feat(micromate): one opcode table and a send-side gate -- writes refused unless allowed, 0xA2 always`. + +--- + +### Task 3: Fixtures cut from THOR's write captures + +**Files:** +- Create: `scratch/mm_write_fixtures.py` +- Create, force-added: `tests/fixtures/micromate-writes/*.json` +- Test: `tests/test_micromate_write_fixtures.py` (new) + +**Interfaces:** +- Produces: one JSON file per captured session, in this schema: + +```json +{ + "source": "bridges/captures/9-24-26 - micromate2/", + "source_sha256": {"bw": "", "s3": ""}, + "unit": "UM12947", + "firmware_line": "11.0CB", + "exchanges": [ + {"sub": 65, "request": "", "response_sub": 190, "response_data": ""} + ] +} +``` + + The sessions and their slugs: + +| slug | capture (under `bridges/captures/9-24-26 - micromate2/`) | +|---|---| +| `setup-push-new-test1` | `raw_{bw,s3}_20260924_181942_send_TEST1_to_unit.bin` | +| `setup-push-overwrite-test1` | `overwritetest/raw_{bw,s3}_20260924_185113_test1_overwrite_check.bin` | +| `setup-push-read-scheduler` | `raw_{bw,s3}_20260924_191835_read_scheduler.bin` | +| `setup-push-pull-schedule` | `raw_{bw,s3}_20260925_003029_pull_schedule,_turn_off_repeat_daily,_push_schedule.bin` | +| `setup-push-multiday` | `raw_{bw,s3}_20260925_011907_send_multiday_schedule.bin` | +| `call-home-enable-disable` | `raw_{bw,s3}_20260925_011620_ACH-change_1_setting.bin` | +| `monitor-start-stop` | `raw_{bw,s3}_20260924_191214_turn_on_monitormode_then_attempt_to_write_config.bin` | + +- [ ] **Step 1: Write the extraction script** `scratch/mm_write_fixtures.py`: + +```python +#!/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 # 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 = [] + for rq, rp in zip(reqs, rsps): + from micromate.framing import request_sub + 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_line": "11.0CB", + "exchanges": exchanges, + } + (OUT / f"{slug}.json").write_text(json.dumps(doc, indent=1) + "\n") + print(f"{slug}: {len(exchanges)} exchanges") + + +if __name__ == "__main__": + main() +``` + + Check two things before running: + - `MicromateFrameParser().feed()` returns a list of `MicromateFrame` with `.sub`, `.data` and `.checksum_valid` (micromate/framing.py). + - Responses index-align with requests. The survey measured equal counts in every pair; the script refuses otherwise. + + Move the `request_sub` import to the top imports. It is shown inline above only for clarity. + +- [ ] **Step 2: Run it.** `.venv/bin/python scratch/mm_write_fixtures.py`. Expect 7 lines, one per slug. Check the count for each kind of session: + - **setup push:** 12 to 25 exchanges; + - **call-home:** 14; + - **start/stop:** about 40. + + If any session fails alignment, STOP and report it. + +- [ ] **Step 3: Write the tests** in `tests/test_micromate_write_fixtures.py`: + +```python +"""The write-session fixtures are what they claim to be: THOR's own frames, paired.""" +from __future__ import annotations + +import json +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 micromate.framing import request_sub, unstuff # noqa: E402 + +FIX = Path(__file__).parent / "fixtures" / "micromate-writes" +ALL = sorted(FIX.glob("*.json")) + + +def test_all_seven_sessions_are_present(): + assert {p.stem for p in ALL} == { + "setup-push-new-test1", "setup-push-overwrite-test1", "setup-push-read-scheduler", + "setup-push-pull-schedule", "setup-push-multiday", "call-home-enable-disable", + "monitor-start-stop"} + + +@pytest.mark.parametrize("path", ALL, ids=lambda p: p.stem) +def test_every_request_is_a_valid_frame_and_every_response_answers_it(path): + doc = json.loads(path.read_text()) + assert doc["source_sha256"]["bw"] and doc["exchanges"] + for ex in doc["exchanges"]: + wire = bytes.fromhex(ex["request"]) + assert request_sub(wire) == ex["sub"] + body = unstuff(wire[2:-1]) + assert body[-1] == sum(body[:-1]) & 0xFF # plain SUM8 + assert ex["response_sub"] == 0xFF - ex["sub"] + + +@pytest.mark.parametrize("slug,subs", [ + ("setup-push-new-test1", [0x41, 0x08, 0x2E, 0x1A, 0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72]), + ("call-home-enable-disable", [0x2C, 0x7E, 0x7F]), + ("monitor-start-stop", [0x96, 0x97]), +]) +def test_each_session_holds_the_frames_its_tests_need(slug, subs): + seen = [ex["sub"] for ex in json.loads((FIX / f"{slug}.json").read_text())["exchanges"]] + for s in subs: + assert s in seen, f"{slug}: no SUB 0x{s:02X}" +``` + +- [ ] **Step 4: Run the tests and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_micromate_write_fixtures.py -q`. + To show the fixtures stand alone, check that neither the fixture tests nor Task 4's tests reference the capture directory: + `grep -n "captures" tests/test_micromate_write_fixtures.py` must print nothing. + ⚠ **Never move, rename or delete `bridges/captures/`**, not even temporarily. It holds irreplaceable research captures. + +- [ ] **Step 5: Commit and push.** Use `git add -f tests/fixtures/micromate-writes/*.json` and `git add scratch/mm_write_fixtures.py tests/test_micromate_write_fixtures.py`. Message: `test(micromate): THOR's write sessions as fixtures -- seven captures, paired, with provenance`. + +--- + +### Task 4: Write plans, reproduced byte for byte + +**Files:** +- Create: `micromate/writes.py` +- Test: `tests/test_micromate_writes.py` (new) + +**Interfaces:** +- Consumes: + - Task 1's `build_request(data=)`; + - Task 2's `WRITE_SUBS`, `CROSS_SERIES_COLLISIONS` and `OpcodeRefused`; + - `micromate.setup_block.crc_ok`; + - Task 3's fixtures. +- Produces: + - `WriteStep(sub, offset, data=b"", params=bytes(10), what="")` with `.ack_sub`, `.frame` and `.describe()`; + - `WritePlan(action, steps)` with `.subs`, `.frames()` and `.describe()`; + - `plan_start_monitoring()`, `plan_stop_monitoring()`; + - `plan_call_home_enabled(call_home: bytes, enabled: bool)`; + - `plan_setup_push(prefs: bytes, trigger: bytes, setup: bytes, name: str)`. + + All inputs are block **content**: response data `[11:]`. + +- [ ] **Step 1: Write the failing tests** in `tests/test_micromate_writes.py`: + +```python +"""Write plans: built from the unit's own reads, equal to THOR's frames byte for byte.""" +from __future__ import annotations + +import json +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 micromate.opcodes import OpcodeRefused # noqa: E402 +from micromate.writes import ( # noqa: E402 + WritePlan, WriteStep, plan_call_home_enabled, plan_setup_push, + plan_start_monitoring, plan_stop_monitoring, +) + +FIX = Path(__file__).parent / "fixtures" / "micromate-writes" +PUSHES = ["setup-push-new-test1", "setup-push-overwrite-test1", "setup-push-read-scheduler", + "setup-push-pull-schedule", "setup-push-multiday"] +NO_EDIT_PUSHES = ["setup-push-read-scheduler", "setup-push-pull-schedule", "setup-push-multiday"] + + +def _session(slug): + return json.loads((FIX / f"{slug}.json").read_text())["exchanges"] + + +def _content(ex): + return bytes.fromhex(ex["response_data"])[11:] + + +def _first_push(slug): + """The reads (by SUB) and THOR's writes (by SUB) of the session's first push.""" + ex = _session(slug) + start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA) + reads = {} + for e in ex[:start]: + reads[e["sub"]] = _content(e) # the LAST read of each SUB before the push + writes = {} + for e in ex[start:]: + if e["sub"] in writes: + break + writes[e["sub"]] = bytes.fromhex(e["request"]) + if e["sub"] == 0x72: + break + return reads, writes + + +def _name_from_active(content): + # Mirror how MicromateClient.get_active_setup() extracts the name from the + # 0x41 content -- check it and copy its slicing if the name does not start + # at content[0]. + return content.split(b"\x00", 1)[0].decode("ascii") + + +# ── start / stop ────────────────────────────────────────────────────────────── + +def test_start_and_stop_equal_thors_frames(): + thor = {e["sub"]: bytes.fromhex(e["request"]) for e in _session("monitor-start-stop") + if e["sub"] in (0x96, 0x97)} + assert plan_start_monitoring().frames() == [thor[0x96]] + assert plan_stop_monitoring().frames() == [thor[0x97]] + assert thor[0x96].hex() == "41021010009600ffff00000000000000000000a403" + + +# ── call-home ───────────────────────────────────────────────────────────────── + +def test_call_home_enable_then_disable_equal_thors_frames(): + ex = _session("call-home-enable-disable") + pairs, last_read = [], None + for e in ex: + if e["sub"] == 0x2C: + last_read = _content(e) + elif e["sub"] == 0x7E: + pairs.append((last_read, bytes.fromhex(e["request"]))) + confirms = [bytes.fromhex(e["request"]) for e in ex if e["sub"] == 0x7F] + assert len(pairs) == 2 and len(confirms) == 2 + (r1, w1), (r2, w2) = pairs + on, off = plan_call_home_enabled(r1, True), plan_call_home_enabled(r2, False) + assert on.frames() == [w1, confirms[0]] + assert off.frames() == [w2, confirms[1]] + + +def test_call_home_flips_exactly_one_bit_and_echoes_everything_else(): + r1 = next(_content(e) for e in _session("call-home-enable-disable") if e["sub"] == 0x2C) + for enabled in (True, False): + data = plan_call_home_enabled(r1, enabled).steps[0].data + diff = [i for i in range(len(r1)) if data[i] != r1[i]] + assert set(diff) <= {5} + assert data[5] & 0x01 == (1 if enabled else 0) + assert data[5] & 0xFE == r1[5] & 0xFE + assert data[118:120] == r1[118:120] + + +def test_call_home_refuses_an_unobserved_size(): + with pytest.raises(ValueError, match="126"): + plan_call_home_enabled(bytes(125), True) + + +# ── setup push ──────────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("slug", PUSHES) +def test_setup_push_name_prefs_trigger_and_confirms_equal_thors_frames(slug): + reads, thor = _first_push(slug) + name = ("TEST1.mmb" if slug == "setup-push-new-test1" + else _name_from_active(reads[0x41])) + plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name) + ours = {s.sub: s.frame for s in plan.steps} + for sub in (0xDA, 0x68, 0x73, 0x82, 0x83, 0x72): + assert ours[sub] == thor[sub], f"{slug}: SUB 0x{sub:02X}" + assert [s.sub for s in plan.steps] == [0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72] + + +@pytest.mark.parametrize("slug", NO_EDIT_PUSHES) +def test_a_no_edit_push_reproduces_thors_setup_block_frame(slug): + reads, thor = _first_push(slug) + plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], _name_from_active(reads[0x41])) + assert next(s.frame for s in plan.steps if s.sub == 0x71) == thor[0x71] + + +def test_setup_push_refuses_a_read_that_fails_its_checksum(): + reads, _ = _first_push("setup-push-multiday") + bad = bytearray(reads[0x1A]) + bad[100] ^= 0xFF + with pytest.raises(ValueError, match="checksum"): + plan_setup_push(reads[0x08], reads[0x2E], bytes(bad), "x.mmb") + + +@pytest.mark.parametrize("which", ["prefs", "trigger", "setup"]) +def test_setup_push_refuses_an_unobserved_block_size(which): + reads, _ = _first_push("setup-push-multiday") + args = {"prefs": reads[0x08], "trigger": reads[0x2E], "setup": reads[0x1A]} + args[which] = args[which] + b"\x00\x00" + with pytest.raises(ValueError, match="size"): + plan_setup_push(args["prefs"], args["trigger"], args["setup"], "x.mmb") + + +@pytest.mark.parametrize("name", ["", "a\x00b", "é.mmb", "x" * 256]) +def test_setup_push_refuses_a_bad_name(name): + reads, _ = _first_push("setup-push-multiday") + with pytest.raises(ValueError): + plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name) + + +# ── the plan object ─────────────────────────────────────────────────────────── + +def test_a_plan_cannot_hold_a_collision_opcode(): + with pytest.raises(OpcodeRefused): + WritePlan("end call-home", (WriteStep(0xA2, 0xFFFF),)) + + +def test_a_plan_cannot_hold_a_read(): + with pytest.raises(ValueError): + WritePlan("poll", (WriteStep(0x5B, 0x0030),)) + + +def test_describe_is_the_dry_run_shape(): + d = plan_stop_monitoring().describe() + assert d["action"] == "stop monitoring" and d["sends_nothing"] is True + step = d["steps"][0] + assert step == {"sub": "0x97", "what": "stop monitoring", "offset": "0xFFFF", + "data_len": 0, "expect_ack": "0x68", + "frame": "41021010009700ffff00000000000000000000a503"} +``` + +- [ ] **Step 2: Run them, and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_micromate_writes.py -q` + Expected: FAIL with `ModuleNotFoundError: No module named 'micromate.writes'`. + +- [ ] **Step 3: Implement** `micromate/writes.py`: + +```python +"""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 +also needs a protocol constructed with those SUBs in `allowed_writes`, which no +code does yet (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 = "" + + @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, ...] + + def __post_init__(self) -> None: + for s in self.steps: + 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, + "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. + + `[5]` reads 0x05 enabled / 0x04 disabled; bit 2 is set in both, so only + bit 0 is the enable. `[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") + return WritePlan(what, ( + WriteStep(0x7E, 0x007E, data, what="call-home config write"), + WriteStep(0x7F, _CONFIRM, what="call-home config confirm"), + )) + + +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 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. + """ + _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"), + )) +``` + + If a reproduction assertion fails, do NOT adjust the builder to match one capture. Report the exact byte difference. The builder rules come from the survey's measured diffs (`0x68` = `0x08` content[0:88] with [0:3] zeroed; `0x82` = `0x2E` content[0:28] with [0:3] and [26:28] zeroed; `0x71` = `0x1A` content[0:2090] with [0:3] zeroed; `0xDA` = the name, null-padded to 256). A mismatch means a rule is wrong, and that is a finding. + +- [ ] **Step 4: Run the tests, and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_micromate_writes.py -q` + Expected: all pass. + +- [ ] **Step 5: Run the full suite.** Only the 16 pre-existing failures are allowed. + +- [ ] **Step 6: Commit and push.** Message: `feat(micromate): write plans for start/stop, call-home and setup push -- THOR's frames byte for byte`. + +--- + +### Task 5: The dry-run bench tool, run on UM20147 + +**Files:** +- Create: `bridges/mm_dry_run.py` +- Modify: `docs/micromate_protocol_reference.md`, `CLAUDE.md` + +Read-only on the unit. UM20147 is on `/dev/ttyACM0`, which needs `sg dialout -c "..."`. + +- [ ] **Step 1: Write the tool** `bridges/mm_dry_run.py`: + +```python +#!/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 +""" +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 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: + return bytes(data)[11:] + + +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) + mm.open() + try: + info = mm.connect() + p = mm.protocol + if a.action == "start": + plan = plan_start_monitoring() + elif a.action == "stop": + plan = plan_stop_monitoring() + elif a.action.startswith("call-home"): + plan = plan_call_home_enabled(_content(p.read_call_home_config()), + a.action == "call-home-on") + else: + name = mm.get_active_setup() + plan = plan_setup_push(_content(p.read_event_index()), _content(p.read_trigger_config()), + _content(p.read_compliance_config()), name) + out = plan.describe() + out["unit"] = {"serial": info.serial, "firmware_line": info.firmware_line} + print(json.dumps(out, indent=1)) + finally: + mm.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) +``` + + Before running, check the real names and return types of these: + - `MicromateProtocol.read_call_home_config`, `read_event_index` (the `0x08` preferences block), `read_trigger_config` and `read_compliance_config`. Do they return the response data or a frame? + - `MicromateClient.get_active_setup()`. Does it return the file name string, e.g. `"test2.MMB"`? + + Adapt `_content()` and the calls to the real API. Mention any adaptation in the report. + +- [ ] **Step 2: Run it on UM20147, one action at a time.** Run each as its own command, under `sg dialout`: + - `start` + - `stop` + - `call-home-on` + - `call-home-off` + - `setup-rewrite` + + Save each output to `/dryrun/.json`. The scratchpad is `/tmp/claude-1000/-home-serversdown-seismo-relay/fc1049ca-ccbd-41ba-ac35-6b7c3996ffcd/scratchpad`. + + Expected for every action: + - JSON with `sends_nothing: true` and the planned frames. + - No `OpcodeRefused` traceback. The tool only calls reads; a traceback would mean a write was attempted, which is a bug to report. + + If a setup or call-home block is not the observed size on this unit's firmware (11.0BD), the plan is refused with a size error. Record that. It is a finding: THOR's offsets would then be unverified on this firmware. Do not change the size table. + +- [ ] **Step 3: Compare with THOR's frames** (UM12947, 11.0CB, from the fixtures). For each action, tabulate SUB order, offsets and data lengths, ours against THOR's. They should match exactly; only data content differs, since it is the unit's own blocks. + - Also confirm the `setup-rewrite` plan's `0x71` data equals the unit's `0x1A` content [3:2090] with three zero bytes in front. That is a no-edit rewrite. + - For `call-home-off` / `call-home-on`, also confirm exactly one byte ([5]) differs between the two plans' `0x7E` data. + +- [ ] **Step 4: Record.** + - In `docs/micromate_protocol_reference.md`, near the setup-push and call-home write sections, add a **dated, graded** line: "2026-10-22 — UM20147 (11.0BD) block sizes equal UM12947's (11.0CB): …; so THOR's write offsets apply to both firmware lines **as far as size goes** (measured, one unit each; nothing sent)". Use whatever was actually measured. + - In `CLAUDE.md`, add a sentence in the Series-4 "Where things stand" area: + - Phase 2 is done: the write encoder, the opcode gate and write plans. + - It covers start/stop, call-home and the setup rewrite, reproduced byte for byte against THOR (counts). + - `bridges/mm_dry_run.py` prints a write's planned frames from a live unit's reads. + - The protocol's `_send` gate refuses every write opcode unless explicitly allowed, and `0xA2` always. + - "**No command has ever been originated against a unit by this project**" is still true, and is now enforced in code. + +- [ ] **Step 5: Commit and push** the tool and both docs. Message: `feat(bridges): mm_dry_run -- a write's planned frames from a live unit's reads; bench-checked on UM20147`. + +--- + +## Self-review notes + +- **Spec coverage:** + - Encoder: Task 1. + - Opcode guard (one table; `0xA2`): Task 2. + - Dry run: Task 4 (`WritePlan.describe()`) and Task 5 (live). The write endpoints' `dry_run=true` parameter arrives with each write in phases 3–5 and returns `describe()`. + - Frame reproduction for `0x96`/`0x97`, `0x7E`/`0x7F` and the full setup push: Tasks 1, 3 and 4. The `0x71` edit pushes reproduce everything but `0x71`, because field editing is phase 5. + - Fixtures force-added: Task 3. +- **Not in phase 2:** + - Any transmit of a write. + - The identity check, audit table and read-back framework (phase 3). + - Field encoding (phase 5). + - Per-event delete. It is destructive tier; its SUBs are in the opcode table only. + - Scheduler `0x47` and file `0x8D`/`0x8E` (table only). +- **Never captured, and so only synthetic:** + - A checksum on an escape byte. + - A literal `0x10` in data. + - Start or stop when the unit is already in that state. + - Any write on 11.0BD. diff --git a/docs/superpowers/plans/2026-10-23-sfm-phase3-start-stop.md b/docs/superpowers/plans/2026-10-23-sfm-phase3-start-stop.md new file mode 100644 index 0000000..75c5241 --- /dev/null +++ b/docs/superpowers/plans/2026-10-23-sfm-phase3-start-stop.md @@ -0,0 +1,1013 @@ +# Phase 3: start / stop monitoring, the first live write — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Task 7 is not for a subagent**: the controller runs it at the bench, with Brian approving the send. + +**Goal:** Start and stop monitoring by serial, for both series, through the safety layer. The layer covers: +- an identity check right before the write; +- the unit's state, read first; +- a dry run that returns the exact frames; +- an audit row for every attempt; +- a read-back that decides success; +- never a retried write. + +Then make the project's first live send to a unit (UM20147), with Brian approving it at the bench. + +**Architecture:** + +- **Series 4.** `MicromateProtocol.execute(plan)` becomes the only write path. + - It transmits exactly a `WritePlan`'s frames, granting permission for that call alone. + - It refuses any plan beyond a code-reviewed ceiling, `ENABLEABLE_WRITES = {0x96, 0x97}`. + - It refuses on a connection whose replies did not carry Micromate flags. +- **The change operation**, one per series: + 1. re-reads the serial; + 2. reads the run state, `0x49` on Series 4 and `0x1C` on Series 3; + 3. skips or refuses as appropriate; + 4. audits the attempt; + 5. sends; + 6. polls the state until it matches or a window expires; + 7. audits the result. + + It returns a `ChangeResult`. +- **No retry.** `DeviceAccess` runs change operations with no retry of any kind. +- **Audit.** The table lives in SDM (`device_commands` in SeismoDb). The device side writes to it through an injected sink, so `sfm/device_access/` still imports no DB. +- **Endpoints.** The existing `POST /device/monitor/start` and `/stop` gain `serial`, `dry_run`, `even_if_already` and `caller`. Without `serial` they behave exactly as today. + +**Tech Stack:** Python 3, FastAPI, pytest, SQLite. + +**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`, in particular: +- *The safety layer* (tiers, identity, read-back, audit table); +- *Series-4 write path* (dry run, start/stop row); +- *Testing → Bench* (the first-live-send protocol); +- **Build phases item 3, including its "Preconditions from the phase-2 final review" block**, which is binding. + +## Global Constraints + +- **Writes.** The only writes are `0x96`/`0x97`. + - On Series 4 they go through `MicromateProtocol.execute(plan)` only. + - On Series 3 they go through `MiniMateClient.start_monitoring()`/`stop_monitoring()`, which are unchanged. + - Nothing else may be transmitted that changes a unit. + - Tests use fakes and scripted transports only. **No task but Task 7 touches hardware**, and Task 7 sends only with Brian's explicit go-ahead in the conversation. +- **A write is never retried.** + - This covers the retry-once in `DeviceAccess._dispatch`, the TCP retry in `Series3Adapter._run`, and any loop. + - The structure must make retry impossible for a change operation. A comment saying so is not enough. +- **Identity before any write.** + - The serial is read from the unit immediately before the write: `0x15` on Series 4, `connect()` on Series 3. + - A mismatch means 409 and nothing is sent. +- **0xA2 is never sent.** + - The ceiling is `{0x96, 0x97}`. + - Raising it is a spec change. +- **The audit is mandatory.** + - A live change without an audit sink is refused (501), with nothing sent. + - Every live attempt, including a skip, gets one row. + - Dry runs are not audited: they send nothing. +- **Legacy routes are unchanged without `serial`.** + - The only permitted change: `baud` becomes `Optional[int] = Query(None)` with 38400 applied at the top of the legacy path. +- **Schema.** The `device_commands` table is additive (`CREATE TABLE IF NOT EXISTS`). At merge, the changelog must say "schema: new table, no migration, no backfill". +- **Tiers.** `sfm/device_access/` must not import `sfm.database`, `sfm.waveform_store` or `sfm.server`. +- **The suite.** Its 16 pre-existing failures stay exactly that set. +- **Branch.** Work on `feat/series4-sfm-parity`. Never commit to `main` or `dev`, do not edit `CHANGELOG.md`, and run `git push` after each commit. +- **Never move or modify `bridges/captures/`.** Port 8200 is another SFM. +- **Trailers.** Every commit message ends with: + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 + ``` + +## Review Focus + +These are the five things most likely to bite, each with the task that tests it: + +1. **A lost ack.** It must never cause a second send, whether through the held-line retry, the Series-3 cold-boot retry, or anything else (Tasks 4, 5). +2. **A different unit at the address**, for example after a modem moved. It must be refused before any write, on a fresh serial read rather than the call-up's cached serial (Tasks 4, 5). +3. **A unit that is calling home** (`0x49` = `0x03`). It is refused, with nothing sent (Task 4). +4. **A clean ack where the state never changes.** This also covers a sensor check that delays the change. It is reported as a failed change after the verify window, audited as `mismatch`, with every state value seen recorded (Tasks 4, 5). +5. **Write permission leaking.** + - After `execute()`, the same connection cannot send `0x96` again without another `execute()`. + - A plan holding `0x7E` (call-home) is refused by the ceiling. + - A connection that has seen no Micromate-flagged reply cannot execute anything (Task 1). + +--- + +## File map + +| file | change | +|---|---| +| `micromate/opcodes.py` | `ENABLEABLE_WRITES` | +| `micromate/protocol.py` | `execute(plan)`; `_send(frame, *, permit=)`; `_validate` records `last_flags` | +| `micromate/models.py` | `MicromateRunState` | +| `micromate/client.py` | `serial(refresh=)`; `read_run_state()` | +| `sfm/database.py` | `device_commands` table; `begin_device_command`, `finish_device_command`, `query_device_commands` | +| `sfm/audit.py` | **new**: `DbAudit`, the SDM sink | +| `sfm/device_access/models.py` | `ChangeResult` | +| `sfm/device_access/s4.py` | `s4_change_monitoring` | +| `sfm/device_access/s3.py` | `Series3Adapter.change_monitoring`; `_run(retry=)` | +| `sfm/device_access/access.py` | `start_monitoring`/`stop_monitoring`; `_dispatch(change=)`; `audit=`, `sleep=`, `verify_*` | +| `sfm/server.py` | serial branch on `/device/monitor/start` and `/stop`; guard paths; `GET /db/device_commands`; audit wiring | +| `tests/device_access_fakes.py` | run states, `execute`, Series-3 start/stop | +| tests | `test_micromate_execute.py`, `test_device_commands.py`, `test_device_access_change.py`, plus additions to `test_micromate_client.py` and `test_server_device_access.py` | + +--- + +### Task 1: `execute(plan)`, the ceiling and the flags check + +**Files:** +- Modify: `micromate/opcodes.py` +- Modify: `micromate/protocol.py` (`__init__`, `_validate`, `_send`, new `execute`, module docstring) +- Test: `tests/test_micromate_execute.py` (new) + +**Interfaces:** +- Produces: + - `ENABLEABLE_WRITES: frozenset` + - `MicromateProtocol.execute(plan: WritePlan) -> list[MicromateFrame]`, returning the ack frames + - `MicromateProtocol.last_flags: Optional[int]` + +- [ ] **Step 1: Write the failing tests.** Create `tests/test_micromate_execute.py`: + +```python +"""execute(plan): the only write path -- exact frames, one call's permission, a ceiling.""" +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 micromate.framing import FLAGS_THOR, build_request # noqa: E402 +from micromate.opcodes import ENABLEABLE_WRITES, OpcodeRefused # noqa: E402 +from micromate.protocol import ACK_DATA_LEN, UnexpectedResponse # noqa: E402 +from micromate.writes import ( # noqa: E402 + plan_call_home_enabled, plan_start_monitoring, plan_stop_monitoring, +) +from test_micromate_protocol import frame, proto # noqa: E402 + +ACK_START = frame(0x69, bytes(ACK_DATA_LEN)) +POLL_RSP = frame(0xA4, bytes(48)) + + +def _ready(responses): + """A protocol that has already seen one Micromate-flagged reply (a POLL).""" + p, t = proto([POLL_RSP] + responses) + p.poll() + t.written.clear() + return p, t + + +def test_the_ceiling_is_start_and_stop_only(): + assert ENABLEABLE_WRITES == frozenset({0x96, 0x97}) + + +def test_execute_sends_exactly_the_plans_frame_and_returns_the_ack(): + p, t = _ready([ACK_START]) + acks = p.execute(plan_start_monitoring()) + assert t.written == [build_request(0x96, 0xFFFF)] + assert [a.sub for a in acks] == [0x69] + + +def test_permission_ends_with_the_call(): + p, t = _ready([ACK_START]) + p.execute(plan_start_monitoring()) + with pytest.raises(OpcodeRefused): + p._send(build_request(0x96, 0xFFFF)) + assert len(t.written) == 1 + + +def test_a_plan_beyond_the_ceiling_is_refused_and_nothing_is_sent(): + content = bytes(5) + b"\x05" + bytes(120) + p, t = _ready([]) + with pytest.raises(OpcodeRefused, match="ceiling"): + p.execute(plan_call_home_enabled(content, False)) + assert t.written == [] + + +def test_execute_refuses_before_any_micromate_reply_has_been_seen(): + p, t = proto([ACK_START]) + with pytest.raises(OpcodeRefused, match="Micromate"): + p.execute(plan_start_monitoring()) + assert t.written == [] + + +def test_execute_refuses_after_a_non_micromate_flags_reply(): + p, t = proto([frame(0xA4, bytes(48), flags=0x10), ACK_START], strict_checksums=False) + p.poll() + t.written.clear() + with pytest.raises(OpcodeRefused): + p.execute(plan_stop_monitoring()) + assert t.written == [] + + +def test_a_wrong_ack_sub_raises_after_one_send(): + p, t = _ready([frame(0x68, bytes(ACK_DATA_LEN))]) # stop's ack, for a start + with pytest.raises(UnexpectedResponse): + p.execute(plan_start_monitoring()) + assert len(t.written) == 1 + + +def test_thor_flags_are_accepted_too(): + p, t = proto([frame(0xA4, bytes(48), flags=FLAGS_THOR), frame(0x68, bytes(ACK_DATA_LEN))]) + p.poll() + p.execute(plan_stop_monitoring()) + assert t.written[-1] == build_request(0x97, 0xFFFF) +``` + + Before you write any code, make two checks: + - In `tests/test_micromate_protocol.py`, check that `ScriptedTransport` exposes `.written` as a list you can `.clear()`, and that `frame(..., flags=)` exists. + - Check that `micromate.framing` exports `FLAGS_THOR` and `FLAGS_BLASTWARE`. + + If either differs, adapt the helper calls only, and say so. + +- [ ] **Step 2: Run the tests and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_micromate_execute.py -q` + Expected: an ImportError on `ENABLEABLE_WRITES`. + +- [ ] **Step 3: Implement.** + + In `micromate/opcodes.py`, add after the tables: + +```python +# 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}) +``` + + In `micromate/protocol.py`: + - Imports: add `FLAGS_BLASTWARE` and `FLAGS_THOR` to the `from .framing import ...` line. Add `ENABLEABLE_WRITES` and `OpcodeRefused` to the `.opcodes` import. + - In `__init__`, add `self.last_flags: Optional[int] = None`. + - In `_validate`, before `return frame`, add `self.last_flags = frame.flags`. + - Replace `_send` with: + +```python + 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 by execute(), for exactly one step. + frame = bytes(frame) + check_transmit(request_sub(frame), self._allowed_writes | permit) + log.debug("TX %d bytes: %s", len(frame), frame.hex()) + self._transport.write(frame) +``` + + - Add after `_exchange`: + +```python + def execute(self, plan) -> list: + """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. + """ + beyond = plan.subs - 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: + self._parser.reset() + self._pending.clear() + self._send(step.frame, permit=frozenset({step.sub})) + acks.append(self._recv_one(expected_sub=step.ack_sub, reset_parser=False)) + return acks +``` + + - Module docstring: in the scope paragraph, add one sentence. `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. + +- [ ] **Step 4: Run the tests and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_micromate_execute.py tests/test_micromate_opcodes.py tests/test_micromate_protocol.py -q` + Expected: all pass. + +- [ ] **Step 5: Full suite, then commit and push.** + Message: `feat(micromate): execute(plan) -- the only write path, one call's permission, a start/stop ceiling`. + +--- + +### Task 2: The unit's run state and a fresh serial + +**Files:** +- Modify: `micromate/models.py`, `micromate/client.py` +- Test: `tests/test_micromate_client.py` (append) + +**Interfaces:** +- Produces: + - `MicromateRunState(code: int, name: str)`, where `name` is one of `"idle"` / `"monitoring"` / `"calling_home"` / `"unknown(0xNN)"`. + - `MicromateClient.read_run_state() -> MicromateRunState` + - `MicromateClient.serial(*, refresh: bool = False) -> str` + +- [ ] **Step 1: Write the failing tests.** Append to `tests/test_micromate_client.py`: + +```python +# ── run state (0x49) and a fresh serial ─────────────────────────────────────── + +import json as _json # noqa: E402 + +_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes" + + +def _captured_0x49(): + ex = _json.loads((_WRITES / "monitor-start-stop.json").read_text())["exchanges"] + return [bytes.fromhex(e["response_data"]) for e in ex if e["sub"] == 0x49] + + +def test_run_state_names_thors_captured_states(): + datas = _captured_0x49() + names = [] + for d in datas: + mm, _t = client([frame(0xB6, d)]) + names.append(mm.read_run_state().name) + assert "idle" in names and "monitoring" in names + + +@pytest.mark.parametrize("code,name", [(0x00, "idle"), (0x02, "monitoring"), + (0x03, "calling_home"), (0x07, "unknown(0x07)")]) +def test_run_state_names_every_value(code, name): + data = bytes(11) + bytes([code]) + bytes(4) + mm, _t = client([frame(0xB6, data)]) + st = mm.read_run_state() + assert (st.code, st.name) == (code, name) + + +def test_serial_refresh_reads_the_unit_again(): + mm, t = client([frame(0xEA, bytes(11) + b"UM20147\x00\x00\x00")]) + mm._serial = "UM99999" # a stale cached serial + assert mm.serial(refresh=True) == "UM20147" + assert len(t.written) == 1 +``` + + Before running, check two things: + - `client()` and `frame()` exist in this file with those shapes. If they differ, adapt the calls. + - The response SUBs: `0x49` gives `0xFF-0x49 = 0xB6`, and `0x15` gives `0xEA`. + +- [ ] **Step 2: Run the tests and watch them fail.** + Run: `.venv/bin/python -m pytest tests/test_micromate_client.py -q -k "run_state or refresh"` + Expected: `AttributeError: ... 'read_run_state'`. + +- [ ] **Step 3: Implement.** + + In `micromate/models.py`, add: + +```python +@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 +``` + + In `micromate/client.py`: + - Import `MicromateRunState`. + - Change `serial` to `def serial(self, *, refresh: bool = False) -> str:`, with the condition `if refresh or self._serial is None:`. Document that a change operation refreshes it right before writing. + - Add after `serial`: + +```python + _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})")) +``` + +- [ ] **Step 4: Run the tests and watch them pass.** Then run the full suite, commit and push. + Message: `feat(micromate): read the unit's run state and refresh its serial on demand`. + +--- + +### Task 3: The audit table and its sink + +**Files:** +- Modify: `sfm/database.py`. Add to `_SCHEMA`, plus three methods. +- Create: `sfm/audit.py` +- Modify: `sfm/server.py`, for `GET /db/device_commands` +- Test: `tests/test_device_commands.py` (new) + +**Interfaces:** +- Produces: + - `SeismoDb.begin_device_command(*, serial, series, address, action, tier, request: dict, caller: str) -> str` + - `SeismoDb.finish_device_command(command_id, *, outcome, verified, ack: Optional[dict], error: Optional[str]) -> None` + - `SeismoDb.query_device_commands(serial=None, limit=100) -> list[dict]`, newest first, with `request` and `ack` parsed back from JSON. + - `DbAudit(get_db: Callable[[], SeismoDb])` with `begin(**fields) -> str` and `finish(command_id, **fields)`. + +- [ ] **Step 1: Write the failing tests** in `tests/test_device_commands.py`: + +```python +"""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") +``` + +- [ ] **Step 2: Run them, and watch them fail** (ImportError). + +- [ ] **Step 3: Implement.** + - Append to `_SCHEMA` in `sfm/database.py`: + +```sql +CREATE TABLE IF NOT EXISTS device_commands ( + id TEXT PRIMARY KEY, + ts TEXT NOT NULL, -- when the attempt began (UTC ISO) + 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" | ... +); +CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts); +``` + + - Add the methods to `SeismoDb`. Use the existing `_new_id()` and `_connect()`, `json.dumps`/`json.loads` for `request`/`ack`, and a UTC ISO string for `ts`/`finished_ts`. + - `query_device_commands` orders by `ts DESC`. + - Create `sfm/audit.py`: + +```python +"""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) +``` + + - Add `GET /db/device_commands`, with params `serial: Optional[str] = Query(None)` and `limit: int = Query(100)`. It returns `{"commands": _get_db().query_device_commands(serial, limit)}`. Put it near the other `/db/*` reads. + +- [ ] **Step 4: Run the tests and watch them pass.** Then run the full suite, commit and push. + Message: `feat(sfm): device_commands audit table -- one row per change attempt`. + +--- + +### Task 4: The Series-4 change operation and `DeviceAccess.start_monitoring` / `stop_monitoring` + +**Files:** +- Modify: `sfm/device_access/models.py` (add `ChangeResult`), `sfm/device_access/s4.py` (add `s4_change_monitoring`), `sfm/device_access/access.py`, `sfm/device_access/__init__.py` +- Modify: `tests/device_access_fakes.py` +- Test: `tests/test_device_access_change.py` (new) + +**Interfaces:** +- Consumes: Task 1 (`execute`), Task 2 (`read_run_state`, `serial(refresh=)`), and the phase-2 `plan_start_monitoring`/`plan_stop_monitoring`. +- Produces: + - `ChangeResult`, with the fields shown below. + - `DeviceAccess(..., audit=None, sleep=time.sleep, verify_timeout_s=60.0, verify_interval_s=2.0)` + - `DeviceAccess.start_monitoring(address, serial, *, dry_run=False, even_if_already=False, caller="api") -> ChangeResult`, and the same for `stop_monitoring`. + +- [ ] **Step 1: Extend the fakes.** In `tests/device_access_fakes.py`, give `FakeMicromateClient` these keyword arguments: + - `run_states=None`, a list of codes consumed one per `read_run_state()` call, with the last one repeating; it defaults to `[0x00]`; + - `serial_reported=None`, defaulting to `serial`; + - `execute_error=None`. + + Then add these methods: + +```python + def serial(self, *, refresh=False): + self._step("serial") + return self.serial_reported + + 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})")) +``` + + On `_FakeProtocol`, add: + +```python + 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] +``` + + Also add `self.executed = []` to `FakeMicromateClient.__init__`. + +- [ ] **Step 2: Write the failing tests** in `tests/test_device_access_change.py`: + +```python +"""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 device_access_fakes import FakeMicromateClient # noqa: E402 +from sfm.device_access.access import DeviceAccess # noqa: E402 +from sfm.device_access.errors import ( # noqa: E402 + CallHomeInProgress, NotSupported, 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 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 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"][-1] == "monitoring" + + +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]) + with pytest.raises(CallHomeInProgress): + access(fake).stop_monitoring(ADDR, "UM20147") + assert fake.executed == [] + + +def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing(): + fake = FakeMicromateClient(serial_reported="UM12947") + with pytest.raises(WrongUnit): + access(fake).start_monitoring(ADDR, "UM20147") + assert fake.executed == [] + + +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 == [] + + +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" + + +def test_a_lost_ack_is_never_retried(): + 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 +``` + + Before running, check `FakeMicromateClient.status`'s call sequence, so the `fail` queue in the last test hits the first call of the change. Adapt the queue position if needed, and say so in the report. + +- [ ] **Step 3: Run the tests and watch them fail** (AttributeError: `start_monitoring`). + +- [ ] **Step 4: Implement.** + + `sfm/device_access/models.py`, append: + +```python +@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) +``` + + `sfm/device_access/s4.py`, add: + - imports: `from micromate.writes import plan_start_monitoring, plan_stop_monitoring`, plus `ChangeResult`, `CallHomeInProgress`, `NotSupported` and `WrongUnit` where not already imported; + - the function below. It is a plain function; `DeviceAccess` calls it inside `session.run`. + +```python +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: + """Identity -> state -> (dry run | skip | audit -> send -> read back -> audit).""" + action = "start monitoring" if start else "stop monitoring" + want = "monitoring" if start else "idle" + + reported = normalise_serial(client.serial(refresh=True)) + if reported != serial: + raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- " + "nothing sent") + before = client.read_run_state() + if before.name == "calling_home": + raise CallHomeInProgress(_RING_MESSAGE) + plan = plan_start_monitoring() if start else plan_stop_monitoring() + base = dict(serial=serial, series=4, action=action, plan=plan.describe(), + state_before=before.name) + + 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": plan.describe(), "even_if_already": even_if_already} + cid = audit.begin(serial=serial, series=4, address=address.key, action=action, + tier="change", request=request, caller=caller) + if before.name == want and not even_if_already: + audit.finish(cid, outcome="skipped", verified="not_checked", ack=None, + error=f"already {want}") + return ChangeResult(dry_run=False, sent=False, outcome="skipped", + verified="not_checked", state_after=before.name, + audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base) + + try: + acks = client.protocol.execute(plan) + except Exception as exc: # noqa: BLE001 -- recorded, never retried + after = _try_run_state(client) + audit.finish(cid, outcome="failed", verified="not_checked", ack=None, + error=f"no clean ack: {exc}") + if after is None: + raise # the line is suspect: let _exchange hang up + 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) + + ack = {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]} + seen = [before.name] + polls = int(verify_timeout_s // verify_interval_s) + for _ in range(polls): + sleep(verify_interval_s) + seen.append(client.read_run_state().name) + if seen[-1] == want: + break + ok = seen[-1] == want + audit.finish(cid, outcome="sent" if ok else "failed", verified="ok" if ok else "mismatch", + ack=ack, error=None if ok else f"unit reads {seen[-1]}, expected {want}") + return ChangeResult(dry_run=False, sent=True, outcome="sent" if ok else "failed", + verified="ok" if ok else "mismatch", state_after=seen[-1], + audit_id=cid, detail={"states_seen": seen, "ack": ack}, **base) + + +def _try_run_state(client: Any) -> Optional[str]: + try: + return client.read_run_state().name + except Exception: # noqa: BLE001 + return None +``` + + Check the poll count against the test's expectation. With a 6 s window and a 2 s interval, the loop gives 3 reads after the first, so 4 in total. Keep the test and the code consistent. If you change one, say which in the report. + + In `sfm/device_access/access.py`: + - Constructor: add the keyword arguments `audit: Any = None`, `sleep: Callable[[float], None] = time.sleep`, `verify_timeout_s: float = 60.0` and `verify_interval_s: float = 2.0`, and store them, with `self._audit = audit`. + - Add `change: bool = False` to `_dispatch`. Make the Series-4 retry condition `if was_held and not change and isinstance(exc, (NoAnswer, ConnectFailed)):`, and update the comment: a change is never retried, by construction. + - Add the public methods: + +```python + 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): + kw = dict(start=start, dry_run=dry_run, even_if_already=even_if_already, + audit=self._audit, address=address, 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, **kw), + change=True) +``` + + `self._s3.change_monitoring` arrives in Task 5. Until then, add a stub on `Series3Adapter` that raises `NotSupported("Series 3 start/stop through DeviceAccess arrives in Task 5")`, so this task's tests run. + - Export `ChangeResult` from `__init__.py`. + +- [ ] **Step 5: Run the tests and watch them pass.** + Run: `.venv/bin/python -m pytest tests/test_device_access_change.py tests/test_device_access*.py -q` + Expected: all pass. + +- [ ] **Step 6: Full suite, then commit and push.** + Message: `feat(sfm): start/stop monitoring for Series 4 -- identity, state, dry run, audit, read-back, never retried`. + +--- + +### Task 5: The Series-3 change operation + +**Files:** +- Modify: `sfm/device_access/s3.py` +- Modify: `tests/device_access_fakes.py` +- Test: `tests/test_device_access_change.py` (append) + +**Interfaces:** +- Produces: + - `Series3Adapter.change_monitoring(address, serial, **kw) -> ChangeResult`, with the same keyword arguments as `s4_change_monitoring`. + - `Series3Adapter._run(address, fn, timeout=None, retry=True)` + +- [ ] **Step 1: Extend the fakes.** On `FakeMiniMateClient`: + - add the keyword arguments `monitor_states=None` (a list of bools consumed by `get_monitor_status()`, with the last one repeating; it defaults to `[monitoring]`) and `write_error=None`; + - add `self.writes = []`; + - add `start_monitoring()` and `stop_monitoring()`. Each `_step`s, appends its name to `writes`, and raises `write_error` if one is set; + - make `get_monitor_status()` consume `monitor_states`. + +- [ ] **Step 2: Write the failing tests** (append to `tests/test_device_access_change.py`): + +```python +# ── 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"): + 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=lambda s: None, 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 == [] + + +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"] + + +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_is_never_retried_even_over_tcp(): + 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" +``` + +- [ ] **Step 3: Run them and watch them fail** (the Task 4 stub raises NotSupported). + +- [ ] **Step 4: Implement.** In `sfm/device_access/s3.py`: + - `_run` gains `retry: bool = True`. In its `except NoAnswer:`, add `if not retry or not address.host: raise`. + - Replace the stub with `change_monitoring`. It follows `s4_change_monitoring` step for step: + 1. `info = client.connect()` and `self._check(info.serial, serial, address)`. This is the fresh identity read: `connect()` reads `0x15`. + 2. `before = "monitoring" if client.get_monitor_status().is_monitoring else "idle"`. + 3. The dry-run plan, built from `minimateplus.framing.build_bw_write_frame(SUB_START_MONITORING or SUB_STOP_MONITORING, b"")`. Take the SUB constants from `minimateplus.protocol`. Shape it as `{"action", "sends_nothing": True, "steps": [{"sub": "0x96", "what": ..., "offset": "0x0000", "data_len": 0, "expect_ack": "0x69", "frame": }]}`, the same shape as Series 4. + 4. The audit, skip, send (`client.start_monitoring()`/`stop_monitoring()`), read-back poll and audit-finish logic, identical in shape to Series 4. There is no `calling_home` state on Series 3. + 5. Call `self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False)`. + - Factor the shared poll/audit tail out of `s4_change_monitoring` into a helper in a new module, `sfm/device_access/change.py`, if that keeps both short. Do not duplicate 40 lines. + +- [ ] **Step 5: Run the tests and watch them pass**, then the full suite, then commit and push. + Message: `feat(sfm): start/stop monitoring for Series 3 through the same safety layer`. + +--- + +### Task 6: The endpoints + +**Files:** +- Modify: `sfm/server.py`. Change `device_monitor_start` and `device_monitor_stop`, add to `_SERIAL_AWARE_PATHS`, and build `_device_access_instance` with `audit=DbAudit(_get_db)`. +- Test: `tests/test_server_device_access.py` (append) + +**Interfaces:** +- Produces: `POST /device/monitor/start` and `POST /device/monitor/stop`. Each gains `serial`, `dry_run: bool = False`, `even_if_already: bool = False` and `caller: Optional[str] = None`, and returns the `ChangeResult` as JSON. The HTTP status: + +| case | status | +|---|---| +| dry_run, skipped, sent and verified ok | 200 | +| failed with `verified` "mismatch" | **409** | +| any other failed | **502** | +| a `DeviceError` | its own status | + +- [ ] **Step 1: Write the failing tests.** Append direct-call handler tests. Build each `DeviceAccess` with the fakes and an `Audit` recorder, and monkeypatch `srv._device_access_instance`. Cover: + - a dry run returns 200 with the frame; + - a live start that verifies returns 200; + - a mismatch returns 409 with the body still holding `states_seen`; + - a lost ack where the state read back fine returns 502; + - `/device/monitor/start` without `serial` runs the legacy code unchanged. Use the same "legacy untouchable" pattern as the existing events test: monkeypatch `_device_access` to raise, and monkeypatch `_build_client` to raise a sentinel. + - Add both paths to the guard test's "allowed" list. + +- [ ] **Step 2: Run them and watch them fail.** + +- [ ] **Step 3: Implement.** + - **`baud` parameter:** `baud` becomes `Optional[int] = Query(None)` on both routes. + - **New parameters:** append `serial: Optional[str] = Query(None, description=_SERIAL_DOC)`, `dry_run: bool = Query(False)`, `even_if_already: bool = Query(False)` and `caller: Optional[str] = Query(None)`. + - **Docstring:** add a paragraph. With `serial`: identity check, state first, dry run, audit, read-back, never retried. The response is the ChangeResult. Without `serial`: the legacy behaviour below. + - **Serial branch:** put it first in each route, then `baud = 38400 if baud is None else baud` before the legacy code. + +```python + 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")) +``` + + - **The helper:** + +```python +def _change_response(fn) -> JSONResponse: + try: + result = fn() + except DeviceError as exc: + raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc + status = 200 + if result.outcome == "failed": + status = 409 if result.verified == "mismatch" else 502 + return JSONResponse(status_code=status, content=dataclasses.asdict(result)) +``` + + - **Wiring:** `_device_access_instance = DeviceAccess(audit=DbAudit(_get_db))`. Import `DbAudit` from `sfm.audit`. + - **Guard:** add `"/device/monitor/start"` and `"/device/monitor/stop"` to `_SERIAL_AWARE_PATHS`. + +- [ ] **Step 4: Run the tests, watch them pass, then the full suite, commit and push.** + Message: `feat(sfm): start/stop monitoring by serial -- dry run, audit, read-back`. + +--- + +### Task 7: The first live send, at the bench (controller and Brian, not a subagent) + +**Run only with Brian present and saying go.** UM20147 is on `/dev/ttyACM0` (`sg dialout`). SFM runs on port 8299 with a scratch database, through the phase-1b launcher pattern (patch `_DEFAULT_DB_PATH`, write a PID file, start and stop in one command). Log `micromate.protocol` at DEBUG, so every TX/RX frame is recorded. + +1. **Dry run, both actions:** + - `POST /device/monitor/start?serial=UM20147&port=/dev/ttyACM0&dry_run=true` + - the same for `/stop` + + Show Brian the state and the exact frame. It must be `41021010009600ffff00000000000000000000a403` for start, byte-identical to THOR's. +2. **Brian says go:** a live `POST /device/monitor/start`. Record: + - the HTTP status and body; + - the debug TX/RX lines; + - `states_seen`, including any sensor-check interval; + - the `device_commands` row. + + Confirm on the unit's screen that it is monitoring. +3. **Brian says go:** a live `POST /device/monitor/stop`. Record the same, and confirm on the screen. +4. **Optional, if Brian wants to settle the open question:** + - Stop again with `even_if_already=true` while idle. This records the ack of a "stop while stopped" (spec: open bench question). + - The plain stop-while-idle path is a skip and sends nothing. +5. **Record the results:** + - **`docs/micromate_protocol_reference.md`:** a dated, graded entry with the frames, acks, states and timings. It answers "does `0x49` reflect the change immediately", and records the sensor-check delay if any. + - **`CLAUDE.md`:** retract, in place, "No command has ever been originated against a unit by this project". Add: the first commands were `0x96`/`0x97` to UM20147 on , sent by SFM at the bench with Brian's approval. + - **Trilium:** a dev-log entry. + +## Self-review notes + +- **Spec coverage.** Build phases item 3 and its six preconditions: + - per-call permission: Task 1; + - ceiling: Task 1; + - never retry: Tasks 4 and 5; + - plan built inside the lock right before sending, with no stored dry-run plan ever sent: Task 4, where the plan is built inside the dispatched operation; + - read state first: Tasks 4 and 5; + - Micromate flags: Task 1. + + The safety layer's identity check, audit table and read-back are Tasks 3–5. The dry run is Tasks 4–6. The bench protocol is Task 7. +- **Not in phase 3:** call-home writes (phase 4), setup push (phase 5), the dry-run digest echo (optional in the spec, deferred), Series-3 held sessions, and the blind-stop-tool decision (Brian). +- **The verify window.** It is 60 s by default. Series 3's sensor check took about 40 s (4-8-26). Series 4's is unmeasured, and Task 7 measures it. diff --git a/docs/superpowers/plans/2026-10-28-sfm-phase1c-webapp.md b/docs/superpowers/plans/2026-10-28-sfm-phase1c-webapp.md new file mode 100644 index 0000000..094d15e --- /dev/null +++ b/docs/superpowers/plans/2026-10-28-sfm-phase1c-webapp.md @@ -0,0 +1,207 @@ +# 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 ` + +