Compare commits
102
Commits
d0c14aaec8
...
v0.34.0
No files matched your search
+465
-1
@@ -4,9 +4,125 @@ All notable changes to seismo-relay are documented here.
|
||||
|
||||
---
|
||||
|
||||
## Unreleased
|
||||
## 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
|
||||
@@ -34,6 +150,354 @@ All notable changes to seismo-relay are documented here.
|
||||
- ⚠ **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/<ch>` 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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -228,14 +292,44 @@ Read this first when picking the project back up.
|
||||
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` with
|
||||
the unit's mic overlaid, its peaks/vector sum too unless Normal range is confirmed
|
||||
-- since 2026-10-31, after the checker's histogram-PVS fix -- and its range passed). #2 came with the
|
||||
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.
|
||||
@@ -400,8 +494,9 @@ Read this first when picking the project back up.
|
||||
take: Blastware downloading BE9441 event 2 (`0111c92c`) or 19 (`0118a4ca`)
|
||||
through the recording bridge. Blastware's own files for both are fixtures
|
||||
(`tests/fixtures/minimate-bench-10-25-26/blastware/`), as byte-exact targets.
|
||||
- **Open, not blocking:** 14 sensitive-range files show an exact 8x
|
||||
(= 10.0/1.25) units discrepancy; `scripts/backfill_sidecars.py --force` also
|
||||
- **Open, not blocking:** ~~14 sensitive-range files show an exact 8x
|
||||
(= 10.0/1.25) units discrepancy~~ (**resolved on `dev` 2026-11-02:** the
|
||||
range is read from the file, reference D.6.4); `scripts/backfill_sidecars.py --force` also
|
||||
inserts DB rows for store files that have none (one-time per store) and the
|
||||
dry-run does not report that count.
|
||||
- **After any codec change, regenerate the store** — `backfill_sidecars.py`
|
||||
@@ -630,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)
|
||||
@@ -811,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`)
|
||||
@@ -818,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
|
||||
@@ -845,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
|
||||
@@ -853,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
|
||||
@@ -1554,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 |
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
@@ -636,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).
|
||||
|
||||
@@ -11,6 +11,14 @@
|
||||
|
||||
| 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. |
|
||||
@@ -20,7 +28,7 @@
|
||||
| 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. |
|
||||
@@ -2677,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
|
||||
@@ -3179,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 |
|
||||
|
||||
@@ -3406,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.
|
||||
|
||||
@@ -3436,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.
|
||||
@@ -3585,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) |
|
||||
@@ -3603,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.*
|
||||
|
||||
@@ -1925,6 +1925,15 @@ at `payload[3:5]`:
|
||||
| 2nd | `0x0002` | 535 B | the file body |
|
||||
| 3rd | `0x0000` | 11 B | all zeros = **end of file** |
|
||||
|
||||
✅ **SFM reads the schedule this way, read-only (2026-11-03, phase 5)** --
|
||||
`MicromateProtocol.read_file` / `MicromateClient.read_schedule`, frames equal to
|
||||
THOR's byte for byte (`tests/test_micromate_schedule.py`). Two details the table
|
||||
above leaves out: the `0x94` request carries **`params[3] = 1`**, and the **first**
|
||||
`0x48` carries **`params[7] = 1`** (the later ones all-zero params); both `0x48`
|
||||
offsets are `0xFFFF`. A long file is **written** in 1,024-byte `0x8E` pieces
|
||||
(the five-entry *actioncheck* schedule went as 1,024 + 280). ⚠ Unmeasured: what
|
||||
`0x94` / `0x48` return for a unit with no schedule file.
|
||||
|
||||
⚠ This is the single most consequential find of the session, because it is not
|
||||
specific to the scheduler. **`callhome.MMB` is a file too**, and the call-home
|
||||
config is the last unsolved piece of the project. Reading it should be a
|
||||
@@ -2693,10 +2702,82 @@ noted, which is cheap to collect during any future ACH capture.
|
||||
Neighbouring bytes: `write[117]` is `0x03`, lining up with Series III's
|
||||
`num_retries` of 3, and `write[120:122]` is `00 3c` = 60.
|
||||
|
||||
#### Bench 2026-11-03: SFM's own call-home writes to UM20147
|
||||
|
||||
SFM's audited `POST /device/call_home/{enable,disable}`, one send per go.
|
||||
Audit records are in the bench DB.
|
||||
|
||||
**Measured, idle:**
|
||||
- UM20147 reads `content[5] = 0x01` for on. It **accepts `0x00` for off**, a
|
||||
value THOR was never seen writing. The read-back reads off, and the unit's own
|
||||
menu said "Auto Call Home: Disabled"; on again, "Enabled".
|
||||
- **A no-op write is acked** (`0x81`, `0x80`), and `[118:120]` does **not** move:
|
||||
`8fab` → `8fab`.
|
||||
- **Flipping bit 0 of `[5]` moves `[118:120]` by XOR `0x6D7D`, both directions:**
|
||||
`8fab` ↔ `e2d6`. That is the same XOR as UM12947's `0x04` ↔ `0x05` above, on
|
||||
a different unit with a different block. Writing the original block back
|
||||
restores the original value (`8fab`).
|
||||
|
||||
This **settles the open question above (hash vs nonce): it is not a per-write
|
||||
nonce.** The field is a function of the block's content, and the fixed delta
|
||||
for a fixed bit flip is the signature of a linear checksum (CRC family) over a
|
||||
region that includes `[5]`. The fixed-delta part is *inferred*. A desk lead:
|
||||
solve the polynomial from the deltas; the earlier sweep's regions or variants
|
||||
were wrong.
|
||||
|
||||
**Measured, monitoring:**
|
||||
- The unit returns its **real** call-home block (`00 7C DC`…).
|
||||
- It **acks** a `0x7E`/`0x7F` write but **does not apply it**: three read-backs
|
||||
over 3 s were unchanged, and `[118:120]` did not move. After the stop,
|
||||
call-home still read on, so the write was **ignored, not staged**.
|
||||
- Its own menu refuses the call-home screen while monitoring: **"Feature
|
||||
disabled while monitoring"**.
|
||||
- SFM therefore refuses a call-home change while monitoring (`f35845d`).
|
||||
|
||||
**Measured, also:**
|
||||
- A stop with call-home on started a call-in **after** the stop's ack. SFM hung
|
||||
up within about 1 s, and the call **reached THOR**: the session's histogram
|
||||
arrived. (2026-10-29 Run A lost the call: there the ring replaced the ack.)
|
||||
- UM20147's clock read one hour ahead after daylight saving ended (16:09:25 at
|
||||
15:09:22 EST).
|
||||
|
||||
⚠ Beyond the enable byte and the dial string, **the field map is not
|
||||
established** — only one setting was varied. Series III's offsets are a starting
|
||||
hypothesis, not a transfer.
|
||||
|
||||
#### Bench 2026-11-04: SFM's first setup push (UM20147)
|
||||
|
||||
SFM's audited `POST /device/settings/change`, one send per go (Brian at the
|
||||
unit). Notes: `~/bench-logs/2026-11-04-sfm-settings/`.
|
||||
|
||||
**Measured:**
|
||||
- **The setup push works as THOR's.** Trigger 0.6 → 0.5, then a five-field
|
||||
change (Location, Client, job number + its report flag, record time), then a
|
||||
full restore. Each send was THOR's seven frames, acknowledged in THOR's order
|
||||
(`25 97 8C 7D 7C 8E 8D`), read back as sent, and confirmed in the unit's menu.
|
||||
The setup block ended byte for byte as found, CRC included.
|
||||
- **The unit's recomputed CRC equals SFM's** (`with_crc`): after the first push
|
||||
the stored block equalled SFM's computed image byte for byte, CRC `ea8d`
|
||||
included.
|
||||
- **`schedule.dat` read on a real unit** (`0x94` → `0x6B`; `0x48` → descriptor
|
||||
`04 00 … 01 … 01`, body, all-zero end). UM20147 holds a leftover THOR
|
||||
schedule: repeat on, 07:00, start monitoring with
|
||||
`Fay - Commercial Street - Irish Center.mmb`. The unit runs `test2.MMB`, so
|
||||
SFM blocked the change, as designed.
|
||||
- 🔑 **The scheduler On/Off switch is in none of the blocks SFM reads.** With
|
||||
the keypad switch Off, then On (saved), these were byte for byte identical:
|
||||
`0x08` prefs, `0x2E`, `0x1A`, `0x2C`, `0x41` and `schedule.dat`. The
|
||||
firmware's `SysPref.bMonitorScheduler` lives elsewhere. THOR's end-of-push
|
||||
`0x47` pair (`params[7]` 1 then 3; replies `04 00 … 0N … 00 01`) was only
|
||||
ever captured with the switch On. **Next:** a THOR bridge recording with the
|
||||
switch Off (parked for the work-hours project).
|
||||
- **While monitoring**, a settings preview and a live attempt were both refused
|
||||
on the run state before any block was read (409, nothing sent, 0 write frames).
|
||||
- **With call-home off, a stop goes straight to idle** (`monitoring` →
|
||||
`idle`): no calling-home state and no ring.
|
||||
- Call-home `0x01` ↔ `0x00` was taken again, both ways. The plan's
|
||||
"unobserved" warning is retired for those values.
|
||||
|
||||
## What the THOR manual settles about the ACH session (2026-09-24)
|
||||
|
||||
Source: `manuals/723U0201 THOR Operator Manual Rev 08.pdf` §6.2, §3.6.
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
# Phase 4 — Call-home enable/disable Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Turn a unit's automatic call-home on or off from SFM, for both series, through the audited change path start/stop already uses: identity check → audit → one send → read back → audit.
|
||||
|
||||
**Architecture:** `run_change` (`sfm/device_access/change.py`) becomes kind-agnostic: a `ChangeKind` says what the change is called and which state means it took. Each series supplies a call-home state read (`"enabled"` / `"disabled"`, plus Series 4's `"calling_home"`) and a send built from the block it read moments before. Series 4 sends `micromate.writes.plan_call_home_enabled` (frames already equal to THOR's). Series 3 patches byte 5 of the unescaped `0x2C` image and sends it through the existing `0x7E`/`0x7F` path. A gate keeps that send refused until its frame is reproduced from a Blastware capture. New serial-keyed routes, and the page's Call Home tab by serial gets On/Off buttons.
|
||||
|
||||
**Tech Stack:** Python 3 / FastAPI (SFM), pytest; page JS in `sfm/static/` tested with Node.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` — row 9 of the job table, "The safety layer" (tiers, read-back: "call-home → re-read `0x2C` and compare the edited bytes"), the per-operation table (`call-home enable/disable | read 0x2C → 0x7E (126 B content, offset 0x007E) → 0x7F | re-read 0x2C`), build phase 4.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Branch `feat/series4-sfm-parity`, worktree `~/seismo-relay-parity`. Never commit to `main`. Push every commit. No `CHANGELOG.md` edits (written on `dev` at merge).
|
||||
- **No live write without Brian's explicit go, per send.** Dry runs and tests only, until the bench task.
|
||||
- A write is never retried (`DeviceAccess._dispatch(change=True)`); never send `0xA2`; never write modem baud or modem type.
|
||||
- File boundary with the decode-checker session: do not edit `minimateplus/event_file_io.py`, `histogram_codec.py`, `waveform_codec.py`, `bw_xml_report.py`, `decode_check*.py`.
|
||||
- No inline JavaScript: new page logic goes in `sfm/static/device_routing.js` (DOM-free, Node-tested); `sfm/static/sfm_webapp.js` only applies it (stack-wide rule, 2026-11-02).
|
||||
- Series 4: read-modify-write. Send back every byte of the block as read except bit 0 of `content[5]`. Never synthesise or zero `content[118:120]` (unit-maintained; it changes after a config write).
|
||||
- Series 3: read the enable byte from the **unescaped** block (the lesson of bench finding #1). `0x00` off, `0x01` on (measured April 2026, BE11529). Any other value is `unknown(0xNN)` and nothing is sent.
|
||||
- Speed is secondary to reliability: no new round trips beyond the reads the change needs.
|
||||
- Test command: `/home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider`. Baseline: exactly 16 known failures (15 in `tests/test_bw_ascii_report.py`, `tests/test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`). Read the failure list before committing.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. A change requested while a Micromate is calling home (run state `0x03`) → 503, nothing sent, the line released (the existing `CallHomeInProgress` path).
|
||||
2. A MiniMate whose unescaped byte 5 is neither `0x00` nor `0x01` → state `unknown(0xNN)`: a dry run still shows it, a live change sends nothing (`UnitStateUnknown`, 409).
|
||||
3. A read-back where other bytes changed (Series 4 `[118:120]` always does) → verified on the edited bit alone; the changed offsets are recorded in the result and the audit row, never a mismatch.
|
||||
4. Already in the requested state → skipped with no send, unless `even_if_already` (the bench's no-op write is exactly that experiment).
|
||||
5. A live Series-3 call-home change before its frame has been reproduced from a Blastware capture → 501 before any connection. A dry run works.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: `run_change` takes a `ChangeKind`
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/device_access/change.py` (signature and the three derived names at the top of `run_change`; the finish paths that build `detail` and `states`)
|
||||
- Modify: `sfm/device_access/s3.py` (`change_monitoring`), `sfm/device_access/s4.py` (`s4_change_monitoring`) — call sites only
|
||||
- Test: `tests/test_device_access_change_kind.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) class ChangeKind: action: str; want: str; became: str` in `change.py`.
|
||||
- `monitoring_change(start: bool) -> ChangeKind` gives exactly today's values: `("start monitoring", "monitoring", "started")` / `("stop monitoring", "idle", "stopped")`.
|
||||
- `call_home_change(enabled: bool) -> ChangeKind` gives `("enable call-home", "enabled", "enabled")` / `("disable call-home", "disabled", "disabled")`.
|
||||
- `run_change(*, kind: ChangeKind, serial, series, dry_run, even_if_already, audit, address, caller, sleep, verify_timeout_s, verify_interval_s, read_serial, read_state, describe_plan, send, is_refusal=_never, is_ring=_never, pre_send=None, snapshot: Optional[Callable[[], Dict[str, Any]]] = None) -> ChangeResult`. `start` is gone.
|
||||
- `snapshot`: called once, after the read-back loop, on the two normal finish paths (verified `ok` or `mismatch`). Its dict goes in `detail["snapshot"]` and the audit row's `states["snapshot"]`. A snapshot that raises is recorded as `{"error": str(exc)}` and does not change the outcome.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests** (fake callables, no device, the `Audit` fake pattern from `tests/test_device_access_change.py`):
|
||||
- `test_monitoring_kinds_are_todays_names`: `monitoring_change(True) == ChangeKind("start monitoring", "monitoring", "started")`, and likewise for stop.
|
||||
- `test_a_call_home_change_is_verified_by_its_own_state`: `kind=call_home_change(False)`, states `["enabled", "disabled"]` → `(outcome, verified, state_after) == ("sent", "ok", "disabled")`, and `result.action == "disable call-home"`.
|
||||
- `test_a_call_home_read_back_that_did_not_change_is_a_mismatch`: states `["enabled", "enabled", "enabled", "enabled"]` with verify `(3.0, 1.0)` → `("failed", "mismatch")`.
|
||||
- `test_the_snapshot_is_kept_in_the_result_and_the_audit`: `snapshot=lambda: {"after": "ab"}` → `result.detail["snapshot"] == {"after": "ab"}` and the audit row's `states["snapshot"] == {"after": "ab"}`.
|
||||
- `test_a_failing_snapshot_does_not_change_the_outcome`: a snapshot raising `RuntimeError("x")` → still `("sent", "ok")`, `detail["snapshot"] == {"error": "x"}`.
|
||||
- [ ] **Step 2: Run** `pytest tests/test_device_access_change_kind.py -v`. Expected: FAIL (`ImportError: cannot import name 'ChangeKind'`).
|
||||
- [ ] **Step 3: Implement.** Replace `start` with `kind` in `run_change`, deriving `action`, `want` and `became` from `kind`. Add the snapshot as specified. Update the two call sites to `kind=monitoring_change(start)`, keeping their own `start` parameter.
|
||||
- [ ] **Step 4: Run** the new file plus `tests/test_device_access_change.py tests/test_device_access_s3_events.py tests/test_server_device_access.py`. Expected: all pass, with the existing start/stop tests unchanged.
|
||||
- [ ] **Step 5: Commit** `refactor(sfm): run_change takes a ChangeKind -- start/stop unchanged, call-home next (phase 4)`.
|
||||
|
||||
### Task 2: Series 4 — read call-home, change it
|
||||
|
||||
**Files:**
|
||||
- Modify: `micromate/opcodes.py` (`ENABLEABLE_WRITES`), `micromate/client.py` (new method)
|
||||
- Modify: `sfm/device_access/models.py` (new `CallHomeState`), `sfm/device_access/s4.py` (two new functions)
|
||||
- Modify: `tests/device_access_fakes.py` (`FakeMicromateClient` call-home support), `tests/test_micromate_execute.py:37` (the ceiling assertion)
|
||||
- Test: `tests/test_device_access_s4_call_home.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1's `ChangeKind`, `call_home_change`, `run_change(snapshot=…)`.
|
||||
- Produces:
|
||||
- `ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F})`.
|
||||
- `MicromateClient.get_call_home_content() -> bytes`: the 126-byte content, `_content(self.protocol.read_call_home_config())`.
|
||||
- `@dataclass class CallHomeState: serial: str; series: int; enabled: Optional[bool]; dial_string: Optional[str]; detail: Dict[str, Any]` (`detail["byte5"]` as `"0xNN"`, `detail["block"]` as hex).
|
||||
- `s4_call_home_state(client, serial) -> CallHomeState`: enabled is bit 0 of `content[5]`; the dial string is `content[6:46]` up to its first NUL, decoded as ASCII.
|
||||
- `s4_change_call_home(client, serial, *, enabled, dry_run, even_if_already, audit, address, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`:
|
||||
- `read_state` returns `"calling_home"` when `client.read_run_state().name == "calling_home"`, else `"enabled"` / `"disabled"` from `content[5] & 1`. It keeps the last content it read.
|
||||
- `describe_plan`: `plan_call_home_enabled(last_content, enabled).describe()`, so the plan is built from the read `run_change` made just before.
|
||||
- `send` executes that same plan object.
|
||||
- `snapshot` returns `{"before": hex, "after": hex, "changed_offsets": [...]}`, comparing the first and last content read.
|
||||
- `pre_send`, `is_refusal` and `is_ring` are as in `s4_change_monitoring`.
|
||||
|
||||
- [ ] **Step 1: Fake support.**
|
||||
- `FakeMicromateClient(call_home=<126-byte content>)`, defaulting to UM12947's enabled read from `tests/fixtures/micromate-writes` (the reads `tests/test_micromate_writes.py::_call_home_reads` uses), plus a `read_call_home_config()` on `_FakeProtocol` returning `bytes(11) + content`.
|
||||
- `execute(plan)` applies a `0x7E` step's data as the new content, then replaces `[118:120]` with its bitwise complement, mimicking the unit-maintained field (the default read already holds `2e 5e`, so a fixed value would not change it).
|
||||
- [ ] **Step 2: Write the failing tests:**
|
||||
- `test_s4_call_home_state_reads_the_enable_bit_and_dial_string`: on the default content (UM12947, `[5] = 0x05`) → `enabled is True`, `dial_string == "RADIO RING"`, `detail["byte5"] == "0x05"`.
|
||||
- `test_s4_dry_run_shows_thors_frames`: dry run `enabled=False` → `result.plan` frames equal `plan_call_home_enabled(content, False).describe()["steps"]` frames, and `fake.executed == []`.
|
||||
- `test_s4_disable_sends_7e_7f_and_verifies`: live `enabled=False` → `("sent", "ok", "disabled")`; executed plan subs `[0x7E, 0x7F]`.
|
||||
- `test_s4_unit_maintained_bytes_do_not_make_a_mismatch`: same run → `verified == "ok"` and `detail["snapshot"]["changed_offsets"] == [5, 118, 119]`.
|
||||
- `test_s4_no_change_while_calling_home`: `run_states=[0x03]` → `CallHomeInProgress`, nothing executed.
|
||||
- `test_s4_already_enabled_is_skipped`: `enabled=True` on enabled content → `outcome == "skipped"`, nothing executed. With `even_if_already=True` → executed once, and the plan carries the "changes nothing" warning.
|
||||
- Update `test_micromate_execute.py:37` to the new four-SUB set.
|
||||
- [ ] **Step 3: Run** the new file. Expected: FAIL (`ImportError: s4_call_home_state`).
|
||||
- [ ] **Step 4: Implement** as specified in Interfaces.
|
||||
- [ ] **Step 5: Run** the new file plus `tests/test_micromate_execute.py tests/test_micromate_writes.py tests/test_device_access_change.py`. Expected: pass.
|
||||
- [ ] **Step 6: Commit** `feat(sfm): Series-4 call-home state and audited enable/disable (phase 4)`.
|
||||
|
||||
### Task 3: Series 3 — read call-home, change it (live send gated)
|
||||
|
||||
**Files:**
|
||||
- Modify: `minimateplus/protocol.py` (two pure functions next to `write_image`), `minimateplus/client.py` (two methods)
|
||||
- Modify: `sfm/device_access/s3.py` (gate constant + two adapter methods)
|
||||
- Modify: `tests/device_access_fakes.py` (`FakeMiniMateClient` call-home support)
|
||||
- Test: `tests/test_s3_call_home.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1, and Task 2's `CallHomeState`.
|
||||
- Produces:
|
||||
- `call_home_enabled(raw: bytes) -> Optional[bool]` in `minimateplus/protocol.py`: `unescape_reply(raw)[5]`, `0x01` → True, `0x00` → False, else None.
|
||||
- `call_home_image(raw: bytes, enabled: bool) -> bytes`: `write_image(SUB_CALL_HOME_WRITE, raw)` with byte 5 set to `0x01`/`0x00` and every other byte unchanged. Raises `ValueError` when the image's byte 5 is not `0x00`/`0x01`.
|
||||
- `MiniMateClient.read_call_home_raw() -> bytes` (the protocol's `read_call_home_config()`) and `MiniMateClient.write_call_home_image(image: bytes) -> None` (the protocol's `write_call_home_config(image)`: `0x7E` then `0x7F`, each ack checked).
|
||||
- `S3_CALL_HOME_FRAME_VERIFIED = False` in `sfm/device_access/s3.py`. Task 4 flips it.
|
||||
- `Series3Adapter.call_home_state(address, serial) -> CallHomeState`: `wake`, then `read_call_home_raw()`. The dial string is the unescaped `[6:46]` up to its first NUL. `detail` carries `byte5`, `block` (raw hex) and `serial_verified: False`, as status does.
|
||||
- `Series3Adapter.change_call_home(address, serial, *, enabled, dry_run, even_if_already, audit, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`:
|
||||
- When `not dry_run and not S3_CALL_HOME_FRAME_VERIFIED`, raise `NotSupported("a MiniMate call-home write waits until its frame has been reproduced from a Blastware capture -- nothing sent")` before `_run`.
|
||||
- Otherwise use `run_change(kind=call_home_change(enabled), retry=False)` with:
|
||||
- `read_serial` = `client.connect()`, as for start/stop;
|
||||
- `read_state` = `wake` + `read_call_home_raw()`, giving `enabled` / `disabled` / `unknown(0xNN)` and keeping the last raw;
|
||||
- `describe_plan` = the steps `[{"sub": "0x7E", "frame": build_bw_write_frame(0x7E, image).hex()}, {"sub": "0x7F", "frame": build_bw_write_frame(0x7F, b"").hex()}]`;
|
||||
- `send` = `client.write_call_home_image(image)`, returning `{"subs": ["0x81", "0x80"]}`;
|
||||
- `snapshot` as in Task 2, over unescaped images.
|
||||
|
||||
- [ ] **Step 1: Fake support.**
|
||||
- `FakeMiniMateClient(call_home_raw=<125 B>)`. The default is built from the documented 4-20-26 layout: `00 7C DC 00 00`, `[5] = 0x01`, `[6:46] = b"RADIO RING"` NUL-padded, `[117:119] = 10 03`, zeros elsewhere to 125 bytes.
|
||||
- `read_call_home_raw()` steps and returns it.
|
||||
- `write_call_home_image(image)` records `self.writes.append("call_home")` and stores the image for the next read.
|
||||
- [ ] **Step 2: Write the failing tests:**
|
||||
- `test_s3_enable_byte_reads_from_the_unescaped_block`: on the default raw → `call_home_enabled(raw) is True`. A raw with an escape spliced in before byte 5 (`00 7C 10 03 00 00 01 …`) still reads True.
|
||||
- `test_s3_image_changes_only_byte_5`: `call_home_image(raw, False)` differs from `write_image(0x7E, raw)` at index 5 only, and its length is 126 (N `0x7C` + 2).
|
||||
- `test_s3_image_refuses_an_unknown_byte_5`: raw with unescaped `[5] = 0x07` → `ValueError`.
|
||||
- `test_s3_call_home_state`: through `Series3Adapter` with the fake → `enabled is True`, `dial_string == "RADIO RING"`, `detail["serial_verified"] is False`; the calls include `"wake"` before `"read_call_home_raw"`.
|
||||
- `test_s3_live_change_is_refused_until_the_frame_is_verified`: `dry_run=False` → `NotSupported` (501), the factory never called.
|
||||
- `test_s3_dry_run_shows_both_frames`: `dry_run=True` → plan steps `0x7E`/`0x7F`, `fake.writes == []`.
|
||||
- `test_s3_change_once_verified` (monkeypatch `S3_CALL_HOME_FRAME_VERIFIED = True`): live `enabled=False` → `("sent", "ok", "disabled")`, `fake.writes == ["call_home"]`, `detail["snapshot"]["changed_offsets"] == [5]`.
|
||||
- `test_s3_unknown_byte_5_sends_nothing` (gate open): raw with `[5] = 0x07` → `UnitStateUnknown`, no write.
|
||||
- [ ] **Step 3: Run** the new file. Expected: FAIL (`ImportError: call_home_enabled`).
|
||||
- [ ] **Step 4: Implement** as specified.
|
||||
- [ ] **Step 5: Run** the new file plus `tests/test_device_access_change.py tests/test_server_series3_guard.py`. Expected: pass.
|
||||
- [ ] **Step 6: Commit** `feat(sfm): Series-3 call-home state and audited enable/disable, live send gated until its frame is verified (phase 4)`.
|
||||
|
||||
### Task 4: Reproduce Blastware's Series-3 call-home write (opens the gate)
|
||||
|
||||
**Precondition:** Brian has found a capture of Blastware changing call-home settings, from the BW VM (CLAUDE.md names it `4-20-26/call home settings/`, BE11529), and copied the BW-TX and S3-RX files into `tests/fixtures/s3-call-home-bw/`. **If no capture exists, skip this task.** The gate stays shut, the Series-3 half of the bench (Task 7) starts by recording one, and this task runs after it.
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/fixtures/s3-call-home-bw/` (Brian's files, added with `git add -f` if they match an ignore rule) and `tests/test_s3_call_home_bw_frames.py`
|
||||
- Modify: `sfm/device_access/s3.py` (`S3_CALL_HOME_FRAME_VERIFIED = True`, with a comment naming the test)
|
||||
|
||||
- [ ] **Step 1: Write the test** `test_sfm_builds_blastwares_call_home_write`:
|
||||
1. Parse the S3-RX file with `S3FrameParser`, taking each `0xD3` data reply (`data[11:]`) in order. Parse the BW-TX file for the `0x7E` and `0x7F` request frames, using the #46 parser in `tests/test_minimate_write_frames.py` (`_frames`, `_payload`; import or copy them).
|
||||
2. For each `0x7E`, work out what Blastware asked for: the unescaped byte 5 of its image.
|
||||
3. Assert `build_bw_write_frame(0x7E, call_home_image(prev_read, wanted)) == bw_7e_frame` and `build_bw_write_frame(0x7F, b"") == bw_7f_frame`.
|
||||
4. If Blastware also changed fields other than byte 5 in that write, assert only on writes where byte 5 is the sole difference from the read, and record the count.
|
||||
- [ ] **Step 2: Run it.** Expected: PASS, with at least one write asserted. A FAIL means SFM's frame is not Blastware's: stop, record the byte differences in the spec's phase-4 notes, and leave the gate shut.
|
||||
- [ ] **Step 3: Flip the gate**, then run `tests/test_s3_call_home.py`. The "refused until verified" test now fails by design: change it to assert the gate's comment names this test, and keep the monkeypatched tests.
|
||||
- [ ] **Step 4: Commit** `test(s3): SFM's call-home write equals Blastware's, frame for frame -- opens the live send`.
|
||||
|
||||
### Task 5: DeviceAccess and the serial routes
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/device_access/access.py` (two methods, two constants), `sfm/server.py` (three routes, `_SERIAL_AWARE_PATHS`)
|
||||
- Test: `tests/test_device_access_call_home.py`, plus additions to `tests/test_server_device_access.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Tasks 2 and 3.
|
||||
- Produces:
|
||||
- `DeviceAccess.call_home_state(address, serial) -> CallHomeState` (a read, via `_dispatch`).
|
||||
- `DeviceAccess.set_call_home(address, serial, *, enabled: bool, dry_run=False, even_if_already=False, caller="api") -> ChangeResult` (`change=True`). It uses `_CALL_HOME_VERIFY_TIMEOUT_S = 3.0` and `_CALL_HOME_VERIFY_INTERVAL_S = 1.0`, at most 3 read-backs one second apart, not the monitoring window.
|
||||
- Routes:
|
||||
- `GET /device/call_home/state?serial=&host=&tcp_port=` → the `CallHomeState` as a dict.
|
||||
- `POST /device/call_home/enable` and `/device/call_home/disable`, taking `serial` (required), `host`, `tcp_port`, `dry_run`, `even_if_already` and `caller`, through `_change_response`. The statuses are the start/stop route's, including Batch 2's `sent`/`audit_id` on an unconfirmed change.
|
||||
- All three go in `_SERIAL_AWARE_PATHS`. The legacy `GET`/`POST /device/call_home` stay unchanged, and outside that set.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
- `test_set_call_home_dispatches_by_series`: a `UM` serial reaches the S4 function and a `BE` serial the S3 adapter, using the fakes from Tasks 2 and 3.
|
||||
- `test_set_call_home_is_never_retried`: an S4 held line that drops → raised, executed once.
|
||||
- `test_call_home_routes_need_a_serial`: no `serial` → 422.
|
||||
- `test_enable_route_returns_the_change_result`: a fake access → 200 and the body's `action == "enable call-home"`.
|
||||
- `test_legacy_call_home_post_still_refuses_a_micromate_serial`: `_device_guard("/device/call_home", {"serial": "UM20147"})` → 501, unchanged.
|
||||
- `test_call_home_routes_are_serial_aware`: the three new paths are in `_SERIAL_AWARE_PATHS`.
|
||||
- [ ] **Step 2: Run.** Expected: FAIL (`AttributeError: set_call_home`).
|
||||
- [ ] **Step 3: Implement**, mirroring `start_monitoring` / `device_monitor_start`.
|
||||
- [ ] **Step 4: Run** the new and modified test files plus `tests/test_server_series3_guard.py`. Expected: pass.
|
||||
- [ ] **Step 5: Commit** `feat(sfm): call-home state and enable/disable by serial -- GET /device/call_home/state, POST /device/call_home/{enable,disable} (phase 4)`.
|
||||
|
||||
### Task 6: The page — Call Home by serial
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/static/device_routing.js` (routes, `controlsFor`, `serialPanes`, `changeErrorText`, new `callHomeRows`), `sfm/static/sfm_webapp.js` (glue), `sfm/sfm_webapp.html` (a state box and two buttons in the Call Home tab)
|
||||
- Test: `tests/test_webapp_device_routing.py`, plus a jsdom run of `page_files_load.js` in the scratchpad (not committed)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 5's routes and Batch 2's `serialPanes` / `changeErrorText`.
|
||||
- Produces:
|
||||
- `DEVICE_ROUTES`:
|
||||
- `call_home_state: ['GET', '/device/call_home/state', true]`
|
||||
- `call_home_on: ['POST', '/device/call_home/enable', true]`
|
||||
- `call_home_off: ['POST', '/device/call_home/disable', true]`
|
||||
- `controlsFor(unit).callHomeChange = serialMode && (series === 3 || series === 4)`. `callHomeWrite` (the legacy multi-field form) stays `false`, with `reasons.callHomeWrite = 'By serial: use Call-home On / Off (audited). Other call-home fields wait for the THOR round.'`
|
||||
- `serialPanes(...)` gains `callHomeForm: !bySerial` and `callHomeBox: bySerial`. Batch 2's existing test gets the two keys added.
|
||||
- `changeErrorText(label, status, body, unit, statusText)` takes the whole label (`"Start monitoring"`, `"Enable call-home"`) and returns `` `${label} not confirmed: …` `` / `` `${label} failed: …` ``. Update its two callers and Batch 2's test.
|
||||
- `callHomeRows(state) -> [[label, value], …]` returns:
|
||||
- `['Call-home', 'On' | 'Off' | 'Unknown (byte 5 = 0xNN)']`
|
||||
- `['Dial string', … or '—']`
|
||||
- `['Series', 3 | 4]`
|
||||
- [ ] **Step 1: Write the failing Node tests:**
|
||||
- `test_call_home_routes_need_a_serial`: `deviceUrl('call_home_on', BLANK)` → null; with S4 → `{method: 'POST', path: '/device/call_home/enable?serial=UM20147&host=h&tcp_port=9034'}`.
|
||||
- `test_call_home_change_needs_a_confirmed_series`: typed but unconfirmed → false; confirmed 3 → true; confirmed 4 → true; legacy → false.
|
||||
- `test_call_home_rows`: `{enabled: true, dial_string: 'RADIO RING', series: 4}` → `[['Call-home','On'],['Dial string','RADIO RING'],['Series',4]]`; `{enabled: null, detail: {byte5: '0x07'}, series: 3}` → first row `['Call-home','Unknown (byte 5 = 0x07)']`.
|
||||
- Update the `changeErrorText` and `serialPanes` tests to the new shapes.
|
||||
- [ ] **Step 2: Run** `pytest tests/test_webapp_device_routing.py`. Expected: FAIL (`callHomeRows` is not defined).
|
||||
- [ ] **Step 3: Implement the routing functions**, then the glue:
|
||||
- By serial, the Call Home tab hides the legacy form and shows the state box via `serialPanes`, in `applyControls`.
|
||||
- `readCallHome()` uses `call_home_state` and renders `callHomeRows`.
|
||||
- `changeCallHome(on)` asks `confirm()` with the serial and on/off, sends `call_home_on`/`call_home_off`, reports with `changeSummary` / `changeErrorText('Enable call-home' | 'Disable call-home', …)`, then re-reads the state.
|
||||
- The buttons are enabled by `controlsFor().callHomeChange`.
|
||||
- HTML: `#ch-state` (a `dev-table`), `#ch-on-btn` and `#ch-off-btn` inside a `#ch-serial` box; the existing form goes in `#ch-legacy`.
|
||||
- [ ] **Step 4: Run** the Node tests (pass), then the jsdom check. Extend `page_files_load.js` with:
|
||||
- S4: Call Home read → rows shown, legacy form hidden;
|
||||
- Off → `POST /device/call_home/disable?serial=UM20147…` sent after confirm, status from `changeSummary`;
|
||||
- legacy mode: form shown;
|
||||
- no script errors.
|
||||
- [ ] **Step 5: Commit** `feat(sfm): the page's Call Home tab by serial -- state and audited On / Off (phase 4)`.
|
||||
|
||||
### Task 7: Docs, and the bench session (Brian's go per send)
|
||||
|
||||
**Files:**
|
||||
- Modify: the spec (a "Phase 4" entry after phase 3's under Build phases), `CLAUDE.md` ("Where things stand"), and `docs/micromate_protocol_reference.md` / `docs/instantel_protocol_reference.md` (CRLF: Edit tool or byte-safe writes) for whatever the bench measures
|
||||
|
||||
- [ ] **Step 1: Docs before the bench.**
|
||||
- Spec: what was built, with commit IDs; the gate's state; the bench questions below.
|
||||
- CLAUDE.md: one status line.
|
||||
- Commit `docs: phase 4 built -- call-home enable/disable by serial; bench questions`.
|
||||
- [ ] **Step 2: Bench, UM20147 on its modem, idle.** One send per go:
|
||||
- (a) dry run `disable`, showing frames and warnings, including "0x00 is unobserved";
|
||||
- (b) `enable` with `even_if_already` (the no-op write: does a Micromate accept it?);
|
||||
- (c) `disable`: read-back, the unit's screen, and the snapshot's changed offsets;
|
||||
- (d) `enable`, back to how it was.
|
||||
- Record each audit id and `[118:120]` before/after.
|
||||
- [ ] **Step 3: Bench, BE9441 on its modem, idle.**
|
||||
- If Task 4 did not run: first record Blastware changing call-home on BE9441 through the bridge, then run Task 4.
|
||||
- Then (a) to (d) as above.
|
||||
- [ ] **Step 4: One unit monitoring** (Brian picks which): a dry run, then one `disable` / `enable` pair. This settles whether a unit accepts a call-home write while monitoring. Unmeasured; nothing in the code assumes either answer.
|
||||
- [ ] **Step 5: Record the results** in the spec and the protocol references (measured, with audit ids), and commit `docs: phase 4 bench -- call-home on/off on both series`.
|
||||
@@ -0,0 +1,525 @@
|
||||
# Phase 5: Changing a Unit's Settings by Serial — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** An operator edits a unit's live settings in SFM, by serial, on either series: preview old → new, send once (audited), and see what the unit now holds.
|
||||
|
||||
**Architecture:**
|
||||
- **One pure settings codec for both series** (`micromate/setup_fields.py`), on the measured shared 2,090-byte layout.
|
||||
- **Each series' adapter supplies reads, the plan and the send** to the existing `run_change` core, unchanged.
|
||||
- Its "state" is a read-back verdict: `as asked` / `unchanged` / `differs`.
|
||||
- Series 3 sends through `push_config_raw`; Series 4 through `plan_setup_push`.
|
||||
- Series 4 also reads the unit's schedule, read-only, to refuse a change that a scheduled start would undo.
|
||||
- **One audited route**, `POST /device/settings/change`. The legacy by-host write is retired.
|
||||
|
||||
**Tech Stack:** Python 3 (FastAPI, pytest), vanilla JS tested in Node (`tests/test_webapp_device_routing.py`).
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md` (approved by Brian 2026-11-03). Parent spec: `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- **Worktree and branch:** work in `~/seismo-relay-parity` on `feat/series4-sfm-parity`. Check `git branch --show-current` before every commit; never commit to `main`; push every commit.
|
||||
- **Python:** `/home/serversdown/seismo-relay/.venv/bin/python -m pytest …` from the worktree root.
|
||||
- **The suite has 16 known failures.**
|
||||
- Run the full suite once before Task 1 and save the failure list in the plan workspace as `baseline-failures.txt`.
|
||||
- Before every commit, run the suite, read the failure list, and confirm it equals the baseline.
|
||||
- Commit in a separate call, never chained to the test run.
|
||||
- **No live device traffic** in any task. The bench is after the final review, with Brian's explicit go per send.
|
||||
- Never port 8200.
|
||||
- Never write modem baud or modem type.
|
||||
- Never send `0xA2`.
|
||||
- **`CHANGELOG.md` is not touched** on this branch; it is written on `dev` at the merge.
|
||||
- **No inline JavaScript.** New page logic goes in `sfm/static/device_routing.js` (DOM-free, Node-tested); glue goes in `sfm/static/sfm_webapp.js`.
|
||||
- **`docs/instantel_protocol_reference.md` is CRLF.** Edit it only with the Edit tool. Keep its rows in date order.
|
||||
- **Off-limits (the checker session's files):** `minimateplus/event_file_io.py`, `histogram_codec.py`, `waveform_codec.py`, `bw_xml_report.py`, `decode_check*.py`.
|
||||
- **`TOOL_VERSION` is unchanged:** nothing here changes event decoding. Operational consequence: none; no migration, no backfill.
|
||||
- **Grade every protocol claim** in comments and docs as measured or inferred.
|
||||
- **Mutation checks:** after a mutate/restore, delete the module's `__pycache__/*.pyc` before the confirming run.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. **A Micromate with no schedule file, or a schedule read that fails.**
|
||||
- A body with no records means no conflict, and the change proceeds.
|
||||
- A read that raises refuses the change in plain words.
|
||||
- Owner: Task 4; tests `test_no_schedule_records_is_no_conflict` and `test_an_unreadable_schedule_refuses`.
|
||||
2. **A float that is stored as f32.** 0.3 reads back as 0.30000001192.
|
||||
- The verdict compares bytes with the image written, never floats, so it reads `as asked`.
|
||||
- Owner: Task 2; test `test_f32_values_read_back_as_asked`.
|
||||
3. **A stale or foreign revision** after a keypad edit, or a preview of another unit.
|
||||
- The send is refused with 409, nothing is sent, and no audit row is written.
|
||||
- Owner: Tasks 4 and 5; tests `test_s4_stale_revision_sends_nothing` and `test_s3_stale_revision_sends_nothing`.
|
||||
4. **Range and trigger changed in one request.** The trigger is checked against the **new** range.
|
||||
- Owner: Task 2; test `test_trigger_checked_against_the_new_range`.
|
||||
5. **Notes at the edges.**
|
||||
- `""` clears a note.
|
||||
- 41 bytes is accepted; 42 is refused; non-ASCII is refused.
|
||||
- Labels are never written.
|
||||
- Owner: Task 2; tests `test_note_edges` and `test_note_labels_are_never_written`.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| file | responsibility |
|
||||
|---|---|
|
||||
| `minimateplus/protocol.py` | **Series 3 assembly:** `assemble_compliance_content`, `is_compliance_content`, `MiniMateProtocol.read_compliance_content`. **Writes:** `push_config_raw`'s pre-check raises `ImageRefused`. |
|
||||
| `minimateplus/client.py` | **Added:** `read_compliance_content()` and `read_settings_blocks()`. **Deleted:** `apply_config`, `set_project_info`, `_encode_compliance_config`. |
|
||||
| `micromate/setup_block.py` | **Added:** `with_crc(content)`. |
|
||||
| `micromate/setup_fields.py` (new) | **The shared, pure settings codec:** field registry, `editable_fields`, `check_changes`, `encode_setup`, `field_values`, `settings_state`, `revision`. |
|
||||
| `micromate/schedule.py` (new) | **Pure:** `parse_schedule`, `ScheduleEntry`, `schedule_conflicts`. |
|
||||
| `micromate/protocol.py` | **Added:** `read_file(path)`, using `0x94` then `0x48` pages. |
|
||||
| `micromate/client.py` | **Added:** `read_schedule()`, `get_active_setup_raw()`, `get_prefs_content()`, `get_trigger_content()`, `get_setup_content()`. |
|
||||
| `micromate/opcodes.py` | `ENABLEABLE_WRITES` gains the setup-push SUBs. |
|
||||
| `sfm/device_access/errors.py` | **Added:** `SettingsChanged` and `ChangeRefused`, both 409. |
|
||||
| `sfm/device_access/change.py` | **Added:** `settings_change()`. |
|
||||
| `sfm/device_access/s4.py` | `s4_settings` moves onto the codec. **Added:** `s4_change_settings`. |
|
||||
| `sfm/device_access/s3.py` | `Series3Adapter.settings` moves onto the codec. **Added:** `Series3Adapter.change_settings`. |
|
||||
| `sfm/device_access/access.py` | **Added:** `DeviceAccess.change_settings`. |
|
||||
| `sfm/server.py` | **Added:** `POST /device/settings/change`. `/device/config` and `/device/config/project` return 410. |
|
||||
| `sfm/static/device_routing.js`, `sfm/static/sfm_webapp.js`, `sfm/sfm_webapp.html` | The edit form. |
|
||||
| `tests/device_access_fakes.py` | The fakes gain settings blocks, a schedule, and writes. |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Series 3 — assemble a settings read into the logical block
|
||||
|
||||
**Measured basis (spec, 2026-11-03):** unescape each `1A` data frame and take `data[11:]`. Every frame but the last starts with one non-content `00` byte; drop it. The result is 2,090 bytes with `N = 2090` at `[0:2]`.
|
||||
|
||||
**Files:**
|
||||
- Modify: `minimateplus/protocol.py`, near `read_compliance_config` (≈ line 913)
|
||||
- Modify: `minimateplus/client.py`
|
||||
- Modify: `docs/instantel_protocol_reference.md` (one dated row, 2026-11-03)
|
||||
- Test: `tests/test_s3_settings_read.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `assemble_compliance_content(frames: list[bytes]) -> bytes`. `frames` is each data reply's `frame.data`, escapes kept, in order.
|
||||
- `is_compliance_content(block: bytes) -> bool`: `len == 2090` and `int.from_bytes(block[0:2], "big") == 2090`.
|
||||
- `COMPLIANCE_CONTENT_LEN = 2090`.
|
||||
- `MiniMateProtocol.read_compliance_content() -> bytes`:
|
||||
- sends the same probe and B/C/D requests as `read_compliance_config`;
|
||||
- a missing data frame raises `ProtocolError` (no `continue`);
|
||||
- returns the assembled bytes **without** judging them, so a monitoring unit's device-info answer comes back for the caller to recognise.
|
||||
- `MiniMateClient.read_compliance_content() -> bytes`.
|
||||
- `MiniMateClient.read_settings_blocks() -> dict` with keys `event_index`, `compliance`, `trigger` and `waveform`. Each value is the bytes its existing read returns:
|
||||
- `event_index`: `proto.read_event_index()`
|
||||
- `compliance`: `read_compliance_content()`
|
||||
- `trigger`: `proto.read_trigger_config()`
|
||||
- `waveform`: `proto.read_waveform_data_raw()`
|
||||
|
||||
- [ ] **Step 1: Write the failing tests** in `tests/test_s3_settings_read.py`. Use `tests/fixtures/minimate-bench-10-26-26-histogram` (`unit_replies.bin` parsed with `S3FrameParser`). Group the `0xE5` frames into reads: a frame with `len(data) == 11` starts each read. Take the write images from `tests/test_minimate_write_frames.py` (`WRITES[0:13]`, `WRITES[13:26]`; the `0x71` payloads `[16:]` joined).
|
||||
|
||||
```python
|
||||
def test_reads_assemble_to_2090_bytes(): # all 12 reads, both frame patterns (5 and 3 frames)
|
||||
assert all(len(assemble_compliance_content(r)) == 2090 for r in READS)
|
||||
|
||||
def test_a_read_after_a_blastware_write_equals_the_write():
|
||||
assert assemble_compliance_content(READS[1]) == IMAGES[0][:2090]
|
||||
assert assemble_compliance_content(READS[2]) == IMAGES[1][:2090]
|
||||
|
||||
def test_a_monitoring_units_answer_is_not_settings(): # READS[3:8] start 0e 'BE9441'
|
||||
assert [is_compliance_content(assemble_compliance_content(r)) for r in READS[3:8]] == [False] * 5
|
||||
assert all(is_compliance_content(assemble_compliance_content(r)) for r in READS[:3] + READS[8:])
|
||||
|
||||
def test_read_compliance_content_refuses_a_missing_frame():
|
||||
... # a fake transport that answers the probe and frame B, then times out: ProtocolError, nothing assembled
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them.** `…pytest tests/test_s3_settings_read.py -q`. Expected: FAIL (ImportError: `assemble_compliance_content`).
|
||||
- [ ] **Step 3: Implement** the Produces block in `protocol.py` and `client.py`. Use `unescape_reply` from `minimateplus.framing`. The docstring cites the measurement and its fixture.
|
||||
- [ ] **Step 4: Run them.** Expected: PASS (4 passed).
|
||||
- [ ] **Step 5: Add a reference row** to `docs/instantel_protocol_reference.md` (Edit tool; CRLF), dated 2026-11-03, measured. Cover:
|
||||
- the assembly rule;
|
||||
- the round trip (2 of 2);
|
||||
- `[26:28]`: Blastware writes `00 00` (11 of 11), and the unit sets `01 7f` after monitoring;
|
||||
- the trailing two bytes: a per-unit Blastware constant (`7c ea` BE11529 ×9, `0c e9` BE9441 ×2), not the CRC, and never in a reply;
|
||||
- `0x09 [200:202]`: echoed 9 of 9 in April; changed on 10-26 (`17 17` → `78 76`).
|
||||
- [ ] **Step 6: Run the full suite** and compare the failure list with the baseline. **Then commit** (separate call): `feat(s3): assemble a settings read into the 2,090-byte block`.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: The shared settings codec
|
||||
|
||||
**Files:**
|
||||
- Create: `micromate/setup_fields.py`
|
||||
- Modify: `micromate/setup_block.py`: add `with_crc(content: bytes) -> bytes`, which returns the content with `CRC-16/AUG-CCITT` over `[0:N-2]` written BE at `[N:N+2]`.
|
||||
- Test: `tests/test_setup_fields.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1's `assemble_compliance_content`, used in tests only. The codec itself imports nothing from `minimateplus` and nothing from `sfm`.
|
||||
- Produces (all pure). Each `content` is the 2,090-byte (Series 3) or 2,092-byte (Series 4) block.
|
||||
- `editable_fields(content: bytes, series: int) -> list[dict]`. Each dict has `field`, `label`, `kind` (`"number"`, `"choice"`, `"text"` or `"bool"`) and `value`, plus as relevant `unit`, `min`, `max`, `choices` (a list of `{value, label}`) and `maxlength`.
|
||||
- `field_values(content: bytes, series: int) -> dict[str, Any]`: the same fields, values only.
|
||||
- `check_changes(content: bytes, series: int, changes: dict) -> dict`: returns the normalised changes, or raises `SettingsValueError(ValueError)` with a plain sentence. It has two kinds of check: static (names, types, choices, limits) and content-dependent (unit strings, the trigger against the range).
|
||||
- `encode_setup(content: bytes, series: int, changes: dict) -> bytes`:
|
||||
- same length as `content`;
|
||||
- only the changed fields' bytes move;
|
||||
- bit fields are patched bit by bit;
|
||||
- Series 3 also sets `[26:28] = 00 00` (`S3_BLASTWARE_FIXED`);
|
||||
- Series 4 returns `with_crc(...)`.
|
||||
- `settings_state(before: bytes, written: bytes, now: bytes, *, series: int) -> str`. It compares `[0:2090]`:
|
||||
- `"as asked"` if `now` equals `written` (Series 4 also needs `crc_ok(now)`);
|
||||
- else `"unchanged"` if `now` equals `before`;
|
||||
- else `"differs"`.
|
||||
- `revision(blocks: list[bytes]) -> str` = `hashlib.sha256(b"".join(blocks)).hexdigest()[:16]`.
|
||||
- `S3_ALARM_WRITE_MEASURED = False`. While False, `geo_alarm_ips` is shown (read-only, `kind` plus `"readonly": True`) and refused in `check_changes`.
|
||||
|
||||
**The field registry** (content offsets; channel `k` = `1708 + 48·k`, `k` = 0, 1, 2 for the geophones):
|
||||
|
||||
| field | series | bytes | values (exact) |
|
||||
|---|---|---|---|
|
||||
| `record_mode` | 3 | `[5]` | `single_shot`=0, `continuous`=1, `histogram`=3, `histogram_continuous`=4 |
|
||||
| `record_mode` | 4 | `[5]` | `waveform`=1, `manual`=2, `histogram`=3, `combo`=4 |
|
||||
| `sample_rate` | 3, 4 | `[6:8]` u16 BE | {1024, 2048, 4096} |
|
||||
| `histogram_interval_s` | 3, 4 | `[8:10]` u16 BE | {2, 5, 15, 60, 300, 900} |
|
||||
| `record_time_s` | 3 | `[18:22]` f32 BE | 1.0 ≤ v ≤ `S3_MAX_RECORD_S[sample_rate]` = {1024: 104, 2048: 52, 4096: 26}, and ≤ 13 when `record_mode` is `histogram_continuous` (the **new** mode and rate if they change too) |
|
||||
| `record_time_s` | 4 | `[18:22]` f32 BE | 1.0 ≤ v ≤ 90.0 |
|
||||
| `geo_trigger_ips` | 3, 4 | ch k `+30` f32 BE, all three | 0.005 ≤ v ≤ 10.0, a multiple of 0.001 (within 1e-9), and ≤ the (new) range's full scale (10.0 / 1.25) |
|
||||
| `geo_range` | 3 | ch k `+29` u8, all three | `normal`=0, `sensitive`=1 |
|
||||
| `geo_alarm_ips` | 3 (gated) | ch k `+38` f32 BE, all three | 0.005 ≤ v ≤ full scale |
|
||||
| `job_number` | 3, 4 | `[40:42]` u16 BE | 1 ≤ v ≤ 9999 |
|
||||
| `job_number_shown` | 3, 4 | `[39]` bit `0x02` | bool |
|
||||
| `note_1` … `note_4` | 3, 4 | value `[144+64n : 186+64n]`; label `[122+64n : 144+64n]` read only | printable ASCII 0x20–0x7E, ≤ 41 bytes, zero-filled to 42 |
|
||||
|
||||
The limits are **the units' own, from Instantel's manuals** (Brian, 2026-11-03), cited in the module as comments:
|
||||
- **Trigger** 0.005–10 in/s, steps of 0.001: MiniMate Plus manual 716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual 721U0201 Rev 06, *Geophone Trigger Level*.
|
||||
- **Record time:**
|
||||
- Micromate 1–90 s (*Record Time*).
|
||||
- MiniMate: §4.4's *Maximum Record Times*, 1 MB unit, channels 1–4; §3.8.9, 13 s in Histogram Combo.
|
||||
- **Job number** 1–9999: both manuals.
|
||||
|
||||
**A level write is refused** unless all three geophone channels' unit string, `ch +34:+38` with NULs and `.` stripped, equals `in`. Measured: `in.` and `in` both occur on UM20147. A unit set to Metric is unmeasured.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests** in `tests/test_setup_fields.py`:
|
||||
|
||||
```python
|
||||
def test_s3_reproduces_every_blastware_write():
|
||||
# BE11529's 9 April images (bridges/captures/4-20-26/**/raw_bw_*.bin), in time order (the HHMMSS in
|
||||
# the name): before = the previous image; the first (151921) uses the assembled 1A read in its own
|
||||
# raw_s3 capture if that read is whole, else it is skipped (say so in the test). BE9441's 2 images:
|
||||
# before = the assembled READS[0], then image 1. changes = field_values(after) for every field whose
|
||||
# value differs. Assert encode_setup(before, 3, changes)[:2090] == after[:2090].
|
||||
# The 16:26 write also moves [25] (mic on): include `_sensors_mic` as a test-only patch helper,
|
||||
# not a registry field.
|
||||
|
||||
def test_s4_fixture_pairs_reproduce():
|
||||
# for every ordered pair (a, b) of tests/fixtures/micromate-setup/*.bin whose differing bytes outside
|
||||
# [2090:2092] all lie inside registry fields: encode_setup(a, 4, {f: field_values(b)[f] for differing f}) == b
|
||||
|
||||
def test_trigger_checked_against_the_new_range(): ... # Series 3: {"geo_range": "sensitive", "geo_trigger_ips": 2.0} refuses (above 1.25); 1.25 passes; {"geo_trigger_ips": 2.0} alone on Normal passes
|
||||
def test_limits_refuse_outside_values(): ... # 0.004 and 10.001 in/s; 0.3005 (not a 0.001 step); job 0 and 10000; S4 0.9 and 90.1 s;
|
||||
# S3 at 4096 sps: 26 ok, 26.1 refused; S3 histogram_continuous: 13 ok, 13.1 refused;
|
||||
# S3 {"sample_rate": 1024, "record_time_s": 100} passes from a 4096 sps block (the new rate counts);
|
||||
# sample rate 8192; interval 30
|
||||
def test_field_not_offered_for_the_series(): ... # geo_range on series 4 -> SettingsValueError naming the series
|
||||
def test_alarm_is_read_only_until_measured(): ... # Series 3 geo_alarm_ips -> SettingsValueError while S3_ALARM_WRITE_MEASURED is False
|
||||
def test_metric_unit_string_refuses_level_writes(): ... # ch +34 = b"mm\x00\x00" -> SettingsValueError; b"in.\x00" and b"in\x00\x00" pass
|
||||
def test_note_edges(): ... # "" clears; 41 bytes ok; 42 refused; "café" refused
|
||||
def test_note_labels_are_never_written(): ... # changing note_2 moves only [208:250]
|
||||
def test_bit_fields_keep_unknown_bits(): ... # [39] = 0x81: job_number_shown True -> 0x83, False -> 0x81
|
||||
def test_s3_fixed_bytes(): ... # any S3 encode sets [26:28] = 00 00
|
||||
def test_s4_encode_recomputes_the_crc(): ... # crc_ok(encode_setup(fixture, 4, {"job_number": 7}))
|
||||
def test_f32_values_read_back_as_asked(): ... # written = encode(0.3); settings_state(before, written, written) == "as asked"
|
||||
def test_settings_state(): ... # "as asked" / "unchanged" / "differs"; S4 with a bad CRC -> "differs"
|
||||
def test_revision_is_stable_and_content_sensitive(): ...
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them.** Expected: FAIL (ModuleNotFoundError: `micromate.setup_fields`).
|
||||
- [ ] **Step 3: Implement** `micromate/setup_fields.py` and `with_crc`. Decode via the registry (not via `decode_setup`, whose notes are keyed by label). Note labels come from the unit and are display only.
|
||||
- [ ] **Step 4: Run them.** Expected: PASS. Then mutation-check `S3_BLASTWARE_FIXED` (remove it: the Blastware-write test fails), delete the `.pyc`, and restore.
|
||||
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(codec): one settings codec for both series, on the shared layout`.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Micromate — read the schedule file
|
||||
|
||||
**Measured basis:** reference *The scheduler, and a generic file transfer* and *The schedule record format*.
|
||||
- `0x94 <path>` opens a file for read; `offset` = the path's length, and the payload is the path, unpadded.
|
||||
- `0x48` reads the next page, repeated until an all-zero 11-byte response.
|
||||
- The file is 260-byte records. `[4]` is the half-hour slot. `[6]` is the action bitmask: 2 start-with-setup, 4 stop, 8 self-check, 16 ACH. `[7]` is the name length; `[8:260]` is the name.
|
||||
|
||||
**Files:**
|
||||
- Create: `micromate/schedule.py`
|
||||
- Modify: `micromate/protocol.py` (`read_file`), `micromate/client.py`
|
||||
- Modify: `docs/micromate_protocol_reference.md`: one line under the scheduler section saying SFM reads it (read-only) from 2026-11-03.
|
||||
- Test: `tests/test_micromate_schedule.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `SCHEDULE_PATH = "\\system\\schedule\\schedule.dat"`.
|
||||
- `MicromateProtocol.read_file(path: str) -> bytes`: the concatenated content of each `0x48` page after the page-0 descriptor, stopping at the all-zero response; at most 64 pages, else `ProtocolError`.
|
||||
- `MicromateClient.read_schedule() -> bytes`.
|
||||
- `MicromateClient.get_active_setup_raw() -> str`: the `0x41` name up to its NUL, **not** stripped.
|
||||
- `MicromateClient.get_prefs_content() -> bytes` (`0x08`), `get_trigger_content() -> bytes` (`0x2E`) and `get_setup_content() -> bytes` (`0x1A`), each `_content(...)` of its read.
|
||||
- `@dataclass(frozen=True) class ScheduleEntry`: `index: int`, `time: str` (`"HH:MM"`), `day: int`, `action_bits: int`, `actions: tuple[str, ...]`, `setup: str`.
|
||||
- `parse_schedule(body: bytes) -> list[ScheduleEntry]`: 260-byte records; a record with `[4:8]` all zero and no name ends the list. `actions` names the bits 2/4/8/16 as `start_with_setup`, `stop`, `self_check` and `call_home`; any other bit becomes `unknown(0xNN)`.
|
||||
- `schedule_conflicts(entries, active_setup: str) -> list[ScheduleEntry]`: start entries whose setup, compared case-insensitively after `strip()`, is not the active setup.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests.** Parse the bodies from `bridges/captures/9-24-26 - micromate2/raw_s3_20260924_191835_read_scheduler.bin` (frames 0–4), and from the two `raw_*_20260925_*` captures, with `MicromateFrameParser`.
|
||||
|
||||
```python
|
||||
def test_the_read_capture_parses(): # 2 records: start-with-setup 07:30 (40-char name), call_home 19:30 (no name)
|
||||
def test_the_five_entry_schedule_parses(): # 07:30 start TEST1.mmb, 08:00 stop, 08:30 self_check, 09:00 start test2.mmb, 19:30 call_home
|
||||
def test_conflicts_are_case_insensitive(): # active "test1.MMB" -> only the test2.mmb start conflicts
|
||||
def test_no_schedule_records_is_no_conflict(): assert schedule_conflicts(parse_schedule(bytes(524)), "x.mmb") == []
|
||||
def test_read_file_sends_the_path_unpadded_and_stops_at_zeros(): ... # a fake protocol: 0x94 offset 0x001D, then 0x48 until all-zero
|
||||
def test_get_active_setup_raw_keeps_spaces(): ... # " LOC 4 .mmb " survives
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them.** Expected: FAIL (ModuleNotFoundError: `micromate.schedule`).
|
||||
- [ ] **Step 3: Implement** the Produces block. `read_file` builds `0x94` with `build_request(0x94, len(path), bytes(10), path.encode("ascii"))`. Both SUBs are already in `READ_SUBS`.
|
||||
- [ ] **Step 4: Run them.** Expected: PASS.
|
||||
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(micromate): read the schedule file (read-only)`.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Change-path pieces and the Series 4 settings change
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/device_access/errors.py`, `sfm/device_access/change.py`, `micromate/opcodes.py`, `sfm/device_access/s4.py`, `tests/device_access_fakes.py`
|
||||
- Modify: `tests/test_micromate_execute.py`, `tests/test_micromate_opcodes.py`. Their over-ceiling example `0x71` becomes enableable here; use `0xA8` (delete one event) instead.
|
||||
- Test: `tests/test_device_access_s4_settings.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes:
|
||||
- Task 2: `editable_fields`, `field_values`, `check_changes`, `encode_setup`, `settings_state`, `revision`.
|
||||
- Task 3: `read_schedule`, `parse_schedule`, `schedule_conflicts`, `get_active_setup_raw`, and the content getters.
|
||||
- `micromate.writes.plan_setup_push(prefs, trigger, setup, name)`.
|
||||
- Produces:
|
||||
- `class SettingsChanged(DeviceError)`, `http_status = 409`.
|
||||
- `class ChangeRefused(DeviceError)`, `http_status = 409`.
|
||||
- `settings_change() -> ChangeKind("change settings", "as asked", "applied")`.
|
||||
- `ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F, 0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72})`.
|
||||
- `s4_settings(client, serial) -> UnitSettings`. It keeps every current field, plus `detail["editable"] = editable_fields(setup, 4)`. The revision comes only from a preview (dry run), never from this read.
|
||||
- `s4_change_settings(client, serial, *, changes: dict, revision: Optional[str], dry_run: bool, audit, address, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`.
|
||||
|
||||
**`s4_change_settings` behaviour**, through `run_change` (`even_if_already=False`):
|
||||
|
||||
- **`read_state`, first call:**
|
||||
- Read the run state.
|
||||
- `calling_home` and `unknown*` are returned as they are.
|
||||
- `monitoring` raises `UnitStateUnknown(f"{serial} is monitoring -- stop it first (a stop makes it call in if call-home is on) -- nothing sent")`.
|
||||
- Read the name (raw), prefs, trigger and setup.
|
||||
- `check_changes` (a `SettingsValueError` becomes `BadRequest`).
|
||||
- When live, `revision([name.encode("ascii"), prefs, trigger, setup])` must equal the request's. Otherwise raise `SettingsChanged("the unit's settings changed since the preview -- preview again; nothing sent")`.
|
||||
- `image = encode_setup(setup, 4, changes)`.
|
||||
- Read the schedule; a read error is kept as a blocking reason.
|
||||
- Return `settings_state(setup, image, setup, series=4)`.
|
||||
- **Later calls:** read the setup and return `settings_state(before, image, now, series=4)`.
|
||||
- **`describe_plan`:**
|
||||
- `plan_setup_push(prefs, trigger, image, name).describe()`, plus `fields` = `{f: {label, old, new}}` for the changed fields, `revision`, `warnings` and `blocked`.
|
||||
- `warnings` always includes: "this reads the unit's keypad edit buffer: if someone is in its menu, their unsaved edits are sent too".
|
||||
- `blocked`:
|
||||
- the name is `factory.MMB` (case-insensitive): "this unit is running its factory setup; load any other setup on its keypad, then try again";
|
||||
- each schedule conflict: "this unit's schedule loads <setup> at <HH:MM>, which would replace this change";
|
||||
- a schedule read error: "could not read this unit's schedule (<error>) -- SFM will not change a unit whose schedule it cannot check";
|
||||
- `plan_setup_push` raising `ValueError` (a block size or header THOR's offsets were never seen at, or a failed checksum): "this unit's <message> -- SFM has not seen a block like it".
|
||||
- When `blocked` is non-empty, `steps` is `[]`, and a live call raises `ChangeRefused("; ".join(blocked) + " -- nothing sent")`.
|
||||
- When the schedule names the active setup, `warnings` adds: "the unit's schedule loads this setup at <HH:MM>; the change survives it".
|
||||
- **`send`:** `client.protocol.execute(plan)`, as `s4_change_call_home` does.
|
||||
- **`snapshot`:**
|
||||
- `fields`: `{f: {label, old, new, now}}`;
|
||||
- `before` / `after` hex of the setup;
|
||||
- `changed_offsets`;
|
||||
- `prefs` and `trigger`: before hex only.
|
||||
- **`is_refusal`**, **`is_ring`** and **`pre_send`**: as in `s4_change_call_home`.
|
||||
|
||||
**Validation order:** a live call without `revision` is refused before any I/O, in Task 6's `DeviceAccess` (not here).
|
||||
|
||||
- [ ] **Step 1: Write the failing tests.** Extend `FakeMicromateClient` with:
|
||||
- `setup` (default: `tests/fixtures/micromate-setup/um20147_baseline.bin`'s last 2,092 bytes);
|
||||
- `prefs`, `trigger` and `active_name` (default `"test2.mmb"`);
|
||||
- `schedule_body` (default `bytes(524)`) and `schedule_error`;
|
||||
- `execute` applies a setup-push plan's `0x71` data to `self.setup` (re-adding the CRC with `with_crc`), so a read-back sees it.
|
||||
|
||||
```python
|
||||
def test_s4_dry_run_previews_old_to_new_and_sends_nothing(): # fields == {"geo_trigger_ips": {"label": ..., "old": 0.5, "new": 0.3}}; revision present; fake.executed == []
|
||||
def test_s4_trigger_change_sends_the_push_and_verifies(): # subs [0xDA,0x68,0x73,0x82,0x83,0x71,0x72]; outcome sent/ok; state_after "as asked"
|
||||
def test_s4_stale_revision_sends_nothing(): # SettingsChanged; fake.executed == []; audit has no rows
|
||||
def test_s4_already_as_asked_is_skipped(): # outcome skipped, nothing executed
|
||||
def test_s4_monitoring_is_refused(dry_run in (True, False)): # "stop it first" and "nothing sent"
|
||||
def test_s4_factory_setup_is_refused_live_and_shown_in_preview():
|
||||
def test_s4_schedule_conflict_blocks(): # schedule starts "other.mmb" at 07:00 -> ChangeRefused naming other.mmb and 07:00
|
||||
def test_s4_schedule_on_the_active_setup_warns_only():
|
||||
def test_an_unreadable_schedule_refuses():
|
||||
def test_no_schedule_records_is_no_conflict(): # bytes(524) -> sent
|
||||
def test_s4_a_lost_ack_records_what_the_unit_holds(): # execute_error -> outcome failed, sent True, snapshot present
|
||||
def test_s4_unseen_block_size_is_blocked(): # prefs 91 B -> preview blocked; live ChangeRefused; nothing executed
|
||||
def test_setup_push_subs_are_now_enableable():
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them.** Expected: FAIL (ImportError: `s4_change_settings`).
|
||||
- [ ] **Step 3: Implement** the Produces block and update `s4_settings`. In the two opcode tests, swap the over-ceiling example to `0xA8`.
|
||||
- [ ] **Step 4: Run them**, plus `tests/test_micromate_execute.py`, `tests/test_micromate_opcodes.py`, `tests/test_micromate_writes.py` (THOR's setup-push frames still reproduce) and `tests/test_device_access_s4_call_home.py`. Expected: PASS.
|
||||
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(s4): change a Micromate's settings by serial, audited, schedule-checked`.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: The Series 3 settings change
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/device_access/s3.py`, `minimateplus/client.py` (`push_config_raw` pre-check), `tests/device_access_fakes.py`
|
||||
- Test: `tests/test_device_access_s3_settings.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes:
|
||||
- Task 1: `read_compliance_content`, `read_settings_blocks`, `is_compliance_content`.
|
||||
- Task 2: the codec.
|
||||
- Task 4: `settings_change`, `SettingsChanged`, `ChangeRefused`.
|
||||
- `MiniMateClient.push_config_raw(event_index, compliance, trigger, waveform)`.
|
||||
- Produces:
|
||||
- `push_config_raw` raises `ImageRefused` (from `minimateplus.protocol`) when its pre-check refuses a block, before any frame.
|
||||
- `Series3Adapter.settings(address, serial) -> UnitSettings`. It is built on `read_compliance_content` and the codec, with the same top-level fields as today, plus `detail["editable"]`. A non-settings answer raises `UnitStateUnknown(S3_SETTINGS_WHILE_MONITORING)`.
|
||||
- `S3_SETTINGS_WHILE_MONITORING = "did not return its settings -- a MiniMate answers this way while monitoring; stop monitoring first"`.
|
||||
- `Series3Adapter.change_settings(address, serial, *, changes, revision, dry_run, audit, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`, through `run_change` and `self._run(address, op, retry=False)`:
|
||||
- `read_serial`: `client.connect().serial`.
|
||||
- **`read_state`, first call:**
|
||||
- Wake, then `read_settings_blocks()`.
|
||||
- A non-settings `compliance` raises `UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")`.
|
||||
- `check_changes`, and the live revision check over `[event_index, compliance, trigger, waveform]`.
|
||||
- Compute `image = encode_setup(...)` and return `settings_state(...)`.
|
||||
- **Later calls:** wake, `read_compliance_content()`, then the verdict.
|
||||
- **`describe_plan`:**
|
||||
- `steps` in Blastware's order: 68 (event index, as read), 73, 71 (settings block, 2,092 B), 72, 82 (trigger, as read), 83, 69 (waveform data, as read), 74, 72. Each step has `sub`, `what` and `data_len`.
|
||||
- `fields`, `revision` and `warnings` as Series 4. The warning: "the two bytes after the settings block go out as 00 00 (Blastware sends its own constant; effect unmeasured)".
|
||||
- **`send`:** `client.push_config_raw(event_index, image, trigger, waveform)`.
|
||||
- **`is_refusal`:** `isinstance(e, ImageRefused)`.
|
||||
- **`snapshot`:** as Series 4, without prefs and trigger.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests.** Extend `FakeMiniMateClient` with:
|
||||
- `settings_blocks`: the default compliance is BE9441's assembled 10-26 read 2; `event_index`, `trigger` and `waveform` are the `0x68`, `0x82` and `0x69` payloads (`[16:]`) of `WRITES[13:26]` in `tests/test_minimate_write_frames.py`, each minus its two trailing bytes (a write is the read plus two);
|
||||
- `push_config_raw` records its four arguments and makes the compliance the new `read_compliance_content`;
|
||||
- `monitoring_settings=True` returns a device-info-shaped block.
|
||||
|
||||
```python
|
||||
def test_s3_settings_read_uses_the_codec(): # editable includes geo_range; record_mode "histogram"; notes by slot with unit labels
|
||||
def test_s3_dry_run_previews_and_sends_nothing():
|
||||
def test_s3_trigger_change_sends_the_units_own_blocks(): # push args: event_index/trigger/waveform == the read blocks; compliance == encode_setup(...)
|
||||
def test_s3_change_verifies_by_read_back(): # outcome sent/ok, state_after "as asked", snapshot fields old/new/now
|
||||
def test_s3_stale_revision_sends_nothing():
|
||||
def test_s3_monitoring_is_refused(dry_run in (True, False)):
|
||||
def test_s3_a_refused_image_is_audited_as_nothing_sent(): # push_config_raw raises ImageRefused -> row sent 0, "refused before sending"
|
||||
def test_push_config_raw_precheck_raises_image_refused(): # a 2,089-byte compliance block -> ImageRefused, no frame written
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them.** Expected: FAIL (AttributeError: `change_settings`).
|
||||
- [ ] **Step 3: Implement** the Produces block.
|
||||
- [ ] **Step 4: Run them**, plus `tests/test_s3_call_home.py`, `tests/test_minimate_write_frames.py` and `tests/test_device_access_*`. Expected: PASS, except the tests Task 6 deletes or rewrites. If one fails here only because it pins `apply_config`, leave it for Task 6 and note that in the ledger.
|
||||
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(s3): change a MiniMate's settings by serial on the shared codec`.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Device access, the route, and retiring the legacy write
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/device_access/access.py`, `sfm/server.py`, `minimateplus/client.py`
|
||||
- Delete: `poc_set_project.py`. Remove `exp_compliance_only` (and its registration) from `experiments.py`.
|
||||
- **Ruling (spec: "the legacy write is retired"):** both write a live unit through the retired encoder, which #46 found wrong. Git keeps them.
|
||||
- Modify tests:
|
||||
- `tests/test_s3_compliance_anchor_fields.py`: remove its write-side tests (the encoder is gone).
|
||||
- `tests/test_minimate_write_frames.py`: `test_apply_config_writes_the_units_own_trigger_block` moves to Task 5's `test_s3_trigger_change_sends_the_units_own_blocks`; delete it here.
|
||||
- `tests/test_server_series3_guard.py`: drop `apply_config` from `WRITES` and its fake method.
|
||||
- `tests/test_server_device_access.py`: `/device/config` now 410.
|
||||
- Test: `tests/test_device_access_settings.py` (new), `tests/test_server_settings_change.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 4's `s4_change_settings` and Task 5's `Series3Adapter.change_settings`.
|
||||
- Produces:
|
||||
- `DeviceAccess.change_settings(address, serial, *, changes: dict, revision: Optional[str], dry_run: bool = False, caller: str = "api") -> ChangeResult`:
|
||||
- `normalise_serial`, then `series_for_serial`;
|
||||
- `changes` must be a non-empty dict, else `BadRequest`;
|
||||
- a live call without `revision` raises `BadRequest("preview first: a live change needs the revision from its preview -- nothing sent")`;
|
||||
- a live call with no audit log raises `NotSupported` (as `set_call_home`);
|
||||
- `_dispatch(..., change=True)` with `verify_timeout_s=_SETTINGS_VERIFY_TIMEOUT_S = 2.0` and `verify_interval_s=_SETTINGS_VERIFY_INTERVAL_S = 1.0`.
|
||||
- `POST /device/settings/change`:
|
||||
- query: `serial` (required), `host`, `tcp_port`, `port`, `baud`, `dry_run`, `caller`;
|
||||
- JSON body `{"changes": {...}, "revision": "..."}`;
|
||||
- returns `_change_response(...)`;
|
||||
- added to `_SERIAL_AWARE_PATHS`.
|
||||
- `POST /device/config` and `POST /device/config/project` return **410** with `{"detail": "retired: change a unit's settings by serial with POST /device/settings/change (audited, previewed, read back)"}`. Remove the cache-dirty hooks that only these routes called; keep the read routes.
|
||||
- Delete `MiniMateClient.apply_config`, `set_project_info` and `_encode_compliance_config`, and any import left orphaned.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_live_change_without_revision_is_refused_before_io(): # factory never called
|
||||
def test_empty_changes_is_a_bad_request():
|
||||
def test_change_settings_dispatches_by_series_with_change_true():
|
||||
def test_route_dry_run_returns_fields_and_revision(): # 200, body.plan.fields, body.plan.revision
|
||||
def test_route_verified_change_is_200_and_mismatch_409():
|
||||
def test_route_unconfirmed_carries_sent_and_audit_id():
|
||||
def test_route_refusal_is_409_with_reason(): # ChangeRefused / SettingsChanged / monitoring
|
||||
def test_legacy_config_routes_are_gone(): # both 410, nothing reaches a client factory
|
||||
def test_settings_change_is_serial_aware(): # in _SERIAL_AWARE_PATHS; a UM serial goes to the Series-4 path
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them.** Expected: FAIL (404 / AttributeError).
|
||||
- [ ] **Step 3: Implement** the Produces block, the deletions, and the test updates listed under Files.
|
||||
- [ ] **Step 4: Run them**, plus `tests/test_server_*.py`. Expected: PASS. Check that `grep -rn "apply_config\|set_project_info\|_encode_compliance_config" --include=*.py .` finds only comments and history.
|
||||
- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(sfm): POST /device/settings/change; retire the legacy config write`.
|
||||
|
||||
---
|
||||
|
||||
### Task 7: The page — edit, preview, send, "the unit now holds"
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/static/device_routing.js`, `sfm/static/sfm_webapp.js`, `sfm/sfm_webapp.html`
|
||||
- Modify: `CLAUDE.md` (the "Where things stand" Series-4 parity line: phase 5 built, bench pending), and the spec's status line ("Built 2026-11-xx; bench pending").
|
||||
- Test: `tests/test_webapp_device_routing.py` (extend `EXPORTS` and cases), `tests/test_webapp_static.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `UnitSettings.detail.editable` / `.revision`, and the `ChangeResult` shapes from Tasks 4–6.
|
||||
- Produces (DOM-free, in `device_routing.js`):
|
||||
- `DEVICE_ROUTES.settings_change = ['POST', '/device/settings/change', true]`; remove `config_write`.
|
||||
- `controlsFor(unit)`: `configWrite: serialMode && (series === 3 || series === 4)`; `reasons.configWrite: 'By serial only: Preview, then Send (audited).'`
|
||||
- `settingsFormFields(st) -> Array<{field, label, kind, value, unit?, min?, max?, choices?, maxlength?, readonly?}>`: from `st.detail.editable`, in that order.
|
||||
- `settingsChanges(fields, edited) -> object`: only fields whose edited value differs. Numbers compare as numbers; read-only fields are ignored.
|
||||
- `settingsPreviewRows(body) -> Array<[label, old, new]>`, from `body.plan.fields`.
|
||||
- `settingsBlockedText(body) -> string`: `body.plan.blocked` joined; `''` if none.
|
||||
- `settingsResultRows(body) -> Array<[label, old, new, now]>`, from `body.detail.snapshot.fields`.
|
||||
- **Page behaviour** (`sfm_webapp.js` glue; HTML ids `cfg-edit`, `cfg-preview-btn`, `cfg-send-btn`, `cfg-preview`, `cfg-result`):
|
||||
- The serial-mode Config pane heading reads **"On the unit <SERIAL> — read <HH:MM>"**.
|
||||
- The form is built from `settingsFormFields`.
|
||||
- **Preview** POSTs a dry run and shows old → new, warnings and blocked reasons. It keeps `revision` and enables **Send** only when nothing is blocked and something changes.
|
||||
- **Send** asks `confirm()` naming the serial and the fields, then POSTs live with the kept revision and shows "the unit now holds" rows. Errors go through `changeErrorText`.
|
||||
- Editing any field after a preview disables **Send** until the next preview.
|
||||
- The by-host legacy form loses its write button. Its read stays.
|
||||
- No inline script; listeners via `addEventListener`.
|
||||
|
||||
- [ ] **Step 1: Write the failing Node-run cases** in `tests/test_webapp_device_routing.py`:
|
||||
- `controlsFor` gives `configWrite` true by serial for both series, and false by host;
|
||||
- `settingsChanges` returns only differing fields and compares `0.30` with `0.3` as equal;
|
||||
- `settingsPreviewRows` / `settingsResultRows` / `settingsBlockedText` on bodies shaped as Task 6 returns them;
|
||||
- `deviceUrl('settings_change', unit)` → `/device/settings/change?serial=…`;
|
||||
- `config_write` is no longer a route.
|
||||
|
||||
In `tests/test_webapp_static.py`, assert the page has no inline `<script>` body and loads both static files.
|
||||
- [ ] **Step 2: Run them.** `…pytest tests/test_webapp_device_routing.py tests/test_webapp_static.py -q`. Expected: FAIL (`settingsChanges` is not a function).
|
||||
- [ ] **Step 3: Implement** the Produces block and the page behaviour.
|
||||
- [ ] **Step 4: Run them.** Expected: PASS. Then run the page under the jsdom harness pattern from phase 4 (`smoke/page_files_load.js` in the scratchpad): the page loads with no console error, and a stubbed dry-run body renders the preview rows.
|
||||
- [ ] **Step 5: Update `CLAUDE.md`** and the spec status line. **Run the full suite** and compare with the baseline. **Commit:** `feat(webapp): edit a unit's settings by serial: preview, send, read back`.
|
||||
|
||||
---
|
||||
|
||||
## After the build: final review, then the bench
|
||||
|
||||
The bench is not a task: it runs after the whole-branch review and its fixes, with Brian at the units, and **each send needs his explicit go**. Run SFM with `ringkit/sfm_parity.py` (port 8299; never 8200). Order:
|
||||
|
||||
1. **Read-only, both units:**
|
||||
- `GET /device/settings` by serial; Brian matches it against each unit's screen.
|
||||
- UM20147: `read_schedule` (measure what a unit with no schedule answers, and whether `0x08` shows the scheduler switch).
|
||||
2. **Dry runs** of a trigger change on each unit. Read the preview with Brian.
|
||||
3. **One field per unit**, with Brian's go:
|
||||
- the trigger (UM20147 0.5 → 0.3; BE9441 0.04 → 0.05);
|
||||
- read back; Brian checks the unit's menu;
|
||||
- change it back, with another go.
|
||||
4. **A notes change** on each (go).
|
||||
5. **A several-field "backup unit" change** on each (go).
|
||||
6. **Refusals:**
|
||||
- a dry run while monitoring (expect the refusal);
|
||||
- UM20147 with a schedule naming another setup, if Brian sets one up in THOR (expect the block).
|
||||
7. **Alarm level (Series 3):**
|
||||
- one write with Brian's go, read back and checked on BE9441's menu;
|
||||
- only then flip `S3_ALARM_WRITE_MEASURED`, in its own commit naming the bench result.
|
||||
|
||||
Record everything in the spec's bench section and both protocol references (measured), then the devlog.
|
||||
@@ -560,7 +560,39 @@ Each safety piece arrives with its first real use, so nothing sits untested.
|
||||
experiment.
|
||||
- **Refuse writes unless this connection's responses carried Micromate
|
||||
flags** (0xC5/0x03), alongside the serial identity check.
|
||||
4. **Call-home enable/disable** (row 9).
|
||||
4. **Call-home enable/disable** (row 9). **Built 2026-11-02** (plan
|
||||
`docs/superpowers/plans/2026-11-02-sfm-phase4-call-home.md`): `run_change` takes a
|
||||
`ChangeKind` (`1dd5bfa`); Series 4 reads bit 0 of `0x2C` content[5] and sends
|
||||
`plan_call_home_enabled` (`eeb55ef`; `ENABLEABLE_WRITES` gains `0x7E`/`0x7F`);
|
||||
Series 3 reads byte 5 of the *unescaped* block and sends `call_home_image`
|
||||
(`8612cd9`). The Series-3 frame was gated until reproduced from Blastware: its
|
||||
2026-04-20 enable and disable writes (BE11529) are rebuilt byte for byte from the
|
||||
unit's own reads (`453d42e`), so the gate is open. Routes `GET
|
||||
/device/call_home/state`, `POST /device/call_home/{enable,disable}`, serial
|
||||
required (`06fa56d`); the page's Call Home tab by serial (`84c142f`). The
|
||||
read-back judges the edited bit; the snapshot keeps both blocks and every changed
|
||||
offset (Series 4's `[118:120]` always moves). The final review, before any send,
|
||||
caught the Series-3 send path unescaping the built image a second time -- a
|
||||
16:02-16:04 call-in time would have been refused as 'sent' or sent shifted --
|
||||
fixed with a test through the real protocol (`bdd76b8`), plus a pre-wire refusal
|
||||
audited as nothing sent, an unknown Series-4 run state refused, and the snapshot
|
||||
kept on a lost ack (`9e03b3f`). **Benched 2026-11-03** (UM20147 and BE9441,
|
||||
each on its own modem; one send per go):
|
||||
- **Idle, both series:** a no-op, off, and on were each acked and read back,
|
||||
and each unit's own menu agreed. UM20147 accepts `0x00` at `[5]`.
|
||||
- **Monitoring, neither series can change call-home:**
|
||||
- A MiniMate answers the `0x2C` read with its device-info block, so SFM
|
||||
refuses with "stop monitoring first" (`5326e99`).
|
||||
- A Micromate returns the real block and acks the write, but ignores it
|
||||
("Feature disabled while monitoring" on its own menu). SFM now refuses
|
||||
up front, and edits only a block whose header is its own length
|
||||
(`f35845d`).
|
||||
- **Series 4 `[118:120]`:** a function of the block's content (a fixed XOR of
|
||||
`0x6D7D` per bit-0 flip, on two units).
|
||||
- **Batch 1's #9 reconnect worked live:** BE9441's line dropped in the sensor
|
||||
check, and the start was verified.
|
||||
- Details: `docs/micromate_protocol_reference.md` (Bench 2026-11-03) and the
|
||||
Series-III reference's 2026-11-03 row.
|
||||
5. **Setup push** (row 10): one field first, then several.
|
||||
|
||||
Each phase is its own implementation plan. **All phases land on
|
||||
@@ -681,16 +713,21 @@ a short plan; #14 waits for the line-hold decision above.
|
||||
4. List vector sum 0 / −0 for three events whose peaks reach 1.08 in/s --
|
||||
suspected escapes in the `0C` record (not checked).
|
||||
5. Stored S3 event: client "Terra-Mechanic" (last letter missing) -- unexplained.
|
||||
6. Page: the Config tab shows the empty write form until Read in serial mode.
|
||||
6. ✅ **Fixed 2026-11-02 (Batch 2):** by serial the edit form stays hidden and the settings
|
||||
box shows from the start ("Not read yet"); another unit's settings are cleared.
|
||||
Page: the Config tab shows the empty write form until Read in serial mode.
|
||||
7. `/db/events` 500 "database is locked" on the first page load against a new DB.
|
||||
8. ✅ **Fixed `9492e49`**, plus `3a1d34a` ("already stored" also matches the Blastware
|
||||
name: a histogram's row sits a second off its 0C time). The download carries the assembled Blastware file and is
|
||||
stored through `save_imported_bw` (`source.kind` "sfm-live"), and its range scales
|
||||
the samples. The unit's 0C mic is overlaid (the file reads it as 0). Its channel
|
||||
peaks and vector sum were overlaid too until 2026-10-31; since the checker's
|
||||
histogram-PVS fix (625bc39, merged `6945009`) the file's are taken when the unit
|
||||
confirms Normal range, and the unit's stand for Sensitive or an unread range (the
|
||||
file reader assumes Normal: 8x off). The label came with #41 (`a1d2b61`).
|
||||
stored through `save_imported_bw` (`source.kind` "sfm-live"). Since 2026-11-02
|
||||
(after the checker's fixes for the histogram vector sum 625bc39, the mic psi
|
||||
5644dbd and the file's geophone range 4844135) the row and samples are the
|
||||
file's: peaks, vector sum, mic, and the range the event was recorded at (the live
|
||||
1A is the unit's setting *now*, a fallback only when the file's range does not
|
||||
read). The unit's 0C summary is the download check, and fills in peaks only when
|
||||
the file's range does not read and the unit is not confirmed Normal. Until then
|
||||
the unit's 0C values were overlaid (`9492e49`, narrowed `0a87d85`). The label
|
||||
came with #41 (`a1d2b61`).
|
||||
**S3 downloads are stored from the live waveform decoder** (`store.save`), not
|
||||
the file reader that Series 4 uses (`save_imported_idf`): a histogram gets no
|
||||
samples and is labelled Waveform. Fix: store S3 downloads through the
|
||||
@@ -701,10 +738,14 @@ a short plan; #14 waits for the line-hold decision above.
|
||||
**S3 start over a modem:** the line dropped during the sensor check, the
|
||||
read-back hit `Broken pipe` and did not reconnect → 503 though the start
|
||||
worked. Fix: reconnect for the read-back (reads only; the send stays single).
|
||||
10. Page: "Start monitoring failed:" on a sent-but-unconfirmed change -- wording.
|
||||
10. ✅ **Fixed 2026-11-02 (Batch 2):** the start/stop route adds `sent` + `audit_id` to a
|
||||
ChangeUnconfirmed (same status and message); the page says "… not confirmed:".
|
||||
Page: "Start monitoring failed:" on a sent-but-unconfirmed change -- wording.
|
||||
11. S3 stop ~19 s, 11.6 s of it the identity check (a full connect) vs ~1 s for a
|
||||
serial-only read. **Identified only** (speed is secondary to reliability).
|
||||
12. Page, serial mode: the Device tab's empty legacy compliance table; S4
|
||||
12. ✅ **Fixed 2026-11-02 (Batch 2):** by serial the legacy tables are hidden behind a
|
||||
pointer to the Config tab; a Micromate's Firmware reads "Thor line (version not read)".
|
||||
Page, serial mode: the Device tab's empty legacy compliance table; S4
|
||||
Firmware "—" (should say Thor line).
|
||||
13. S4 mic in the event's peaks "0.0 dBL" vs 96.54 dB(L) in the file -- the
|
||||
`0x0C` mic denormal parked above, now visible.
|
||||
@@ -714,14 +755,18 @@ a short plan; #14 waits for the line-hold decision above.
|
||||
**RETRACTED 2026-10-29: not a bug.** `sent` is documented as 1 acknowledged, 0
|
||||
nothing sent, NULL unknown (`sfm/database.py`, `change.py`); a frame answered by a
|
||||
ring instead of its ack is exactly unknown, and the row's `error` says it was sent.
|
||||
16. Page: a 504 on a unit THOR holds should say "connected, but no reply --
|
||||
16. ✅ **Fixed 2026-11-02 (Batch 2):** a 504 with nothing sent adds "the connection opened,
|
||||
so the modem is reachable — another program (THOR or Blastware) may be holding
|
||||
this unit's line, or the unit is busy".
|
||||
Page: a 504 on a unit THOR holds should say "connected, but no reply --
|
||||
another program may be holding this unit's line".
|
||||
17. **Found by the Batch 1 review (open):** a MiniMate downloaded *while monitoring*
|
||||
answers 1A with its device-info block, so no range is read and the stored
|
||||
`.h5` samples assume Normal -- 8x off on a sensitive-range unit (the row's
|
||||
peaks are the unit's, overlaid). Pre-existing on the old path too. The same
|
||||
reply decodes a setup name of `:S338.17`. Live S3 downloads also no longer
|
||||
keep the `.a5.pkl` wire record.
|
||||
17. ✅ **Range part fixed 2026-11-02:** a MiniMate downloaded *while monitoring*
|
||||
answers 1A with its device-info block, so no range was read and the stored
|
||||
`.h5` samples assumed Normal -- 8x off on a sensitive-range unit. The range now
|
||||
comes from the event file itself (measured: K557J1KB.RQ0W stores 0.019 / 0.055 /
|
||||
0.019, Blastware's report, with the settings unread). Still open: the same reply
|
||||
decodes a setup name of `:S338.17`, and live S3 downloads no longer keep the
|
||||
`.a5.pkl` wire record.
|
||||
- **Same-second collisions (SDM).** Two events of one unit in the same second collide on (serial, timestamp) — a DB-wide dedup property, not 1b's.
|
||||
- **423 without `Retry-After` (1c).** Add `Retry-After` to the 423 a request gets while a download holds the unit.
|
||||
- **A lost `0C` during a Series-3 list (1c).** The strict walk raises on a lost `0A`
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
# Phase 5: changing a unit's settings by serial (design)
|
||||
|
||||
**Date:** 2026-11-03. **Status:** approved by Brian 2026-11-03; built 2026-11-03
|
||||
(plan `docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md`); **benched 2026-11-04** on both
|
||||
series (results at the end). Phase 5 of
|
||||
`docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` (row 10, "change
|
||||
recording settings"; build phase 5, "setup push: one field first, then several").
|
||||
**Branch:** `feat/series4-sfm-parity`.
|
||||
|
||||
## Intent (Brian, 2026-11-03)
|
||||
|
||||
Change **any** of a unit's settings from SFM, and make it as easy and reliable as
|
||||
possible. The goal is to fix what makes Blastware finicky. Three real cases:
|
||||
|
||||
- **One wrong number on a deployed unit.** UM6047 was out monitoring with its
|
||||
geophone trigger at 0.03 instead of 0.300. Brian remoted into the THOR PC,
|
||||
stopped it (it called in), changed the setup, made sure it was *sent*, then
|
||||
restarted monitoring.
|
||||
- **A typo in the notes.**
|
||||
- **A backup unit.** The unit set up at the office fails in the field, so a backup
|
||||
from the truck goes in with blank or stale notes and settings. There is no
|
||||
computer in the field, so the office re-does the whole setup remotely, by hand,
|
||||
while the person in the field stands by to press Start or power-cycle if the
|
||||
link breaks.
|
||||
|
||||
What is wrong with THOR, as Brian and his dad experience it:
|
||||
|
||||
- The same screen edits a setup on disk and views a unit's setup.
|
||||
- Setups get saved under random number strings.
|
||||
- Editing a setup does not change the unit; you verify separately that it was sent.
|
||||
|
||||
Saved setups as templates would be acceptable. Not knowing whether you are
|
||||
changing the unit or a file is not.
|
||||
|
||||
## Goals, non-goals, anti-goals
|
||||
|
||||
**Goals**
|
||||
|
||||
- Edit the unit's **live** settings, both series.
|
||||
- Show exactly what will change, **old → new**, before anything is sent.
|
||||
- After sending, **re-read the unit** and show what it now holds.
|
||||
- Make every refusal say why, in plain words.
|
||||
|
||||
**Non-goals (this phase)**
|
||||
|
||||
- Templates, saved setups, copying from another unit.
|
||||
- Restarting monitoring. **Brian presses Start**, as today; SFM never restarts on
|
||||
its own.
|
||||
- Setting the unit's clock. That is a later call-home receiver rule.
|
||||
- **Writing the Micromate scheduler.** Next project, agreed 2026-11-03:
|
||||
"record during work hours" as a plain, **configurable** setting on the unit's
|
||||
page, both series, no schedule library and no setup files. On the Micromate,
|
||||
it relies on the firmware's setup-less scheduler start (found in the firmware,
|
||||
never sent; one bench session). On the MiniMate, its own timer setting
|
||||
(undecoded). Brian's dad despises THOR's scheduler; Brian is willing to retire
|
||||
it in SFM.
|
||||
- Fields not yet decoded. "Any and all" grows as decoding grows.
|
||||
|
||||
**Anti-goals: things that would make it a failure even if it "works"**
|
||||
|
||||
- Any doubt about whether the unit changed.
|
||||
- A screen where a file and a unit look alike, or a name SFM made up.
|
||||
- Writing a byte SFM did not just read. Every byte SFM does not deliberately change
|
||||
goes back exactly as read. The one exception is a byte that Blastware's (or
|
||||
THOR's) own writes always set to a fixed value. Each such byte is named in the
|
||||
codec with its evidence (so far: Series 3 `[26:28]` → `00 00`; my call, below).
|
||||
- Sending to a monitoring unit.
|
||||
- A retry. A write is sent once; what happened is read back.
|
||||
|
||||
## Measured basis
|
||||
|
||||
**1. Series 4 (Micromate): the `0x1A` setup content map.** Measured from 47
|
||||
keypad snapshots on UM20147 and checksum-verified. `micromate/setup_block.py`
|
||||
(`decode_setup`) reads it, with 69 tests on 15 fixtures.
|
||||
|
||||
| content | field |
|
||||
|---|---|
|
||||
| `[5]` | record mode |
|
||||
| `[6:8]` | sample rate |
|
||||
| `[8:10]` | histogram interval |
|
||||
| `[12:16]` | pre-trigger, f32, negative |
|
||||
| `[17]` | stop mode |
|
||||
| `[18:22]` | record time, f32 |
|
||||
| `[23]` | auto-stop |
|
||||
| `[25]` | active sensors |
|
||||
| `[29]` | trigger sources |
|
||||
| `[30:34]` | distance |
|
||||
| `[34:38]` | charge |
|
||||
| `[39]` | report flags |
|
||||
| `[40:42]` | job number |
|
||||
| `[42:86]` | setup name |
|
||||
| `[122+64n]` / `[144+64n]` | notes (label / value) |
|
||||
| from `[1708]` | 48-byte channel blocks: sensor code `+4:8`, trigger `+30` (geo in/s, mic psi) |
|
||||
|
||||
The CRC-16/AUG-CCITT over `[0:2088]` is stored at `[2090:2092]`; THOR's write
|
||||
omits it and the unit recomputes it.
|
||||
|
||||
- **The push sequence (from THOR's captures)** is `0xDA` (name) → `0x68`/`0x73`
|
||||
(`0x08` preferences) → `0x82`/`0x83` (`0x2E` trigger) → `0x71`/`0x72` (`0x1A`
|
||||
setup). `micromate.writes.plan_setup_push` reproduces THOR's frames (phase 2).
|
||||
- **Not yet mapped on Series 4:** alarm level, geophone range, GPS, aux I/O, SLM
|
||||
options.
|
||||
|
||||
**2. Series 3 (MiniMate) uses the same layout. Measured 2026-11-03.** The
|
||||
compliance image as Blastware writes it is logical (unescaped), 2,092 bytes, with
|
||||
`N = 2090` at `[0:2]` and the channel block "Tran" at `[1708]`.
|
||||
`micromate.setup_block.decode_setup` reads it correctly:
|
||||
|
||||
- **BE9441's 10-26 write** (`tests/fixtures/minimate-bench-10-26-26-histogram`,
|
||||
two whole sends): name, mode, 4096 sps, interval, record time 20 s, trigger
|
||||
0.04 in/s, mic linear, job number and the notes all decode. Only the CRC fails
|
||||
(Series 3's tail goes out stale).
|
||||
- **BE11529's nine 2026-04-20 Blastware writes** (`bridges/captures/4-20-26/`,
|
||||
every one with a whole image) each changed exactly the expected bytes:
|
||||
|
||||
| Blastware changed | bytes that moved |
|
||||
|---|---|
|
||||
| histogram interval (×4) | `[8:10]` |
|
||||
| recording mode (×3) | `[5]` |
|
||||
| geophone range | `1737` / `1785` / `1833`, the range byte at each geophone channel label `+29` |
|
||||
|
||||
- **The live `SUB 1A` read starts the same block.** Measured on the first data
|
||||
frame of each of the four recorded reads (`_settings_replies` in
|
||||
`tests/test_s3_compliance_anchor_fields.py`): unescaped, each carries `N = 2090`
|
||||
12 bytes before the old "anchor", and content `[5]` reads 1 / 4 / 3 / 3. That
|
||||
anchor (`be 80 00 00 00 00`) is content `[12:18]`, pre-trigger −0.25 plus stop
|
||||
mode Fixed. So Series 3 can be read by content offset rather than by anchor
|
||||
search, which survives an Auto-stop unit (the open question of 2026-10-17).
|
||||
- **A whole `1A` read assembles to exactly the 2,090 content bytes** (measured
|
||||
2026-11-03 on BE9441's 10-26 recording, 12 reads). Unescape each data frame and
|
||||
take `data[11:]`. Every frame but the last then starts with one `00` byte that is
|
||||
not content; drop it. This holds for Blastware's read (four 512-byte frames plus
|
||||
42) and SFM's (two 1024-byte frames plus 42).
|
||||
- **The round trip is exact.** Blastware re-read the block after each of its two
|
||||
writes, and each re-read equals the image it had just written, all 2,090 bytes.
|
||||
- **While monitoring**, the read returns `0e 'BE9441' …` (the device-info block),
|
||||
as the 10-29 finding says. The unit was monitoring for 5 of the 12 reads.
|
||||
- **Bytes `[26:28]`: Blastware always writes `00 00`** (all 11 writes), though the
|
||||
unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19).
|
||||
The unit sets them again by itself. Meaning unknown.
|
||||
- **The two bytes after the block are Blastware's own.** Blastware sends a per-unit
|
||||
constant: `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's.
|
||||
It is not the block's CRC-16/AUG, and no reply in BE9441's three-hour session
|
||||
contains it. SFM's `write_image` sends `00 00` there. Since a read never returns
|
||||
those bytes, the read-back cannot show what the unit did with them.
|
||||
- **The mode byte is shared, but its codes are not.** Series 3: `00` Single Shot,
|
||||
`01` Continuous, `03` Histogram, `04` Histogram + Continuous. Series 4: `01`
|
||||
Waveform, `02` Manual, `03` Histogram, `04` Combo.
|
||||
- **Rules from the checker's file-side work** (seismo-relay-b6, 2026-11-03; it
|
||||
measured the same content offsets on 70,042 event files and found nothing that
|
||||
contradicts one shared map):
|
||||
- A bitmask byte is patched **bit by bit, never rebuilt**. The trigger-sources
|
||||
byte `[29]` showed an unidentified `0x80` bit on one unit.
|
||||
- On Series 3, stop mode (`0` Fixed) and mic type (`2` linear) are proven for
|
||||
one value each. They are not offered for writing.
|
||||
- An event file's `[12:16]` is that event's captured pre-trigger, not the
|
||||
setting. SFM writes only from a live read, so this matters only to anyone
|
||||
tempted to build a write from a file.
|
||||
- **Series-3-only fields** (measured on Series 3, not Series 4): the geophone range
|
||||
byte at channel `+29`; the alarm level at channel `+38` (checker-measured on
|
||||
event files; live raw `+42`).
|
||||
|
||||
**3. Series 3 write frames are measured (#46).** Writes use uniform escaping with
|
||||
a length field. The compliance image goes in 512-byte addressed chunks. `0x68` is
|
||||
written as read plus `02 00`, `0x82` plus `00 00`. The sequence is
|
||||
`68→73 | 71×n→72 | 82→83 | 69→74→72`. `push_config_raw` refuses any block that
|
||||
is not whole. `tests/test_minimate_write_frames.py` rebuilds Blastware's frames
|
||||
byte for byte.
|
||||
|
||||
**4. Monitoring.**
|
||||
|
||||
- **Series 3:** while monitoring, the unit answers `1A` (and `0x2C`) with its
|
||||
device-info block (measured 10-29 and 11-03).
|
||||
- **Series 4:** it refuses call-home setup while monitoring ("Feature disabled
|
||||
while monitoring", measured 11-03).
|
||||
- **A stop with call-home on makes the unit call in** (measured 10-25, 10-29,
|
||||
11-03).
|
||||
|
||||
**5. Series 4 specifics.**
|
||||
|
||||
- `0x1A` reads the keypad's edit buffer live: unsaved keypad edits show in the
|
||||
read, and a push would commit them.
|
||||
- Loading a `.MMB` replaces the active config byte for byte. The push writes
|
||||
under the active setup's name (`0xDA`).
|
||||
|
||||
## The flow
|
||||
|
||||
1. **Read.** `GET /device/settings?serial=…` (it exists) returns the unit's
|
||||
settings. The page shows them on the Config tab under **"On the unit BE9441 —
|
||||
read 14:03"**, never anything that looks like a file.
|
||||
2. **Edit and preview.** The operator changes fields, then **Preview**: a dry run.
|
||||
SFM re-reads the unit's blocks on the same line, builds the new blocks, and
|
||||
returns one row per field: **old → new**, plus any warnings. Nothing is sent.
|
||||
3. **Send.** The same request, live, is an audited change:
|
||||
- identity check, audit row, one send, never retried, read back;
|
||||
- **refused with "stop monitoring first"** if the unit is monitoring, noting
|
||||
that the stop makes it call in when call-home is on;
|
||||
- **refused** if the unit's settings changed since the preview. The preview
|
||||
carries a revision (a hash of the blocks read), and the live call must
|
||||
match it.
|
||||
4. **Verify.** Re-read the blocks. Every changed field must read its new value.
|
||||
Every other decoded field, and every byte SFM did not deliberately change, must
|
||||
read as before. The page shows **"the unit now holds"**: field, old, new, now.
|
||||
Known unit-maintained bytes (the Series-4 CRC) are compared as the unit's own
|
||||
checksum (`crc_ok`), not byte for byte.
|
||||
5. **Start** stays the operator's button.
|
||||
|
||||
## Fields in the first version (Brian approved the list)
|
||||
|
||||
| field | Series 3 | Series 4 |
|
||||
|---|---|---|
|
||||
| geophone trigger level | yes (channel `+30`) | yes (channel `+30`) |
|
||||
| alarm level | yes (channel `+38`; measure live) | not mapped, so not offered |
|
||||
| notes: the four note slots, by the unit's own labels | yes (`Project:`, `Client:`, `User Name:`, `Seis. Loc:` on BE9441) | yes (`Location`, `Client`, `Company`, `General Notes`) |
|
||||
| recording mode | yes (`[5]`; values as measured on Series 3) | yes (`[5]`; Series-4 codes) |
|
||||
| sample rate | yes | yes |
|
||||
| record time | yes | yes |
|
||||
| histogram interval | yes | yes |
|
||||
| geophone range | yes (channel `+29`) | not mapped, so not offered |
|
||||
| job number (+ shown on report) | yes | yes |
|
||||
|
||||
A field is offered only where it is measured for that series. Values are refused
|
||||
unless they are among the measured choices: sample rates 1024/2048/4096,
|
||||
intervals 2/5/15/60/300/900 s, and each series' measured mode codes.
|
||||
|
||||
- **Numbers: the units' own limits (Brian, 2026-11-03: "I want to use the actual
|
||||
unit limits, not just what we have done in the past").** From Instantel's
|
||||
operator manuals in `~/seismo-relay/manuals/`:
|
||||
- **Geophone trigger:** 0.005–10 in/s in steps of 0.001 (MiniMate Plus manual
|
||||
716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual
|
||||
721U0201 Rev 06, *Geophone Trigger Level*). It is also capped at the range's
|
||||
full scale (10 / 1.25 in/s). When range and trigger change in one request,
|
||||
check the trigger against the **new** range.
|
||||
- **Record time:**
|
||||
- Micromate: 1–90 s (*Record Time*).
|
||||
- MiniMate: from 1 s to the manual's §4.4 *Maximum Record Times* for a
|
||||
1 MB unit, four channels, at the chosen sample rate: 104 s at 1024 sps,
|
||||
52 s at 2048, 26 s at 4096. In Histogram Combo, 13 s (§3.8.9). The units
|
||||
measured report about 960 KB in total memory (BE11529: 983,026 bytes), the
|
||||
1 MB model.
|
||||
- **Job number:** 1–9999 (both manuals).
|
||||
- **The read-back is the safety net.** A unit that does not take a value (for
|
||||
instance, cuts a record time to what its memory allows) shows as not taken,
|
||||
with what it actually holds.
|
||||
- Values seen across 75,958 Blastware reports (2016–2026) sit well inside these
|
||||
limits: trigger 0.005–0.500 in/s, record time 1–10 s, job number 1.
|
||||
- **Units:** refuse a level write unless the channel's unit string reads the
|
||||
measured one (`in.` for a geophone). A unit set to Metric is unmeasured.
|
||||
- **Notes:** edited by slot, under the label the unit itself shows (labels can be
|
||||
renamed and are not identifiers). The value is at most its field width less
|
||||
one byte, printable ASCII.
|
||||
- Not in v1: Series 3's fifth slot, `Extended Notes` (value `\n` on BE9441).
|
||||
Blastware's extended notes are unmeasured and may live elsewhere.
|
||||
- Not in v1: Series 4's 16-byte field at content `[1064]` (`Loc 1` on
|
||||
UM12947), undecoded.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **One setup-block codec for both series.** Keep `micromate/setup_block.py` as
|
||||
the field map and add `encode_setup(content, changes) -> content`: field patches
|
||||
only, every other byte as given. It stays a pure codec library: no I/O, no
|
||||
`sfm` imports, no import cycle with `minimateplus`. Series-specific fields (the
|
||||
Series-3 range and alarm) are marked by series.
|
||||
- **Series 3 read.** Assemble the `1A` read into the logical 2,090-byte block:
|
||||
unescape, strip the 12-byte reply prefix and the inter-frame headers
|
||||
(`read_compliance_config`). Decode it by content offset.
|
||||
- **Series 3 write.** The patched logical block plus the tail becomes the
|
||||
compliance image for `push_config_raw`. Event index (`0x08`), trigger (`0x2E`)
|
||||
and waveform data (`0x09`) are echoed as read, in Blastware's sequence.
|
||||
- On `0x09`, Blastware echoed the unit's bytes on all nine April writes
|
||||
(`[200:202]` = `8c 76` read and written). Only BE9441's 10-26 writes changed
|
||||
them (`17 17` read, `78 76` written, and read back so). The meaning is
|
||||
unknown, so SFM echoes.
|
||||
- **The raw-offset `_encode_compliance_config` is retired.**
|
||||
- **The legacy write (`/device/config`, `/device/config/project`) is retired (my
|
||||
call).** It retries a whole write on a TCP error, is not audited, does no
|
||||
read-back, does not refuse a monitoring unit, and needs no serial: every
|
||||
anti-goal at once. Its only user is the webapp's by-host Config form, and
|
||||
Terra-View does not call it. Its routes answer with a pointer to the by-serial
|
||||
change, and the by-host form becomes read-only.
|
||||
- **Series 4 write.** `plan_setup_push(prefs, trigger, patched_setup, name)`.
|
||||
- **No setup files in the operator's view (Brian, 2026-11-03).** "We treat the
|
||||
Micromate setups just like Minimate setups … the unit just has its settings,
|
||||
and we change it based on the job. We don't send setups to the unit." A
|
||||
backup unit is usually on whatever setup its previous job left. So SFM
|
||||
rewrites the setup the unit is running, in place, under its own name. It
|
||||
never asks for a file or a name, and never creates one. The name may show as
|
||||
a read-only detail, since the unit's screen shows it.
|
||||
- **The scheduler can undo a change (Brian, 2026-11-03, with THOR's Manage
|
||||
Schedules screen).** Work-hours Micromates run a THOR schedule, e.g. Start
|
||||
Monitoring 07:00 with setup `Mele-PWSA-Carroll -Loc 4`, stop 18:30, repeat
|
||||
daily. THOR sends the schedule with its setup, and each scheduled start loads
|
||||
the setup it names. So the preview and the send read `schedule.dat` (format
|
||||
decoded, reference *The schedule record format*), read-only. A start action
|
||||
naming a setup other than the one being changed blocks the send: "this unit's
|
||||
schedule loads <name> at 07:00, which would replace this change." When the
|
||||
schedule names the active setup (the usual case after a scheduled start), the
|
||||
change survives, and the preview says when the next scheduled start is.
|
||||
SFM never writes the schedule in this phase.
|
||||
- The name comes from the `0x41` read, unstripped.
|
||||
- Refuse `factory.MMB` and any target that is not the active setup (spec). The
|
||||
refusal says it plainly: "this unit is running its factory setup; load any
|
||||
other setup on its keypad, then try again." Brian says the team does not use
|
||||
the factory setup, so this should be rare.
|
||||
- `ENABLEABLE_WRITES` gains `0xDA 0x68 0x73 0x82 0x83 0x71 0x72`.
|
||||
- The keypad edit buffer: warn in the preview that a unit with someone in its
|
||||
menu would have those edits committed. The check the spec names, `0x1A`
|
||||
against the active `.MMB` via `0x94`/`0x48`, is a bench question first.
|
||||
- **The change path.** It keeps run_change's guarantees: identity, audit, one
|
||||
send, read back, `ChangeUnconfirmed` with `sent`/`audit_id`. The "state" is a
|
||||
set of fields, so either `run_change` takes a verify function or a sibling core
|
||||
shares its parts. The builder decides; the guarantees do not change. The audit
|
||||
row keeps the per-field changes, both blocks (hex) and the verdict.
|
||||
- **Routes.** `POST /device/settings/change?serial=…` (serial required) with body
|
||||
`{changes: {field: value}, revision}` and `dry_run`, `caller`. The response is
|
||||
per-field `old` / `new` / `now`, through `_change_response`. A dry run needs no
|
||||
revision and returns one. **A live call without the revision of a preview is
|
||||
refused** (my call): nothing reaches a unit unless someone saw old → new.
|
||||
- **Page.** The Config tab by serial becomes the unit's edit form: Preview → Send
|
||||
(confirm) → "the unit now holds". New logic goes in
|
||||
`sfm/static/device_routing.js` with Node tests, and glue in
|
||||
`sfm/static/sfm_webapp.js` (no inline JS).
|
||||
|
||||
## Verification
|
||||
|
||||
- **Series 3, byte for byte.** For each of the 11 Blastware compliance writes,
|
||||
apply the new encoder to the read before it (or the previous image), with the
|
||||
fields Blastware changed. It must reproduce Blastware's content `[0:2090]`. The
|
||||
two trailing bytes are compared separately, since they are Blastware's constant.
|
||||
Ten writes change one field. BE9441's 16:26 write changes five things: mode,
|
||||
sample rate 2048 → 4096, interval, the mic in the sensors byte `[25]`, and
|
||||
`[26:28]`. That one is tested with all of them, through the codec, though v1's
|
||||
page does not offer the sensors byte.
|
||||
The frames rebuild through `push_config_raw`'s path (the #46 tests).
|
||||
- **Series 3, read side.** The assembly rule above, pinned as a test on the 12
|
||||
reads of BE9441's 10-26 recording. Each read-back equals the write before it.
|
||||
- **Series 4.** THOR's setup-push captures still reproduce, with no field changed.
|
||||
Any capture where THOR changed a field becomes a byte-for-byte test.
|
||||
- **Bench, with Brian's go per send, per series:**
|
||||
1. A dry run of a trigger change, then send, read back, check the unit's menu,
|
||||
and change it back.
|
||||
2. A notes change.
|
||||
3. A several-field "backup unit" change.
|
||||
4. A dry run while monitoring, expecting the refusal.
|
||||
|
||||
## Bench 2026-11-04 (results)
|
||||
|
||||
Brian at BE9441 and UM20147, each on its own modem; every send with his go.
|
||||
Notes: `~/bench-logs/2026-11-04-sfm-settings/`.
|
||||
|
||||
- **Both series change correctly.** Each change was acknowledged, read back as
|
||||
sent, and confirmed on the unit's own screen; both units ended byte for byte as
|
||||
found.
|
||||
- BE9441: trigger each way, a note, several fields at once, the alarm, a full
|
||||
restore.
|
||||
- UM20147: trigger, several fields (two notes, job number and its flag, record
|
||||
time), a full restore. The unit's recomputed CRC equalled SFM's.
|
||||
- **Fixed at the bench (`9992b25`):** the first live MiniMate read came back one
|
||||
byte long. An escaped checksum byte leaves its `0x10` behind (about 1 frame in
|
||||
85; the recordings never had it). The read now takes exactly the lengths it
|
||||
asked for, and so does the waveform read (`c790e20`).
|
||||
- **🔑 The keypad menu wins.** A MiniMate change sent while its setup menu is
|
||||
open is acknowledged and read back, then lost when the operator presses Cancel
|
||||
or Save: the menu writes its copy of the whole block back. SFM cannot see this
|
||||
happen; the MiniMate preview now warns. Rule for the field-plus-office routine:
|
||||
nobody in the unit's menus while the office sends.
|
||||
- **The MiniMate alarm write is measured**, so it is now writable (`55c7b7b`).
|
||||
- **Refused while recording, both series, nothing sent.** A recording MiniMate
|
||||
sometimes leaves a preview at "no answer" rather than the refusal.
|
||||
- **The Micromate scheduler switch is in no block SFM reads.** UM20147 carries a
|
||||
leftover THOR schedule (Fay setup, 07:00 daily) with the switch Off; SFM blocks
|
||||
it, a false alarm here. The bench used a scratch-only override.
|
||||
- Next: a THOR bridge recording to find the switch (parked for work hours).
|
||||
- Meanwhile, worth considering: let the operator confirm "scheduler off" in the
|
||||
preview.
|
||||
|
||||
## Calls I made (Claude), for Brian to check
|
||||
|
||||
- **Series 3 `[26:28]` goes out as `00 00`, as Blastware writes it**, rather than
|
||||
the `01 7f` the unit may read. Measured beats inferred: Blastware's value is on
|
||||
11 accepted writes, and writing back `01 7f` has never been tried.
|
||||
- **The two bytes after the Series 3 block stay `00 00`**, as `write_image` sends
|
||||
them (a unit accepted that in the April 2026 test). Blastware's per-unit
|
||||
constant cannot be derived from anything SFM reads. The first bench write checks
|
||||
that the unit takes the block, and its menu shows the change.
|
||||
- **The `0x09` block is echoed as read**, as Blastware did on all nine April writes.
|
||||
- **Level writes are refused unless the channel's unit string is the measured
|
||||
`in.` / `in`** (a unit set to Metric is unmeasured).
|
||||
- **Notes are edited by slot under the unit's own labels**, four slots on each
|
||||
series. Series 3 extended notes and Series 4's separate location field wait.
|
||||
- **The legacy by-host write is retired**; the by-host form becomes read-only.
|
||||
- **A live send needs a preview's revision.**
|
||||
- **Preview re-reads the unit** rather than trusting the page's copy, and Send
|
||||
refuses if the unit changed since the preview.
|
||||
- **The edit form lives on the Config tab, by serial**, replacing the legacy
|
||||
read-modify-write form for units reached by serial.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The module layout for the shared codec, within the no-cycle, pure-codec rule.
|
||||
- `run_change` generalised versus a sibling core.
|
||||
- The exact revision hash.
|
||||
- Page layout details.
|
||||
-107
@@ -60,7 +60,6 @@ from minimateplus.framing import build_bw_frame, SESSION_RESET
|
||||
from minimateplus.client import (
|
||||
MiniMateClient,
|
||||
_decode_compliance_config_into,
|
||||
_encode_compliance_config,
|
||||
)
|
||||
from minimateplus.models import DeviceInfo
|
||||
|
||||
@@ -462,111 +461,6 @@ def exp_fewer_polls(host: str, port: int) -> tuple[str, str, dict]:
|
||||
t.disconnect()
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
# EXP6 — Compliance-only write (71×3→72), skip event index + trigger + waveform
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
#
|
||||
# Blastware's full write sequence: 68→73 | 71×3→72 | 82→83 | 69→74→72
|
||||
# We want to know: can we write ONLY the compliance block (71×3→72)?
|
||||
#
|
||||
# Test procedure:
|
||||
# 1. Read current compliance config (SUB 1A)
|
||||
# 2. Patch the "notes" field to a test marker
|
||||
# 3. Write ONLY 71×3→72 (skip 68, 73, 82, 83, 69, 74, final 72)
|
||||
# 4. Read back (SUB 1A) and verify the change was written
|
||||
# 5. Restore original value
|
||||
#
|
||||
# If PASS: we can push individual config fields without touching event index,
|
||||
# trigger config, or waveform data — huge simplification.
|
||||
# If FAIL: the device needs the full write sequence (may reject partial write).
|
||||
#
|
||||
# SAFETY: We restore original data in a finally block. If the restore write
|
||||
# fails, the device will have the test marker in "notes" — harmless but visible.
|
||||
|
||||
_EXP6_MARKER = "[exp6-test]"
|
||||
|
||||
def exp_compliance_only(host: str, port: int) -> tuple[str, str, dict]:
|
||||
"""Write compliance block alone (71×3→72), verify, and restore."""
|
||||
client, info = connect_client(host, port)
|
||||
original_raw: Optional[bytes] = None
|
||||
try:
|
||||
proto = client._proto
|
||||
if proto is None:
|
||||
return "FAIL", "Could not get protocol handle from client", {}
|
||||
|
||||
# 1. Read current compliance
|
||||
print(" Reading current compliance config (SUB 1A)…")
|
||||
original_raw = proto.read_compliance_config()
|
||||
print(f" Got {len(original_raw)} bytes of compliance config")
|
||||
|
||||
# Find current notes value for display
|
||||
info_obj = DeviceInfo()
|
||||
_decode_compliance_config_into(original_raw, info_obj)
|
||||
cc = info_obj.compliance_config
|
||||
orig_notes = cc.notes if cc else "(unknown)"
|
||||
print(f" Current notes field: {orig_notes!r}")
|
||||
|
||||
# 2. Build modified payload with test marker in notes
|
||||
test_notes = _EXP6_MARKER
|
||||
modified_raw = _encode_compliance_config(
|
||||
original_raw,
|
||||
notes=test_notes,
|
||||
)
|
||||
print(f" Encoded modified compliance payload ({len(modified_raw)} bytes)")
|
||||
print(f" Patching notes: {orig_notes!r} → {test_notes!r}")
|
||||
|
||||
# 3. Write ONLY the compliance block: 71×3 → 72
|
||||
print(" Writing compliance ONLY (71×3→72) — skipping 68/73/82/83/69/74…")
|
||||
proto.write_compliance_config_raw(modified_raw)
|
||||
print(" Write complete — device acked 71×3→72")
|
||||
|
||||
# 4. Read back and verify
|
||||
print(" Reading back compliance config to verify…")
|
||||
readback_raw = proto.read_compliance_config()
|
||||
readback_info = DeviceInfo()
|
||||
_decode_compliance_config_into(readback_raw, readback_info)
|
||||
rb_cc = readback_info.compliance_config
|
||||
readback_notes = rb_cc.notes if rb_cc else "(decode failed)"
|
||||
print(f" Read-back notes: {readback_notes!r}")
|
||||
|
||||
write_worked = (readback_notes == test_notes)
|
||||
print(f" Write verified: {write_worked}")
|
||||
|
||||
details = {
|
||||
"original_notes": orig_notes,
|
||||
"written_notes": test_notes,
|
||||
"readback_notes": readback_notes,
|
||||
"write_verified": write_worked,
|
||||
}
|
||||
|
||||
if write_worked:
|
||||
return "PASS", "Compliance-only write works! No event index or trigger writes needed.", details
|
||||
else:
|
||||
return "FAIL", f"Write was not reflected in read-back (got {readback_notes!r})", details
|
||||
|
||||
except ProtocolError as exc:
|
||||
return "FAIL", f"Protocol error: {exc}", {}
|
||||
|
||||
finally:
|
||||
# Restore original compliance data regardless of outcome
|
||||
if original_raw is not None:
|
||||
print(" Restoring original compliance config…")
|
||||
try:
|
||||
proto2 = client._proto
|
||||
if proto2:
|
||||
proto2.write_compliance_config_raw(
|
||||
_encode_compliance_config(original_raw) # no-op patch = verbatim
|
||||
)
|
||||
print(" Restore complete")
|
||||
else:
|
||||
print(" WARNING: protocol handle gone — could not restore")
|
||||
except Exception as exc_r:
|
||||
print(f" WARNING: restore failed: {exc_r}")
|
||||
client.close()
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
# Registry + main
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
EXPERIMENTS = {
|
||||
@@ -575,7 +469,6 @@ EXPERIMENTS = {
|
||||
"no_5a": ("EXP3", exp_no_5a, "Event record (0C) without bulk waveform (5A)"),
|
||||
"skip_1e": ("EXP4", exp_skip_1e, "0A/0C with cached key — skip initial 1E"),
|
||||
"fewer_polls": ("EXP5", exp_fewer_polls, "1 POLL before 5A instead of Blastware's 3"),
|
||||
"compliance_only": ("EXP6", exp_compliance_only, "Compliance-only write (71×3→72), no other blocks"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ from .models import (
|
||||
MicromateState,
|
||||
)
|
||||
from .protocol import MicromateProtocol, ProtocolError
|
||||
from .schedule import SCHEDULE_PATH
|
||||
from .setup_block import decode_setup
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -333,6 +334,28 @@ class MicromateClient:
|
||||
"""`SUB 0x41` — the loaded `.MMB` file name, e.g. `TEST1.mmb`."""
|
||||
return _cstring(_content(self._proto.read_active_setup_name()))
|
||||
|
||||
def get_active_setup_raw(self) -> str:
|
||||
"""The `0x41` name exactly as stored, up to its NUL -- NOT stripped, so a
|
||||
setup push writes back the very name the unit holds."""
|
||||
return _content(self._proto.read_active_setup_name()).split(b"\x00")[0].decode("ascii", "replace")
|
||||
|
||||
def get_prefs_content(self) -> bytes:
|
||||
"""`SUB 0x08` -- the preferences block's content (a setup push sends it back)."""
|
||||
return _content(self._proto.read_event_index())
|
||||
|
||||
def get_trigger_content(self) -> bytes:
|
||||
"""`SUB 0x2E` -- the trigger block's content (a setup push sends it back)."""
|
||||
return _content(self._proto.read_trigger_config())
|
||||
|
||||
def get_setup_content(self) -> bytes:
|
||||
"""`SUB 0x1A` -- the setup block's content, undecoded (2,092 B, CRC last).
|
||||
⚠ The keypad's edit buffer: unsaved menu edits come back too."""
|
||||
return _content(self._proto.read_compliance_config())
|
||||
|
||||
def read_schedule(self) -> bytes:
|
||||
"""`schedule.dat`, read-only (`micromate.schedule.parse_schedule` reads it)."""
|
||||
return self._proto.read_file(SCHEDULE_PATH)
|
||||
|
||||
def get_setup(self, *, verify: bool = True) -> MicromateSetup:
|
||||
"""`SUB 0x1A` — what the unit is set to, decoded. One read.
|
||||
|
||||
@@ -388,6 +411,11 @@ class MicromateClient:
|
||||
# Anything else reads unknown(0x..): the safe default, which the change path refuses.
|
||||
_RUN_STATES = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
|
||||
|
||||
def get_call_home_content(self) -> bytes:
|
||||
"""The `0x2C` call-home block's 126-byte content (bit 0 of [5] is the
|
||||
enable, [6:46] the dial string; [118:120] is unit-maintained)."""
|
||||
return _content(self.protocol.read_call_home_config())
|
||||
|
||||
def read_run_state(self) -> MicromateRunState:
|
||||
"""`SUB 0x49` -> the unit's run state, with the in-call-home value kept
|
||||
(connect()'s `monitoring` bool flattens 0x03 into True)."""
|
||||
|
||||
@@ -84,8 +84,12 @@ READ_SUBS: Mapping[int, str] = MappingProxyType(_READ_SUBS)
|
||||
# The write SUBs any code may transmit at all -- through MicromateProtocol.execute,
|
||||
# one call at a time. Raising this is a spec change, reviewed like one: delete
|
||||
# (0xA8/0xAA), raw file writes (0x8D/0x8E -- they could reach the modem
|
||||
# settings) and 0xA2 never belong here without one.
|
||||
ENABLEABLE_WRITES = frozenset({0x96, 0x97})
|
||||
# settings) and 0xA2 never belong here without one. Phase 4 (2026-11-02) added
|
||||
# the call-home write and its confirm (spec row 9: enable/disable only).
|
||||
# Phase 5 (2026-11-03) added the setup push -- name, preferences, trigger and setup
|
||||
# blocks with their confirms -- for changing a unit's settings by serial (spec row 10).
|
||||
ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F,
|
||||
0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72}) # + the setup push (phase 5)
|
||||
|
||||
|
||||
class OpcodeRefused(RuntimeError):
|
||||
|
||||
@@ -93,6 +93,8 @@ SUB_STATE = 0x49
|
||||
SUB_BULK_DOWNLOAD = 0x5A
|
||||
SUB_POLL = 0x5B
|
||||
SUB_ARM_EVENT = 0x93
|
||||
SUB_FILE_READ_NEXT = 0x48 # file transfer: next page of the file opened by 0x94
|
||||
SUB_FILE_OPEN_READ = 0x94 # file transfer: open a file by path, for reading
|
||||
|
||||
# ⚠ Reads are SINGLE-STEP. Series III probes at offset 0 to learn the length,
|
||||
# then reads again at that length; a Micromate returns the whole block when
|
||||
@@ -102,6 +104,10 @@ READ_ALL = 0xFFFF
|
||||
|
||||
# The two commands that do NOT use READ_ALL, and the data length each returned
|
||||
# on UM12947 (firmware 11.0CB).
|
||||
_FILE_OPEN_PARAMS = bytes([0, 0, 0, 1, 0, 0, 0, 0, 0, 0])
|
||||
_FILE_FIRST_PAGE_PARAMS = bytes([0, 0, 0, 0, 0, 0, 0, 1, 0, 0])
|
||||
_MAX_FILE_PAGES = 64
|
||||
|
||||
_OFFSETS = {
|
||||
SUB_POLL: 0x0030, # 59 B — the one offset THOR treats as a constant
|
||||
SUB_SERIAL: 0x000A, # 21 B
|
||||
@@ -376,6 +382,31 @@ class MicromateProtocol:
|
||||
"""
|
||||
return self._read(SUB_SETUP_NEXT)
|
||||
|
||||
# ── Files, by path (read-only) ────────────────────────────────────────────
|
||||
|
||||
def read_file(self, path: str) -> bytes:
|
||||
"""A file off the unit, by full path: `0x94` + the path opens it, then
|
||||
`0x48` pages follow until an all-zero reply. The first `0x48` reply is a
|
||||
descriptor, not file content. Frames are THOR's exactly (UM12947 reading
|
||||
`schedule.dat`, 2026-09-24): `0x94` carries `params[3] = 1` and the path,
|
||||
unpadded, as data with offset = its length; the first `0x48` carries
|
||||
`params[7] = 1`, the rest none. Returns the content (each page's data
|
||||
after its 11-byte prefix), joined.
|
||||
"""
|
||||
raw = path.encode("ascii")
|
||||
self._request(build_request(SUB_FILE_OPEN_READ, len(raw), _FILE_OPEN_PARAMS, raw),
|
||||
0xFF - SUB_FILE_OPEN_READ)
|
||||
body = bytearray()
|
||||
for page in range(_MAX_FILE_PAGES):
|
||||
f = self._exchange(SUB_FILE_READ_NEXT,
|
||||
params=_FILE_FIRST_PAGE_PARAMS if page == 0 else bytes(10))
|
||||
if page == 0:
|
||||
continue # the descriptor
|
||||
if not any(f.data):
|
||||
return bytes(body)
|
||||
body += f.data[11:]
|
||||
raise ProtocolError(f"{path}: no end of file after {_MAX_FILE_PAGES} pages")
|
||||
|
||||
# ── Event chain ───────────────────────────────────────────────────────────
|
||||
|
||||
def arm_event(self) -> MicromateFrame:
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""schedule.py -- a Micromate's schedule file, parsed. Pure; read-only by design.
|
||||
|
||||
THOR's scheduler lives in a file on the unit, `\\system\\schedule\\schedule.dat`,
|
||||
read by path (`MicromateProtocol.read_file`). The format is decoded in
|
||||
docs/micromate_protocol_reference.md, *The schedule record format* (measured on
|
||||
UM12947, 2026-09-24/25): 260-byte records,
|
||||
|
||||
[0] record 0 only: 3 = repeat on, 2 = repeat off
|
||||
[4] half-hour slot, 0-47
|
||||
[5] day (3 in every record seen -- undetermined)
|
||||
[6] action bitmask: 2 start monitoring with setup, 4 stop, 8 self-check,
|
||||
16 auto call home
|
||||
[7] setup-name length
|
||||
[8:260] setup name (empty for actions that take none)
|
||||
|
||||
Why SFM reads it (phase 5): each scheduled start LOADS the setup it names. A
|
||||
settings change to any other setup would be replaced at the next start, so SFM
|
||||
refuses that change -- `schedule_conflicts`. SFM never writes the schedule.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Tuple
|
||||
|
||||
SCHEDULE_PATH = "\\system\\schedule\\schedule.dat"
|
||||
|
||||
_RECORD = 260
|
||||
_NAME_MAX = _RECORD - 8
|
||||
_ACTIONS = ((0x02, "start_with_setup"), (0x04, "stop"), (0x08, "self_check"), (0x10, "call_home"))
|
||||
_KNOWN_BITS = sum(bit for bit, _ in _ACTIONS)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleEntry:
|
||||
index: int
|
||||
time: str # "HH:MM", from the half-hour slot
|
||||
day: int # the raw byte; undetermined
|
||||
action_bits: int
|
||||
actions: Tuple[str, ...] # named bits; any other set bit as "unknown(0xNN)"
|
||||
setup: str # "" when the action takes no setup
|
||||
|
||||
|
||||
def _actions(bits: int) -> Tuple[str, ...]:
|
||||
named = tuple(name for bit, name in _ACTIONS if bits & bit)
|
||||
unknown = tuple(f"unknown(0x{1 << i:02x})" for i in range(8)
|
||||
if bits & (1 << i) and not (1 << i) & _KNOWN_BITS)
|
||||
return named + unknown
|
||||
|
||||
|
||||
def parse_schedule(body: bytes) -> List[ScheduleEntry]:
|
||||
"""The entries in a schedule file body. A record with nothing in [4:8] and
|
||||
no name ends the list (the file is padded with zeros)."""
|
||||
out: List[ScheduleEntry] = []
|
||||
for i in range(len(body) // _RECORD):
|
||||
r = body[i * _RECORD:(i + 1) * _RECORD]
|
||||
n = min(r[7], _NAME_MAX)
|
||||
name = r[8:8 + n].decode("ascii", "replace") if n else ""
|
||||
if not any(r[4:8]) and not name:
|
||||
break
|
||||
slot = r[4]
|
||||
out.append(ScheduleEntry(index=i, time=f"{slot // 2:02d}:{(slot % 2) * 30:02d}", day=r[5],
|
||||
action_bits=r[6], actions=_actions(r[6]), setup=name))
|
||||
return out
|
||||
|
||||
|
||||
def _same_setup(a: str, b: str) -> bool:
|
||||
return a.strip().casefold() == b.strip().casefold()
|
||||
|
||||
|
||||
def schedule_conflicts(entries: List[ScheduleEntry], active_setup: str) -> List[ScheduleEntry]:
|
||||
"""The scheduled starts that would load a setup other than `active_setup`
|
||||
(compared ignoring case and surrounding spaces: THOR and the keypad disagree
|
||||
on case, e.g. `factory.MMB` / `test2.mmb`)."""
|
||||
return [e for e in entries
|
||||
if "start_with_setup" in e.actions and e.setup and not _same_setup(e.setup, active_setup)]
|
||||
@@ -88,6 +88,20 @@ def crc_ok(content: bytes) -> bool:
|
||||
return _crc16_aug_ccitt(content[: n - 2]) == int.from_bytes(content[n : n + 2], "big")
|
||||
|
||||
|
||||
def with_crc(content: bytes) -> bytes:
|
||||
"""`content` with its trailing checksum recomputed: CRC-16/AUG-CCITT over
|
||||
``[0:N-2]``, stored big-endian at ``[N:N+2]`` (the rule `crc_ok` checks).
|
||||
THOR's write omits the checksum and the unit computes its own; this keeps a
|
||||
patched block self-consistent so a plan's integrity check still means
|
||||
something."""
|
||||
n = int.from_bytes(content[0:2], "big")
|
||||
if n < 2 or len(content) < n + 2:
|
||||
raise ValueError(f"block header says {n} but the block is {len(content)} B")
|
||||
out = bytearray(content)
|
||||
out[n : n + 2] = _crc16_aug_ccitt(content[: n - 2]).to_bytes(2, "big")
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _f32(c: bytes, offset: int) -> float:
|
||||
return struct.unpack_from(">f", c, offset)[0]
|
||||
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
"""setup_fields.py -- the settings an operator can change, for both series (phase 5).
|
||||
|
||||
Pure byte interpretation: no I/O, no device, no `sfm` and no `minimateplus`
|
||||
imports. Every offset is into the settings block's CONTENT:
|
||||
|
||||
* Series 4: the `0x1A` content, 2,092 bytes (N = 2090, then its CRC).
|
||||
* Series 3: the 1A read assembled by `minimateplus.protocol.
|
||||
assemble_compliance_content`, 2,090 bytes (N = 2090, no CRC in the read).
|
||||
|
||||
**One layout.** Measured 2026-11-03: Blastware's MiniMate compliance image IS
|
||||
Series IV's `0x1A` content layout (`decode_setup` reads it), and each of
|
||||
BE11529's nine 2026-04-20 Blastware writes moved exactly the bytes of the field
|
||||
it changed. Series 4's offsets are from the 47-snapshot keypad pass on UM20147
|
||||
(2026-10-17/19). Fields measured on one series only are offered on that series
|
||||
only.
|
||||
|
||||
**Limits are the units' own, from Instantel's manuals** (Brian, 2026-11-03: "I
|
||||
want to use the actual unit limits, not just what we have done in the past"):
|
||||
* geophone trigger 0.005-10 in/s in steps of 0.001 -- MiniMate Plus manual
|
||||
716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual
|
||||
721U0201 Rev 06, *Geophone Trigger Level* -- and at most the range's full
|
||||
scale;
|
||||
* record time: Micromate 1-90 s (*Record Time*); MiniMate up to §4.4's
|
||||
*Maximum Record Times* for a 1 MB unit, channels 1-4, at the sample rate,
|
||||
and 13 s in Histogram Combo (§3.8.9);
|
||||
* job number 1-9999 (both manuals).
|
||||
What a unit does not take, the read-back shows (`settings_state`).
|
||||
|
||||
tests/test_setup_fields.py holds this to Blastware's writes and the keypad
|
||||
fixtures byte for byte.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
import struct
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
|
||||
from .setup_block import crc_ok, with_crc
|
||||
|
||||
|
||||
class SettingsValueError(ValueError):
|
||||
"""A requested change SFM will not make, said plainly. Nothing is sent."""
|
||||
|
||||
|
||||
# ── Layout ──────────────────────────────────────────────────────────────────
|
||||
|
||||
_MODE = 5
|
||||
_SAMPLE_RATE = slice(6, 8) # u16 BE
|
||||
_HIST_INTERVAL = slice(8, 10) # u16 BE seconds
|
||||
_RECORD_TIME = 18 # f32 BE seconds
|
||||
_REPORT_FLAGS = 39 # bit 0x02 = job number on the report (measured both series)
|
||||
_JOB_SHOWN = 0x02
|
||||
_JOB_NUMBER = slice(40, 42) # u16 BE
|
||||
|
||||
_NOTE_LABEL, _NOTE_VALUE, _NOTE_STRIDE, _NOTES = 122, 144, 64, 4
|
||||
_NOTE_LABEL_WIDTH, _NOTE_WIDTH = 22, 42
|
||||
NOTE_MAX = _NOTE_WIDTH - 1 # a NUL always ends the value
|
||||
|
||||
_CHANNELS, _CHANNEL_SIZE, _GEOPHONES = 1708, 48, (0, 1, 2)
|
||||
_CH_RANGE = 29 # u8: 0 Normal (10 in/s), 1 Sensitive (1.25 in/s) -- Series 3, measured
|
||||
_CH_TRIGGER = 30 # f32 BE, in/s for a geophone
|
||||
_CH_UNIT = slice(34, 38) # "in." / "in" (the keypad re-renders it); NOT an identifier
|
||||
_CH_ALARM = 38 # f32 BE -- Series 3; write measured at the bench 2026-11-04
|
||||
_FULL_SCALE = {0: 10.0, 1: 1.25}
|
||||
_RANGES = {"normal": 0, "sensitive": 1}
|
||||
|
||||
# Blastware writes these bytes as a fixed value on every write on record (11 of 11,
|
||||
# both units); the unit reads `01 7f` there after a monitoring session. Meaning
|
||||
# unknown -- SFM writes what Blastware writes. Series 3 only.
|
||||
S3_BLASTWARE_FIXED = {26: b"\x00\x00"}
|
||||
|
||||
# Measured at the bench 2026-11-04 (BE9441, Brian's go): 1.0 -> 1.5 -> 1.0 in/s,
|
||||
# each acknowledged, read back, and shown in the unit's own setup menu; the write
|
||||
# moved exactly channel +39 of the three geophones (the f32 at +38).
|
||||
S3_ALARM_WRITE_MEASURED = True
|
||||
|
||||
MODES = {
|
||||
3: {"single_shot": 0x00, "continuous": 0x01, "histogram": 0x03, "histogram_continuous": 0x04},
|
||||
4: {"waveform": 0x01, "manual": 0x02, "histogram": 0x03, "combo": 0x04},
|
||||
}
|
||||
_MODE_LABELS = {
|
||||
"single_shot": "Single Shot", "continuous": "Continuous", "histogram": "Histogram",
|
||||
"histogram_continuous": "Histogram + Continuous", "waveform": "Waveform", "manual": "Manual",
|
||||
"combo": "Combo",
|
||||
}
|
||||
SAMPLE_RATES = (1024, 2048, 4096)
|
||||
INTERVALS = (2, 5, 15, 60, 300, 900)
|
||||
TRIGGER_MIN, TRIGGER_MAX, TRIGGER_STEP = 0.005, 10.0, 0.001
|
||||
RECORD_MIN_S = 1.0
|
||||
S4_MAX_RECORD_S = 90.0
|
||||
S3_MAX_RECORD_S = {1024: 104.0, 2048: 52.0, 4096: 26.0}
|
||||
S3_COMBO_MAX_RECORD_S = 13.0
|
||||
JOB_MIN, JOB_MAX = 1, 9999
|
||||
|
||||
_SERIES_FIELDS = {
|
||||
3: ("record_mode", "sample_rate", "histogram_interval_s", "record_time_s", "geo_trigger_ips",
|
||||
"geo_range", "geo_alarm_ips", "job_number", "job_number_shown",
|
||||
"note_1", "note_2", "note_3", "note_4"),
|
||||
4: ("record_mode", "sample_rate", "histogram_interval_s", "record_time_s", "geo_trigger_ips",
|
||||
"job_number", "job_number_shown", "note_1", "note_2", "note_3", "note_4"),
|
||||
}
|
||||
_LEVELS = ("geo_trigger_ips", "geo_alarm_ips")
|
||||
|
||||
|
||||
def _ch(k: int) -> int:
|
||||
return _CHANNELS + _CHANNEL_SIZE * k
|
||||
|
||||
|
||||
def _f32(c: bytes, offset: int) -> float:
|
||||
return struct.unpack_from(">f", c, offset)[0]
|
||||
|
||||
|
||||
def _shown(v: float) -> float:
|
||||
"""An f32 as an operator typed it: 0.30000001192 is 0.3."""
|
||||
return round(v, 6)
|
||||
|
||||
|
||||
def _note_offsets(n: int) -> tuple:
|
||||
label = _NOTE_LABEL + n * _NOTE_STRIDE
|
||||
value = _NOTE_VALUE + n * _NOTE_STRIDE
|
||||
return label, value
|
||||
|
||||
|
||||
def _note_label(c: bytes, n: int) -> str:
|
||||
start, _ = _note_offsets(n)
|
||||
raw = c[start:start + _NOTE_LABEL_WIDTH].split(b"\x00")[0]
|
||||
text = raw.decode("ascii", "replace").strip().rstrip(":").strip()
|
||||
return text or f"Note {n + 1}"
|
||||
|
||||
|
||||
def _note_value(c: bytes, n: int) -> str:
|
||||
_, start = _note_offsets(n)
|
||||
return c[start:start + _NOTE_WIDTH].split(b"\x00")[0].decode("ascii", "replace")
|
||||
|
||||
|
||||
def field_bytes(series: int) -> Dict[str, Set[int]]:
|
||||
"""Every byte each field may move, by content offset."""
|
||||
def chans(rel: int, width: int) -> Set[int]:
|
||||
return {_ch(k) + rel + i for k in _GEOPHONES for i in range(width)}
|
||||
out = {
|
||||
"record_mode": {_MODE},
|
||||
"sample_rate": set(range(6, 8)),
|
||||
"histogram_interval_s": set(range(8, 10)),
|
||||
"record_time_s": set(range(_RECORD_TIME, _RECORD_TIME + 4)),
|
||||
"geo_trigger_ips": chans(_CH_TRIGGER, 4),
|
||||
"geo_range": chans(_CH_RANGE, 1),
|
||||
"geo_alarm_ips": chans(_CH_ALARM, 4),
|
||||
"job_number": set(range(40, 42)),
|
||||
"job_number_shown": {_REPORT_FLAGS},
|
||||
}
|
||||
for n in range(_NOTES):
|
||||
_, v = _note_offsets(n)
|
||||
out[f"note_{n + 1}"] = set(range(v, v + _NOTE_WIDTH))
|
||||
return {f: out[f] for f in _SERIES_FIELDS[series]}
|
||||
|
||||
|
||||
# ── Reading ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _mode_name(c: bytes, series: int) -> str:
|
||||
code = c[_MODE]
|
||||
for name, value in MODES[series].items():
|
||||
if value == code:
|
||||
return name
|
||||
return f"unknown(0x{code:02x})"
|
||||
|
||||
|
||||
def _range_code(c: bytes) -> int:
|
||||
return c[_ch(0) + _CH_RANGE]
|
||||
|
||||
|
||||
def _full_scale(c: bytes, series: int, range_name: Optional[str] = None) -> Optional[float]:
|
||||
if series == 4:
|
||||
return _FULL_SCALE[0] # Series 4's range byte is not mapped; 10 in/s is the hardware's
|
||||
code = _RANGES[range_name] if range_name is not None else _range_code(c)
|
||||
return _FULL_SCALE.get(code)
|
||||
|
||||
|
||||
def _s3_max_record(rate: int, mode: str) -> Optional[float]:
|
||||
top = S3_MAX_RECORD_S.get(rate)
|
||||
if top is None:
|
||||
return None
|
||||
return min(top, S3_COMBO_MAX_RECORD_S) if mode == "histogram_continuous" else top
|
||||
|
||||
|
||||
def _unit_string(c: bytes) -> List[str]:
|
||||
return [c[_ch(k) + _CH_UNIT.start:_ch(k) + _CH_UNIT.stop].replace(b"\x00", b"")
|
||||
.replace(b".", b"").decode("ascii", "replace") for k in _GEOPHONES]
|
||||
|
||||
|
||||
def editable_fields(content: bytes, series: int) -> List[Dict[str, Any]]:
|
||||
"""The fields an operator can change, described for a form: field, label,
|
||||
kind ("number" / "choice" / "text" / "bool"), value, and as relevant unit,
|
||||
min, max, step, choices [{value, label}], maxlength, readonly."""
|
||||
c = content
|
||||
rate = int.from_bytes(c[_SAMPLE_RATE], "big")
|
||||
mode = _mode_name(c, series)
|
||||
out: List[Dict[str, Any]] = [
|
||||
{"field": "record_mode", "label": "Record mode", "kind": "choice", "value": mode,
|
||||
"choices": [{"value": n, "label": _MODE_LABELS[n]} for n in MODES[series]]},
|
||||
{"field": "sample_rate", "label": "Sample rate", "kind": "choice", "value": rate, "unit": "sps",
|
||||
"choices": [{"value": r, "label": f"{r} sps"} for r in SAMPLE_RATES]},
|
||||
{"field": "histogram_interval_s", "label": "Histogram interval", "kind": "choice",
|
||||
"value": int.from_bytes(c[_HIST_INTERVAL], "big"),
|
||||
"choices": [{"value": s, "label": f"{s} s" if s < 60 else f"{s // 60} min"} for s in INTERVALS]},
|
||||
{"field": "record_time_s", "label": "Record time", "kind": "number", "unit": "s",
|
||||
"value": _shown(_f32(c, _RECORD_TIME)), "min": RECORD_MIN_S,
|
||||
"max": S4_MAX_RECORD_S if series == 4 else _s3_max_record(rate, mode)},
|
||||
{"field": "geo_trigger_ips", "label": "Geophone trigger", "kind": "number", "unit": "in/s",
|
||||
"value": _shown(_f32(c, _ch(0) + _CH_TRIGGER)), "min": TRIGGER_MIN,
|
||||
"max": min(TRIGGER_MAX, _full_scale(c, series) or TRIGGER_MAX), "step": TRIGGER_STEP},
|
||||
]
|
||||
if series == 3:
|
||||
code = _range_code(c)
|
||||
name = next((n for n, v in _RANGES.items() if v == code), f"unknown(0x{code:02x})")
|
||||
out.append({"field": "geo_range", "label": "Geophone range", "kind": "choice", "value": name,
|
||||
"choices": [{"value": "normal", "label": "Normal (10 in/s)"},
|
||||
{"value": "sensitive", "label": "Sensitive (1.25 in/s)"}]})
|
||||
out.append({"field": "geo_alarm_ips", "label": "Geophone alarm", "kind": "number",
|
||||
"unit": "in/s", "value": _shown(_f32(c, _ch(0) + _CH_ALARM)),
|
||||
"min": TRIGGER_MIN, "max": _full_scale(c, 3) or TRIGGER_MAX,
|
||||
"step": TRIGGER_STEP, "readonly": not S3_ALARM_WRITE_MEASURED})
|
||||
out.append({"field": "job_number", "label": "Job number", "kind": "number",
|
||||
"value": int.from_bytes(c[_JOB_NUMBER], "big"), "min": JOB_MIN, "max": JOB_MAX, "step": 1})
|
||||
out.append({"field": "job_number_shown", "label": "Job number on report", "kind": "bool",
|
||||
"value": bool(c[_REPORT_FLAGS] & _JOB_SHOWN)})
|
||||
for n in range(_NOTES):
|
||||
out.append({"field": f"note_{n + 1}", "label": _note_label(c, n), "kind": "text",
|
||||
"value": _note_value(c, n), "maxlength": NOTE_MAX})
|
||||
return out
|
||||
|
||||
|
||||
def field_values(content: bytes, series: int) -> Dict[str, Any]:
|
||||
return {d["field"]: d["value"] for d in editable_fields(content, series)}
|
||||
|
||||
|
||||
def field_rows(before: bytes, written: bytes, series: int, fields, now: Optional[bytes] = None) -> Dict[str, Dict[str, Any]]:
|
||||
"""For each changed field: its label, the value the unit had (old), the value
|
||||
sent (new) and, given a read-back, what the unit now holds (now)."""
|
||||
a, w = field_values(before, series), field_values(written, series)
|
||||
n = field_values(now, series) if now is not None else None
|
||||
labels = {d["field"]: d["label"] for d in editable_fields(written, series)}
|
||||
out: Dict[str, Dict[str, Any]] = {}
|
||||
for f in fields:
|
||||
row: Dict[str, Any] = {"label": labels[f], "old": a[f], "new": w[f]}
|
||||
if n is not None:
|
||||
row["now"] = n[f]
|
||||
out[f] = row
|
||||
return out
|
||||
|
||||
|
||||
# ── Checking ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _number(field: str, v: Any) -> float:
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
|
||||
raise SettingsValueError(f"{field} must be a number, not {v!r}")
|
||||
return float(v)
|
||||
|
||||
|
||||
def _integer(field: str, v: Any) -> int:
|
||||
if isinstance(v, bool) or not isinstance(v, int):
|
||||
raise SettingsValueError(f"{field} must be a whole number, not {v!r}")
|
||||
return v
|
||||
|
||||
|
||||
def check_changes(content: bytes, series: int, changes: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""The changes, normalised -- or SettingsValueError naming the first one SFM
|
||||
will not make, and why. Checks names, types and the units' own limits, then
|
||||
what depends on this unit's block: its unit strings and its range."""
|
||||
if series not in _SERIES_FIELDS:
|
||||
raise SettingsValueError(f"Series {series} has no settings SFM can change")
|
||||
if not isinstance(changes, dict) or not changes:
|
||||
raise SettingsValueError("no settings to change")
|
||||
allowed = _SERIES_FIELDS[series]
|
||||
out: Dict[str, Any] = {}
|
||||
for field, v in changes.items():
|
||||
if field not in allowed:
|
||||
raise SettingsValueError(f"{field} is not a setting SFM can change on a Series {series} unit")
|
||||
if field == "record_mode":
|
||||
if v not in MODES[series]:
|
||||
raise SettingsValueError(f"record_mode must be one of {', '.join(MODES[series])}, not {v!r}")
|
||||
out[field] = v
|
||||
elif field == "sample_rate":
|
||||
if _integer(field, v) not in SAMPLE_RATES:
|
||||
raise SettingsValueError(f"sample_rate must be one of {SAMPLE_RATES}, not {v}")
|
||||
out[field] = v
|
||||
elif field == "histogram_interval_s":
|
||||
if _integer(field, v) not in INTERVALS:
|
||||
raise SettingsValueError(f"histogram_interval_s must be one of {INTERVALS} s, not {v}")
|
||||
out[field] = v
|
||||
elif field == "geo_range":
|
||||
if v not in _RANGES:
|
||||
raise SettingsValueError(f"geo_range must be normal or sensitive, not {v!r}")
|
||||
out[field] = v
|
||||
elif field in ("geo_trigger_ips", "geo_alarm_ips"):
|
||||
if field == "geo_alarm_ips" and not S3_ALARM_WRITE_MEASURED:
|
||||
raise SettingsValueError("the alarm level is shown but not changed yet: a MiniMate "
|
||||
"alarm write has never been measured (the bench measures it)")
|
||||
x = _number(field, v)
|
||||
if not TRIGGER_MIN <= x <= TRIGGER_MAX:
|
||||
raise SettingsValueError(f"{field} must be {TRIGGER_MIN}-{TRIGGER_MAX} in/s, not {x}")
|
||||
if abs(x - round(x, 3)) > 1e-9:
|
||||
raise SettingsValueError(f"{field} must be in steps of {TRIGGER_STEP} in/s, not {x}")
|
||||
out[field] = round(x, 3)
|
||||
elif field == "record_time_s":
|
||||
out[field] = _number(field, v)
|
||||
elif field == "job_number":
|
||||
if not JOB_MIN <= _integer(field, v) <= JOB_MAX:
|
||||
raise SettingsValueError(f"job_number must be {JOB_MIN}-{JOB_MAX}, not {v}")
|
||||
out[field] = v
|
||||
elif field == "job_number_shown":
|
||||
if not isinstance(v, bool):
|
||||
raise SettingsValueError(f"job_number_shown must be true or false, not {v!r}")
|
||||
out[field] = v
|
||||
else: # note_1 .. note_4
|
||||
if not isinstance(v, str):
|
||||
raise SettingsValueError(f"{field} must be text, not {v!r}")
|
||||
if any(not 0x20 <= ord(ch) <= 0x7E for ch in v):
|
||||
raise SettingsValueError(f"{field} must be plain printable ASCII (no accents, tabs or "
|
||||
"line breaks)")
|
||||
if len(v) > NOTE_MAX:
|
||||
raise SettingsValueError(f"{field} is {len(v)} characters; the unit holds {NOTE_MAX}")
|
||||
out[field] = v
|
||||
|
||||
# What depends on this unit's block, with the NEW mode / rate / range if they change
|
||||
# too -- checked on the block that would RESULT, so a one-field change (the range,
|
||||
# the rate, the mode) cannot leave a value the unit already holds over its limit
|
||||
# (final review, 2026-11-03).
|
||||
c = content
|
||||
if any(f in out for f in ("record_time_s", "sample_rate", "record_mode")):
|
||||
t = out.get("record_time_s", _shown(_f32(c, _RECORD_TIME)))
|
||||
held = "" if "record_time_s" in out else f" (the unit holds {t:g} s; change the record time too)"
|
||||
if series == 4:
|
||||
top: Optional[float] = S4_MAX_RECORD_S
|
||||
else:
|
||||
rate = out.get("sample_rate", int.from_bytes(c[_SAMPLE_RATE], "big"))
|
||||
top = _s3_max_record(rate, out.get("record_mode", _mode_name(c, series)))
|
||||
if top is None:
|
||||
raise SettingsValueError(f"this unit's sample rate ({rate}) has no record-time limit "
|
||||
"in the manual -- set the sample rate too")
|
||||
if not RECORD_MIN_S <= t <= top:
|
||||
raise SettingsValueError(f"record_time_s must be {RECORD_MIN_S}-{top:g} s here, not {t}{held}")
|
||||
if any(f in out for f in (*_LEVELS, "geo_range")):
|
||||
units = _unit_string(c)
|
||||
if any(u != "in" for u in units):
|
||||
raise SettingsValueError(f"this unit's geophone channels read {units}, not in/s -- only "
|
||||
"in/s is measured, so SFM will not change a level or the range")
|
||||
full = _full_scale(c, series, out.get("geo_range"))
|
||||
if full is None:
|
||||
raise SettingsValueError("this unit's geophone range byte is not a value ever measured")
|
||||
held_levels = {"geo_trigger_ips": _CH_TRIGGER, "geo_alarm_ips": _CH_ALARM}
|
||||
for f in _LEVELS:
|
||||
if f not in _SERIES_FIELDS[series]:
|
||||
continue
|
||||
v = out.get(f, _shown(_f32(c, _ch(0) + held_levels[f])))
|
||||
if v > full:
|
||||
held = "" if f in out else " (the unit holds it)"
|
||||
raise SettingsValueError(f"{f} {v} in/s is above the range's full scale ({full} in/s){held}")
|
||||
return out
|
||||
|
||||
|
||||
# ── Writing ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def encode_setup(content: bytes, series: int, changes: Dict[str, Any]) -> bytes:
|
||||
"""`content` with only the changed fields' bytes moved. `changes` should
|
||||
come from check_changes; this patches, it does not judge. Bit fields are
|
||||
patched bit by bit. Series 3 also writes Blastware's fixed bytes; Series 4
|
||||
gets its checksum recomputed."""
|
||||
out = bytearray(content)
|
||||
for field, v in changes.items():
|
||||
if field == "record_mode":
|
||||
out[_MODE] = MODES[series][v]
|
||||
elif field == "sample_rate":
|
||||
out[_SAMPLE_RATE] = int(v).to_bytes(2, "big")
|
||||
elif field == "histogram_interval_s":
|
||||
out[_HIST_INTERVAL] = int(v).to_bytes(2, "big")
|
||||
elif field == "record_time_s":
|
||||
struct.pack_into(">f", out, _RECORD_TIME, float(v))
|
||||
elif field == "geo_trigger_ips":
|
||||
for k in _GEOPHONES:
|
||||
struct.pack_into(">f", out, _ch(k) + _CH_TRIGGER, float(v))
|
||||
elif field == "geo_alarm_ips":
|
||||
for k in _GEOPHONES:
|
||||
struct.pack_into(">f", out, _ch(k) + _CH_ALARM, float(v))
|
||||
elif field == "geo_range":
|
||||
for k in _GEOPHONES:
|
||||
out[_ch(k) + _CH_RANGE] = _RANGES[v]
|
||||
elif field == "job_number":
|
||||
out[_JOB_NUMBER] = int(v).to_bytes(2, "big")
|
||||
elif field == "job_number_shown":
|
||||
out[_REPORT_FLAGS] = (out[_REPORT_FLAGS] | _JOB_SHOWN) if v else (out[_REPORT_FLAGS] & ~_JOB_SHOWN)
|
||||
elif field.startswith("note_") and field[5:].isdigit() and 1 <= int(field[5:]) <= _NOTES:
|
||||
_, start = _note_offsets(int(field[5:]) - 1)
|
||||
out[start:start + _NOTE_WIDTH] = v.encode("ascii").ljust(_NOTE_WIDTH, b"\x00")
|
||||
else:
|
||||
raise SettingsValueError(f"{field} is not a setting SFM can change")
|
||||
if series == 3:
|
||||
for offset, value in S3_BLASTWARE_FIXED.items():
|
||||
out[offset:offset + len(value)] = value
|
||||
return bytes(out)
|
||||
return with_crc(bytes(out))
|
||||
|
||||
|
||||
# ── Reading back ────────────────────────────────────────────────────────────
|
||||
|
||||
_COMPARED = 2090
|
||||
|
||||
|
||||
def settings_state(before: bytes, written: bytes, now: bytes, *, series: int) -> str:
|
||||
"""What a read of the unit says about a change, from the bytes alone:
|
||||
"as asked" (it holds what was written), "unchanged" (it holds what it had),
|
||||
or "differs". Floats are never compared -- 0.3 is the same f32 both ways.
|
||||
Series 4 also needs the unit's own checksum to hold. Series 3 bytes that
|
||||
differ only in Blastware's fixed bytes count as as asked: nothing the operator
|
||||
asked for is different."""
|
||||
a, w, n = before[:_COMPARED], written[:_COMPARED], now[:_COMPARED]
|
||||
if series == 4 and not crc_ok(now):
|
||||
return "differs"
|
||||
if n == w:
|
||||
return "as asked"
|
||||
if series == 3:
|
||||
fixed = {o + i for o, v in S3_BLASTWARE_FIXED.items() for i in range(len(v))}
|
||||
if len(n) == len(w) and all(n[i] == w[i] for i in range(len(n)) if i not in fixed):
|
||||
return "as asked"
|
||||
if n == a:
|
||||
return "unchanged"
|
||||
return "differs"
|
||||
|
||||
|
||||
def revision(blocks: List[bytes]) -> str:
|
||||
"""A short fingerprint of the blocks a preview read; a live change must match it."""
|
||||
return hashlib.sha256(b"".join(bytes(b) for b in blocks)).hexdigest()[:16]
|
||||
|
||||
|
||||
def changes_bytes(changes: Dict[str, Any]) -> bytes:
|
||||
"""The normalised changes, canonically: part of a preview's revision, so a live
|
||||
change must ask for exactly what was previewed (final review, 2026-11-03)."""
|
||||
import json
|
||||
return json.dumps(changes, sort_keys=True, separators=(",", ":")).encode("ascii")
|
||||
+19
-6
@@ -22,6 +22,7 @@ from .opcodes import CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused
|
||||
from .setup_block import crc_ok
|
||||
|
||||
_CONFIRM = 0xFFFF
|
||||
_CALL_HOME_OBSERVED = (0x00, 0x01, 0x04, 0x05) # content[5] values units have held
|
||||
|
||||
# block content sizes THOR's offsets were observed at (all on UM12947 / 11.0CB)
|
||||
_PREFS_LEN, _TRIGGER_LEN, _SETUP_LEN, _CALL_HOME_LEN = 90, 28, 2092, 126
|
||||
@@ -101,26 +102,38 @@ def plan_stop_monitoring() -> WritePlan:
|
||||
return WritePlan("stop monitoring", (WriteStep(0x97, _CONFIRM, what="stop monitoring"),))
|
||||
|
||||
|
||||
def is_call_home_content(block: bytes) -> bool:
|
||||
"""Whether 126 bytes are the 0x2C call-home content: its header is its own
|
||||
length (00 7C, N = 124 -- 00 7C DC on every read on record, UM12947 and
|
||||
UM20147). A bit is flipped only in a block that carries it."""
|
||||
return len(block) == _CALL_HOME_LEN and int.from_bytes(block[0:2], "big") == _CALL_HOME_LEN - 2
|
||||
|
||||
|
||||
def plan_call_home_enabled(call_home: bytes, enabled: bool) -> WritePlan:
|
||||
"""Read `0x2C`, flip bit 0 of content[5], send the rest back byte for byte.
|
||||
|
||||
Bit 0 of `[5]` is the enable. 🔶 UM12947 (THOR's unit) read 0x05 enabled /
|
||||
0x04 disabled, bit 2 set in both; UM20147 reads 0x01 (measured, phase-2 dry
|
||||
run). So on UM20147 "off" writes 0x00, a value no capture shows being
|
||||
written: the target value there is unobserved, and the plan's `warnings`
|
||||
say so. `[118:120]` is unit-maintained and THOR echoes it.
|
||||
run). So on UM20147 "off" writes 0x00 -- measured at the bench 2026-11-03
|
||||
(and again 11-04): 0x01 <-> 0x00 acknowledged, read back, and matched in the
|
||||
unit's own menu. A value outside those four still carries a warning.
|
||||
`[118:120]` is unit-maintained and THOR echoes it.
|
||||
"""
|
||||
if len(call_home) != _CALL_HOME_LEN:
|
||||
raise ValueError(f"call-home content must be {_CALL_HOME_LEN} B "
|
||||
f"(the size THOR's offset was seen at), got {len(call_home)}")
|
||||
if not is_call_home_content(call_home):
|
||||
raise ValueError(f"call-home content's header is {call_home[0:2].hex()}, not its own length "
|
||||
f"(00 {_CALL_HOME_LEN - 2:02x}) -- not the call-home block; nothing built")
|
||||
b5 = (call_home[5] | 0x01) if enabled else (call_home[5] & 0xFE)
|
||||
data = call_home[:5] + bytes([b5]) + call_home[6:]
|
||||
what = "call-home " + ("enable" if enabled else "disable")
|
||||
start = call_home[5]
|
||||
warnings = []
|
||||
if start not in (0x04, 0x05) or b5 not in (0x04, 0x05):
|
||||
warnings.append(f"content[5] 0x{start:02X} -> 0x{b5:02X}: THOR was only ever "
|
||||
"seen writing 0x04/0x05 (UM12947); this value is unobserved")
|
||||
if start not in _CALL_HOME_OBSERVED or b5 not in _CALL_HOME_OBSERVED:
|
||||
warnings.append(f"content[5] 0x{start:02X} -> 0x{b5:02X}: no unit has been seen "
|
||||
"holding this value (0x04/0x05 UM12947 by THOR, 0x00/0x01 UM20147 "
|
||||
"by SFM); it is unobserved")
|
||||
if b5 == start:
|
||||
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
|
||||
" -- this write changes nothing")
|
||||
|
||||
+45
-376
@@ -70,15 +70,8 @@ S3_MONITORING_FLAGS = frozenset({0x10, 0x0B})
|
||||
# ⚠ RETRACTED 2026-10-27 (#46): a trigger block "hardcoded from 3-11-26 -- no
|
||||
# read exists, Blastware writes this fixed blob". Blastware reads it first (SUB
|
||||
# 0x2E), and its byte 5 differs by unit and session (01 / 03 / 04 on record), so
|
||||
# the copy changed that setting on any unit that differed. apply_config reads
|
||||
# the unit's own block (MiniMateProtocol.read_trigger_config).
|
||||
|
||||
# Compliance ASCII slot format (confirmed from 3-11-26 capture + label search):
|
||||
# Each label occupies a 64-byte slot.
|
||||
# Value starts at slot_start + 22, max 42 bytes, null-padded.
|
||||
_COMPLIANCE_SLOT_SIZE = 64
|
||||
_COMPLIANCE_VALUE_OFFSET = 22
|
||||
_COMPLIANCE_VALUE_MAX = _COMPLIANCE_SLOT_SIZE - _COMPLIANCE_VALUE_OFFSET # 42
|
||||
# the copy changed that setting on any unit that differed. A settings write sends
|
||||
# the unit's own block back (sfm.device_access.s3 change_settings, phase 5).
|
||||
|
||||
|
||||
# ── MiniMateClient ────────────────────────────────────────────────────────────
|
||||
@@ -922,6 +915,8 @@ class MiniMateClient:
|
||||
compliance_data: bytes,
|
||||
trigger_data: bytes,
|
||||
waveform_data: bytes,
|
||||
*,
|
||||
escaped: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Push a complete config update to the device using the confirmed write
|
||||
@@ -949,6 +944,10 @@ class MiniMateClient:
|
||||
trigger_data: Raw bytes for SUB 82 write (44-byte trigger config).
|
||||
waveform_data: Raw bytes for SUB 69 write.
|
||||
|
||||
`escaped`: False (the default) -- the blocks are logical, as every block
|
||||
read returns them since phase 5; True for blocks that still hold the
|
||||
parser's kept escape bytes.
|
||||
|
||||
Raises:
|
||||
RuntimeError: if the client is not connected.
|
||||
ProtocolError: if any write step fails (timeout, bad ack SUB).
|
||||
@@ -960,32 +959,36 @@ class MiniMateClient:
|
||||
# 2026-10-27): a block refused after 68 + 73 had been sent left a partial
|
||||
# write behind. write_image is the same check each write makes.
|
||||
from .protocol import (SUB_COMPLIANCE_WRITE, SUB_EVENT_INDEX_WRITE,
|
||||
SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE, write_image)
|
||||
SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE, ImageRefused,
|
||||
write_image)
|
||||
for sub, data in ((SUB_EVENT_INDEX_WRITE, event_index_data),
|
||||
(SUB_COMPLIANCE_WRITE, compliance_data),
|
||||
(SUB_TRIGGER_CONFIG_WRITE, trigger_data),
|
||||
(SUB_WAVEFORM_DATA_WRITE, waveform_data)):
|
||||
write_image(sub, data)
|
||||
try:
|
||||
write_image(sub, data, escaped=escaped)
|
||||
except ValueError as exc: # refused before any frame: the caller audits "nothing sent"
|
||||
raise ImageRefused(str(exc)) from exc
|
||||
|
||||
# 68 → 73
|
||||
log.info("push_config_raw: write event index (SUB 68)")
|
||||
proto.write_event_index(event_index_data)
|
||||
proto.write_event_index(event_index_data, escaped=escaped)
|
||||
log.info("push_config_raw: confirm B (SUB 73)")
|
||||
proto.write_confirm(SUB_WRITE_CONFIRM_B)
|
||||
|
||||
# 71×3 → 72 (handled internally by write_compliance_config_raw)
|
||||
log.info("push_config_raw: write compliance config (SUB 71 ×3 + confirm 72)")
|
||||
proto.write_compliance_config_raw(compliance_data)
|
||||
proto.write_compliance_config_raw(compliance_data, escaped=escaped)
|
||||
|
||||
# 82 → 83
|
||||
log.info("push_config_raw: write trigger config (SUB 82)")
|
||||
proto.write_trigger_config(trigger_data)
|
||||
proto.write_trigger_config(trigger_data, escaped=escaped)
|
||||
log.info("push_config_raw: trigger confirm (SUB 83)")
|
||||
proto.write_confirm(SUB_TRIGGER_CONFIRM)
|
||||
|
||||
# 69 → 74 → 72
|
||||
log.info("push_config_raw: write waveform data (SUB 69)")
|
||||
proto.write_waveform_data(waveform_data)
|
||||
proto.write_waveform_data(waveform_data, escaped=escaped)
|
||||
log.info("push_config_raw: confirm C (SUB 74)")
|
||||
proto.write_confirm(SUB_WRITE_CONFIRM_C)
|
||||
log.info("push_config_raw: confirm A (SUB 72)")
|
||||
@@ -993,120 +996,6 @@ class MiniMateClient:
|
||||
|
||||
log.info("push_config_raw: complete")
|
||||
|
||||
def apply_config(
|
||||
self,
|
||||
*,
|
||||
# Recording parameters
|
||||
recording_mode: Optional[int] = None,
|
||||
sample_rate: Optional[int] = None,
|
||||
record_time: Optional[float] = None,
|
||||
histogram_interval_sec: Optional[int] = None,
|
||||
# Threshold parameters (geo channels, in/s)
|
||||
trigger_level_geo: Optional[float] = None,
|
||||
alarm_level_geo: Optional[float] = None,
|
||||
geo_range: Optional[int] = None, # 0x00=Normal 10in/s, 0x01=Sensitive 1.25in/s
|
||||
# Project / operator strings
|
||||
project: Optional[str] = None,
|
||||
client_name: Optional[str] = None,
|
||||
operator: Optional[str] = None,
|
||||
seis_loc: Optional[str] = None,
|
||||
notes: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Read the current device config, apply any supplied changes to the
|
||||
compliance block, and write the full config back to the device.
|
||||
|
||||
Only non-None arguments are modified; all other bytes are round-tripped
|
||||
verbatim from the device.
|
||||
|
||||
Configurable fields
|
||||
-------------------
|
||||
Recording parameters:
|
||||
recording_mode : int — 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous
|
||||
sample_rate : int — samples/sec; valid values: 1024, 2048, 4096
|
||||
record_time : float — record duration in seconds (e.g. 2.0, 3.0)
|
||||
|
||||
Trigger/alarm thresholds and range (geo channels):
|
||||
trigger_level_geo : float — trigger threshold in/s (e.g. 0.5)
|
||||
alarm_level_geo : float — alarm threshold in/s (e.g. 1.0)
|
||||
geo_range : int — 0x00=Normal 10.000 in/s, 0x01=Sensitive 1.250 in/s
|
||||
(written to Tran/Vert/Long channel blocks)
|
||||
|
||||
Project / operator strings (max 41 ASCII characters each):
|
||||
project : str
|
||||
client_name : str
|
||||
operator : str
|
||||
seis_loc : str — sensor location
|
||||
notes : str — extended notes
|
||||
|
||||
Write sequence (confirmed from 3-11-26 BW TX capture):
|
||||
68→73 | 71×3→72 | 82→83 | 69→74→72
|
||||
|
||||
Write payloads:
|
||||
event_index_data : 88 bytes — read live via SUB 08
|
||||
compliance_data : ~2128 bytes — read live via SUB 1A (~2126 bytes, varies ±1-2) + \\x00\\x00 footer
|
||||
trigger_data : 26 bytes — read live via SUB 2E (was hard-coded; #46)
|
||||
waveform_data : 204 bytes — read live via SUB 09
|
||||
|
||||
Raises:
|
||||
RuntimeError: if not connected.
|
||||
ProtocolError: if any read or write step fails.
|
||||
ValueError: if compliance buffer is shorter than the 2082-byte write minimum.
|
||||
"""
|
||||
proto = self._require_proto()
|
||||
|
||||
# 1. Read current payloads from the device
|
||||
log.info("apply_config: reading event index (SUB 08)")
|
||||
event_index_data = proto.read_event_index()
|
||||
|
||||
log.info("apply_config: reading compliance config (SUB 1A)")
|
||||
compliance_raw = proto.read_compliance_config() # ~2126 bytes (varies ±1-2 by DLE jitter)
|
||||
|
||||
log.info("apply_config: reading waveform data (SUB 09)")
|
||||
waveform_data = proto.read_waveform_data_raw() # 204 bytes
|
||||
|
||||
log.info("apply_config: reading trigger config (SUB 2E)")
|
||||
trigger_data = proto.read_trigger_config() # 26 bytes, this unit's own
|
||||
|
||||
# 2. Patch the compliance buffer and build the 2128-byte write payload
|
||||
compliance_data = _encode_compliance_config(
|
||||
compliance_raw,
|
||||
recording_mode=recording_mode,
|
||||
sample_rate=sample_rate,
|
||||
record_time=record_time,
|
||||
histogram_interval_sec=histogram_interval_sec,
|
||||
trigger_level_geo=trigger_level_geo,
|
||||
alarm_level_geo=alarm_level_geo,
|
||||
geo_range=geo_range,
|
||||
project=project,
|
||||
client_name=client_name,
|
||||
operator=operator,
|
||||
seis_loc=seis_loc,
|
||||
notes=notes,
|
||||
)
|
||||
log.info("apply_config: compliance payload ready (%d bytes)", len(compliance_data))
|
||||
|
||||
# 3. Push the full write sequence to the device
|
||||
self.push_config_raw(event_index_data, compliance_data, trigger_data, waveform_data)
|
||||
log.info("apply_config: complete")
|
||||
|
||||
def set_project_info(
|
||||
self,
|
||||
project: Optional[str] = None,
|
||||
client_name: Optional[str] = None,
|
||||
operator: Optional[str] = None,
|
||||
seis_loc: Optional[str] = None,
|
||||
notes: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Backwards-compat shim — delegates to apply_config()."""
|
||||
self.apply_config(
|
||||
project=project,
|
||||
client_name=client_name,
|
||||
operator=operator,
|
||||
seis_loc=seis_loc,
|
||||
notes=notes,
|
||||
)
|
||||
|
||||
# ── Call home config ──────────────────────────────────────────────────────
|
||||
|
||||
def get_call_home_config(self) -> CallHomeConfig:
|
||||
@@ -1127,6 +1016,33 @@ class MiniMateClient:
|
||||
raw = proto.read_call_home_config()
|
||||
return _decode_call_home_config(raw)
|
||||
|
||||
def read_call_home_raw(self) -> bytes:
|
||||
"""The `0x2C` reply payload as read (125 B, kept escapes in), for a
|
||||
read-modify-write (`call_home_image`)."""
|
||||
return self._require_proto().read_call_home_config()
|
||||
|
||||
def read_compliance_content(self) -> bytes:
|
||||
"""The 1A settings read as the logical 2,090-byte block, unjudged (a
|
||||
monitoring unit's device-info answer comes back as it is; see
|
||||
`minimateplus.protocol.is_compliance_content`)."""
|
||||
return self._require_proto().read_compliance_content()
|
||||
|
||||
def read_settings_blocks(self) -> dict:
|
||||
"""The four blocks a settings write sends back, each as its read returns it:
|
||||
event index (08), settings (1A, logical), trigger (2E), waveform data (09)."""
|
||||
proto = self._require_proto()
|
||||
return {"event_index": proto.read_event_index(),
|
||||
"compliance": proto.read_compliance_content(),
|
||||
"trigger": proto.read_trigger_config(),
|
||||
"waveform": proto.read_waveform_data_raw()}
|
||||
|
||||
def write_call_home_image(self, image: bytes) -> None:
|
||||
"""Send a `0x7E` image (`call_home_image`) and its `0x7F` confirm, each ack
|
||||
checked -- framed once, never unescaped again. Raises ImageRefused before
|
||||
any byte goes out for an image that is not a whole block. No retry: what
|
||||
happened is the caller's to read back."""
|
||||
self._require_proto().write_call_home_image(image)
|
||||
|
||||
def set_call_home_config(
|
||||
self,
|
||||
*,
|
||||
@@ -2096,253 +2012,6 @@ def _extract_project_strings(data: bytes) -> Optional[ProjectInfo]:
|
||||
)
|
||||
|
||||
|
||||
def _encode_compliance_config(
|
||||
raw: bytes,
|
||||
*,
|
||||
recording_mode: Optional[int] = None,
|
||||
sample_rate: Optional[int] = None,
|
||||
record_time: Optional[float] = None,
|
||||
trigger_level_geo: Optional[float] = None,
|
||||
alarm_level_geo: Optional[float] = None,
|
||||
geo_range: Optional[int] = None, # 0x00=Normal 10in/s, 0x01=Sensitive 1.25in/s
|
||||
histogram_interval_sec: Optional[int] = None,
|
||||
project: Optional[str] = None,
|
||||
client_name: Optional[str] = None,
|
||||
operator: Optional[str] = None,
|
||||
seis_loc: Optional[str] = None,
|
||||
notes: Optional[str] = None,
|
||||
) -> bytes:
|
||||
"""
|
||||
Patch a live 2126-byte compliance buffer (read from the device) with any
|
||||
supplied field values and return the 2128-byte write payload.
|
||||
|
||||
Only non-None arguments are modified; everything else is round-tripped verbatim.
|
||||
|
||||
Numeric field locations (all anchor-relative or label-relative — immune to
|
||||
DLE-jitter shifts):
|
||||
|
||||
Anchor: b'\\xbe\\x80\\x00\\x00\\x00\\x00' (confirmed stable, both BE11529 and BE18189)
|
||||
⚠ 2026-10-29: these RAW offsets were measured at 1024 sps, where the escape
|
||||
before `04` sits between the mode and the anchor. The decoder now reads
|
||||
the four fields after unescaping (mode -7, rate -6, interval -4, record
|
||||
time +6), so at any other layout these patch the wrong bytes. Until the
|
||||
encoder is rewritten on unescaped bytes (#46), a payload whose four fields
|
||||
do not read back as asked raises ValueError -- see the end of this function.
|
||||
recording_mode → uint8 at anchor_pos - 8 (raw; right at 1024 sps only)
|
||||
Values: 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous
|
||||
NOTE: The byte at anchor_pos - 7 is always 0x10 (a DLE marker regenerated by
|
||||
device firmware in every E5 response). It must NOT be overwritten during
|
||||
write — doing so causes anchor drift (+1 per write cycle).
|
||||
CORRECTION 2026-04-21: previous doc stated anchor-7 for write; empirically
|
||||
confirmed wrong — writing to anchor-7 shifts the anchor by 1 on every cycle.
|
||||
sample_rate → uint16 BE at anchor_pos - 6
|
||||
histogram_interval_sec → uint16 BE at anchor_pos - 4 (seconds; mode-gated to Histogram/Histogram+Continuous)
|
||||
Valid values: 2, 5, 15, 60, 300, 900 (= 2s, 5s, 15s, 1m, 5m, 15m)
|
||||
record_time → float32 BE at anchor_pos + 6
|
||||
|
||||
Channel block (anchored on b"Tran" with unit-string guard):
|
||||
geo_range → uint8 at tran_pos + 33 (confirmed 2026-04-20)
|
||||
0x00 = Normal 10.000 in/s, 0x01 = Sensitive 1.250 in/s
|
||||
Written to Tran, Vert, Long channel blocks (all three).
|
||||
adc_scale_factor → float32 BE at tran_pos + 28 (= 6.206053; do NOT write)
|
||||
trigger_level_geo → float32 BE at tran_pos + 34
|
||||
"in.\\x00" → unit string at tran_pos + 38 (layout guard)
|
||||
alarm_level_geo → float32 BE at tran_pos + 42
|
||||
"/s\\x00\\x00" → unit string at tran_pos + 46 (layout guard)
|
||||
NOTE: tran_pos+28 (float32 = 6.206053) is the ADC-to-velocity scale factor
|
||||
(= 1/sensitivity, (in/s)/V — Interface Handbook §4.5: 1.61133 V × 6.206053 = 10.000 in/s).
|
||||
This is a hardware/firmware constant common to all MiniMate Plus S3 units.
|
||||
It must NOT be written — do not add it back as a parameter.
|
||||
|
||||
String field locations (64-byte slots, label+22 format):
|
||||
b"Project:" → value at label_pos + 22, max 41 chars + null
|
||||
b"Client:" → value at label_pos + 22, max 41 chars + null
|
||||
b"User Name:" → value at label_pos + 22, max 41 chars + null
|
||||
b"Seis Loc:" → value at label_pos + 22, max 41 chars + null
|
||||
b"Extended Notes"→ value at label_pos + 22, max 41 chars + null
|
||||
|
||||
Returns:
|
||||
2128-byte write payload: patched 2126-byte buffer + 2-byte footer \\x00\\x00.
|
||||
(Checksum formula for the footer is unknown; \\x00\\x00 confirmed accepted
|
||||
by the device in POC test 2026-04-07.)
|
||||
|
||||
Raises:
|
||||
ValueError: if raw is shorter than the minimum needed for the 3-chunk write.
|
||||
"""
|
||||
# Total size is nominally ~2126 bytes but varies by ±1-2 bytes depending on
|
||||
# DLE jitter in the E5 read response (0x10 bytes in the config data cause
|
||||
# 1-byte expansions per occurrence during DLE stuffing/unstuffing). The
|
||||
# anchor-based field access and the chunk splitter (fixed chunk1=1027,
|
||||
# chunk2=1055, chunk3=remainder) both handle variable length correctly.
|
||||
# Only enforce a minimum — must have at least chunk1+chunk2 bytes of content.
|
||||
_MIN_COMPLIANCE_LEN = 1027 + 1055 # = 2082
|
||||
if len(raw) < _MIN_COMPLIANCE_LEN:
|
||||
raise ValueError(
|
||||
f"_encode_compliance_config: compliance buffer too short "
|
||||
f"({len(raw)} bytes, need at least {_MIN_COMPLIANCE_LEN})"
|
||||
)
|
||||
if len(raw) not in range(2124, 2132):
|
||||
log.warning(
|
||||
"_encode_compliance_config: unusual compliance buffer length %d "
|
||||
"(expected ~2126); proceeding with anchor-based access",
|
||||
len(raw),
|
||||
)
|
||||
|
||||
buf = bytearray(raw)
|
||||
|
||||
# ── Numeric: recording_mode + sample_rate + record_time (anchor-relative) ──
|
||||
_ANC = b'\xbe\x80\x00\x00\x00\x00'
|
||||
_anc = buf.find(_ANC, 0, 150)
|
||||
|
||||
# Log anchor position every time so we can detect unexpected shifts due to
|
||||
# DLE jitter or firmware differences. Expected position is ~15.
|
||||
if _anc < 0:
|
||||
log.warning(
|
||||
"_encode_compliance_config: anchor NOT FOUND in cfg[0:150] "
|
||||
"(buf len=%d) — all anchor-relative writes will be skipped",
|
||||
len(buf),
|
||||
)
|
||||
else:
|
||||
log.info(
|
||||
"_encode_compliance_config: anchor at cfg[%d] buf_len=%d "
|
||||
"(recording_mode@%d DLE_marker@%d sample_rate@%d:%d "
|
||||
"histogram_interval@%d:%d record_time@%d:%d)",
|
||||
_anc, len(buf),
|
||||
_anc - 8,
|
||||
_anc - 7,
|
||||
_anc - 6, _anc - 4,
|
||||
_anc - 4, _anc - 2,
|
||||
_anc + 6, _anc + 10,
|
||||
)
|
||||
|
||||
if recording_mode is not None:
|
||||
if _anc < 8:
|
||||
log.warning("_encode_compliance_config: anchor not found — cannot write recording_mode")
|
||||
else:
|
||||
# Write to anchor-8, same physical position as the E5 read format.
|
||||
# The byte at anchor-7 is a DLE marker (0x10) that the device firmware
|
||||
# regenerates in every E5 response — it must NOT be overwritten.
|
||||
# Writing to anchor-7 causes the device to add an extra byte on the
|
||||
# next read-back, drifting the anchor by +1 on every write cycle.
|
||||
# (CLAUDE.md "anchor-7 write" was incorrect — confirmed 2026-04-21)
|
||||
buf[_anc - 8] = recording_mode & 0xFF
|
||||
log.debug("_encode_compliance_config: recording_mode=0x%02X -> offset %d",
|
||||
recording_mode, _anc - 8)
|
||||
|
||||
if sample_rate is not None:
|
||||
if _anc < 6:
|
||||
log.warning("_encode_compliance_config: anchor not found — cannot write sample_rate")
|
||||
else:
|
||||
struct.pack_into(">H", buf, _anc - 6, sample_rate)
|
||||
log.debug("_encode_compliance_config: sample_rate=%d -> offset %d", sample_rate, _anc - 6)
|
||||
|
||||
if histogram_interval_sec is not None:
|
||||
if _anc < 4:
|
||||
log.warning("_encode_compliance_config: anchor not found — cannot write histogram_interval")
|
||||
else:
|
||||
struct.pack_into(">H", buf, _anc - 4, histogram_interval_sec)
|
||||
log.debug("_encode_compliance_config: histogram_interval=%ds -> offset %d",
|
||||
histogram_interval_sec, _anc - 4)
|
||||
|
||||
if record_time is not None:
|
||||
if _anc < 0 or _anc + 10 > len(buf):
|
||||
log.warning("_encode_compliance_config: anchor not found — cannot write record_time")
|
||||
else:
|
||||
struct.pack_into(">f", buf, _anc + 6, record_time)
|
||||
log.debug("_encode_compliance_config: record_time=%.3f -> offset %d", record_time, _anc + 6)
|
||||
|
||||
# ── Numeric: channel block (Tran label + unit-string guard) ───────────────
|
||||
# NOTE: tran_pos+24 (write format) or tran_pos+28 (E5 read format) is the
|
||||
# ADC-to-velocity scale factor (6.206053, hardware constant — never written).
|
||||
# geo_range is written to ALL THREE geo channel blocks (Tran, Vert, Long),
|
||||
# confirmed from 4-20-26 captures showing the byte at label+29 in each block.
|
||||
_needs_channel = any(v is not None for v in (trigger_level_geo, alarm_level_geo, geo_range))
|
||||
if _needs_channel:
|
||||
_tran = buf.find(b"Tran", 44)
|
||||
_valid = (
|
||||
_tran >= 0
|
||||
and buf[_tran + 4 : _tran + 5] != b"2"
|
||||
and _tran + 50 <= len(buf)
|
||||
and buf[_tran + 38 : _tran + 42] == b"in.\x00"
|
||||
and buf[_tran + 46 : _tran + 50] == b"/s\x00\x00"
|
||||
)
|
||||
if not _valid:
|
||||
log.warning(
|
||||
"_encode_compliance_config: 'Tran' channel block not found or unit "
|
||||
"guard failed — trigger/alarm/geo_range will not be written"
|
||||
)
|
||||
else:
|
||||
if trigger_level_geo is not None:
|
||||
struct.pack_into(">f", buf, _tran + 34, trigger_level_geo)
|
||||
log.debug("_encode_compliance_config: trigger_level_geo=%.4f -> offset %d", trigger_level_geo, _tran + 34)
|
||||
if alarm_level_geo is not None:
|
||||
struct.pack_into(">f", buf, _tran + 42, alarm_level_geo)
|
||||
log.debug("_encode_compliance_config: alarm_level_geo=%.4f -> offset %d", alarm_level_geo, _tran + 42)
|
||||
if geo_range is not None:
|
||||
# Write geo_range to all three geo channel blocks (Tran, Vert, Long).
|
||||
# Field at label+33 in the E5-format compliance bytes (same in read and write
|
||||
# since the 2126-byte payload is round-tripped verbatim).
|
||||
# 0x00 = Normal 10.000 in/s, 0x01 = Sensitive 1.250 in/s.
|
||||
for _ch_label in (b"Tran", b"Vert", b"Long"):
|
||||
_ch = buf.find(_ch_label, 44)
|
||||
if _ch >= 0 and buf[_ch + 4 : _ch + 5] != b"2" and _ch + 34 <= len(buf):
|
||||
buf[_ch + 33] = geo_range & 0xFF
|
||||
log.debug(
|
||||
"_encode_compliance_config: geo_range=0x%02X -> %s+33 offset %d",
|
||||
geo_range, _ch_label.decode(), _ch + 33,
|
||||
)
|
||||
|
||||
# ── ASCII strings (64-byte slot, value at label_pos+22) ───────────────────
|
||||
def _set_string(label: bytes, value: Optional[str]) -> None:
|
||||
if value is None:
|
||||
return
|
||||
idx = buf.find(label)
|
||||
if idx < 0:
|
||||
log.warning("_encode_compliance_config: label %r not found", label)
|
||||
return
|
||||
val_bytes = value.encode("ascii", errors="replace")[:_COMPLIANCE_VALUE_MAX - 1]
|
||||
padded = val_bytes + b"\x00" * (_COMPLIANCE_VALUE_MAX - len(val_bytes))
|
||||
buf[idx + _COMPLIANCE_VALUE_OFFSET : idx + _COMPLIANCE_SLOT_SIZE] = padded
|
||||
log.debug("_encode_compliance_config: %r -> %r", label, value)
|
||||
|
||||
_set_string(b"Project:", project)
|
||||
_set_string(b"Client:", client_name)
|
||||
_set_string(b"User Name:", operator)
|
||||
_set_string(b"Seis Loc:", seis_loc)
|
||||
_set_string(b"Extended Notes", notes)
|
||||
|
||||
# ── Read-back check: the payload must decode to what was asked ────────────
|
||||
# The decoder is the measured layout (every recorded reply); these offsets are
|
||||
# 1024-sps raw ones. A mode change on BE9441's 10-25 Continuous / 4096 block
|
||||
# rewrote the byte in front of the mode and read back unchanged. Refuse it
|
||||
# here, before push_config_raw sends anything.
|
||||
asked = {"recording_mode": recording_mode, "sample_rate": sample_rate,
|
||||
"histogram_interval_sec": histogram_interval_sec, "record_time": record_time}
|
||||
if any(v is not None for v in asked.values()):
|
||||
before, after = _settings_read_back(raw), _settings_read_back(bytes(buf))
|
||||
if record_time is not None:
|
||||
asked["record_time"] = struct.unpack(">f", struct.pack(">f", record_time))[0]
|
||||
want = {k: (v if v is not None else before[k]) for k, v in asked.items()}
|
||||
wrong = {k: (after[k], want[k]) for k in asked if after[k] != want[k]}
|
||||
if wrong:
|
||||
raise ValueError(
|
||||
"_encode_compliance_config: the patched block would not read back as asked ("
|
||||
+ ", ".join(f"{k} reads {got!r}, not {exp!r}" for k, (got, exp) in wrong.items())
|
||||
+ ") -- refused, nothing built or sent. The encoder's offsets were measured at "
|
||||
"1024 sps and need rewriting on unescaped bytes (#46)."
|
||||
)
|
||||
|
||||
# 2-byte footer — checksum formula unknown; \x00\x00 confirmed accepted by device
|
||||
return bytes(buf) + b"\x00\x00"
|
||||
|
||||
|
||||
def _settings_read_back(data: bytes) -> dict:
|
||||
"""Mode, sample rate, interval and record time as the decoder reads `data`."""
|
||||
info = DeviceInfo(serial="", firmware_minor=0)
|
||||
_decode_compliance_config_into(data, info)
|
||||
cc = info.compliance_config
|
||||
return {k: getattr(cc, k, None) if cc is not None else None
|
||||
for k in ("recording_mode", "sample_rate", "histogram_interval_sec", "record_time")}
|
||||
|
||||
|
||||
def _decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None:
|
||||
|
||||
+148
-18
@@ -13,13 +13,16 @@ Pure: no I/O, and no import from `sfm/`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, Optional, Sequence
|
||||
|
||||
from .bw_xml_report import XmlReport
|
||||
from .event_file_io import (_GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
|
||||
from .event_file_io import (interval_times, _GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
|
||||
decode_blastware_bytes)
|
||||
from .histogram_codec import half_period_to_hz
|
||||
from .models import Event
|
||||
from .waveform_codec import mic_count_to_db
|
||||
|
||||
@@ -30,16 +33,81 @@ GEO_IPS_PER_COUNT: float = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
|
||||
_CHANNELS = ("Tran", "Vert", "Long", "MicL")
|
||||
_EVENT_TYPE = {"Waveform": "Full Waveform", "Histogram": "Full Histogram"}
|
||||
|
||||
# How Blastware prints the setup fields SFM reads (measured 2026-11-03).
|
||||
_MONTHS = ("January", "February", "March", "April", "May", "June", "July",
|
||||
"August", "September", "October", "November", "December")
|
||||
_TRIGGERED_BY = {0x0001: "Tran", 0x0002: "Vert", 0x0004: "Long", 0x0008: "MicL", 0x0200: "Manual"}
|
||||
_STOP_MODES = {0: "Fixed"}
|
||||
_MIC_TYPES = {2: "Linear Weighting"}
|
||||
_GEO_TRIGGERS, _MIC_TRIGGER = 0x07, 0x08
|
||||
# Blastware turns the mic trigger level from psi to dB with 6895 Pa per psi, not
|
||||
# 6894.757: 4,272 / 4,272 DL2 levels against 4,271 (the odd one 0.01 psi,
|
||||
# printed 130.8 dB(L), is 130.7498 at the exact constant).
|
||||
_TRIGGER_PA_PER_PSI = 6895.0
|
||||
|
||||
|
||||
def _setup_values(ev: Event) -> dict[str, object]:
|
||||
out: dict[str, object] = {}
|
||||
di = ev.device_info
|
||||
if di is not None:
|
||||
out["SerialNumber"] = di.serial
|
||||
fw = di.firmware_version or ""
|
||||
if di.dsp_version and fw.startswith("S33") and di.model:
|
||||
# "V 10.72-8.17 MiniMate Plus" from "10.72", "S338.17" and the model --
|
||||
# the only version in DL2, so the rule is proven for it alone.
|
||||
out["Version"] = f"V {di.dsp_version}-{fw[3:]} {di.model}"
|
||||
if di.calibration_date and di.calibrated_by:
|
||||
c = di.calibration_date
|
||||
out["Calibration"] = f"{_MONTHS[c.month - 1]} {c.day}, {c.year} by {di.calibrated_by}"
|
||||
out["BatteryLevel"] = ev.battery_volts
|
||||
out["Trigger"] = _TRIGGERED_BY.get(ev.triggered_by)
|
||||
out["RecordStopMode"] = _STOP_MODES.get(ev.record_stop_mode)
|
||||
out["Microphone"] = _MIC_TYPES.get(ev.mic_type)
|
||||
# dB or psi is Blastware's preference, not the unit's (carve-out
|
||||
# units-is-a-display-preference); SFM reports dB, the default.
|
||||
out["Units"] = "in/s and dB(L)" if ev.mic_type is not None else "in/s"
|
||||
# Blastware prints a trigger level only for a channel that is a trigger
|
||||
# source, and none for a Manual trigger.
|
||||
src, manual = ev.trigger_sources or 0, ev.triggered_by == 0x0200
|
||||
if src & _GEO_TRIGGERS and not manual:
|
||||
out["GeoTriggerLevel"] = ev.trigger_level_geo
|
||||
if src & _MIC_TRIGGER and not manual and ev.trigger_level_mic_psi:
|
||||
psi = ev.trigger_level_mic_psi
|
||||
out["MicTriggerLevel psi(L)"] = psi
|
||||
out["MicTriggerLevel dB(L)"] = 20 * math.log10(psi * _TRIGGER_PA_PER_PSI / 2e-5)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class SfmSide:
|
||||
event: Event
|
||||
values: dict[str, object] # reference tag -> SFM's value; absent or None = blank
|
||||
notes: list[str] # non-empty user-note slots, in order
|
||||
job_number: Optional[str] # None until the decoder reads it
|
||||
job_number: Optional[str] # only when the file says Blastware shows it
|
||||
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
|
||||
counts: dict[str, list[int]] # waveform samples or histogram interval peaks
|
||||
geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it
|
||||
# interval column -> SFM's value per interval (a number, or Blastware's word)
|
||||
interval_values: dict[str, list[object]] = field(default_factory=dict)
|
||||
interval_times: Optional[list[str]] = None # each interval's printed time
|
||||
|
||||
|
||||
def interval_frequency(halfp: int, sample_rate: int) -> object:
|
||||
"""An interval's frequency as Blastware prints it: "N/A" for a half-period
|
||||
of 0, ">100" (">200" at 2048 sps) at 5 samples or fewer, "<1.0" below 1 Hz,
|
||||
else (sample rate / 2) / half-period in Hz. Measured on ~3.1 M DL2 cells,
|
||||
2026-11-03 (#50: the rate, not a fixed 512)."""
|
||||
if halfp == 0:
|
||||
return "N/A"
|
||||
hz = half_period_to_hz(halfp, sample_rate)
|
||||
if hz is None:
|
||||
return f">{round(100 * sample_rate / 1024)}"
|
||||
return "<1.0" if hz < 1.0 else hz
|
||||
|
||||
|
||||
def _interval_size(seconds: int) -> str:
|
||||
n, unit = (seconds // 60, "minute") if seconds % 60 == 0 else (seconds, "second")
|
||||
return f"{n} {unit}{'' if n == 1 else 's'}"
|
||||
|
||||
|
||||
def sfm_side(raw: bytes) -> SfmSide:
|
||||
@@ -69,19 +137,58 @@ def sfm_side(raw: bytes) -> SfmSide:
|
||||
if pv is not None:
|
||||
values.update(TranPPV=pv.tran, VertPPV=pv.vert, LongPPV=pv.long,
|
||||
PeakVectorSum=pv.peak_vector_sum)
|
||||
# A waveform's peak detail (None on a histogram, so not reported).
|
||||
for tag, value in (("TranTimeofPeak", pv.tran_time_of_peak),
|
||||
("VertTimeofPeak", pv.vert_time_of_peak),
|
||||
("LongTimeofPeak", pv.long_time_of_peak),
|
||||
("MicLTimeofPeak", pv.micl_time_of_peak),
|
||||
("PeakVectorSumTimeSum", pv.pvs_time),
|
||||
("TranPeakAcceleration", pv.tran_peak_accel_g),
|
||||
("VertPeakAcceleration", pv.vert_peak_accel_g),
|
||||
("LongPeakAcceleration", pv.long_peak_accel_g)):
|
||||
if value is not None:
|
||||
values[tag] = value
|
||||
if counts["MicL"]:
|
||||
values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"]))
|
||||
values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None
|
||||
values.update(_setup_values(ev))
|
||||
if ev.stop_time is not None:
|
||||
values.update(HistogramStopDate=ev.stop_time.strftime("%Y-%m-%d"),
|
||||
HistogramStopTime=ev.stop_time.strftime("%H:%M:%S"))
|
||||
if ev.histogram_interval_sec:
|
||||
values["IntervalSize"] = _interval_size(ev.histogram_interval_sec)
|
||||
interval_values: dict[str, list[object]] = {}
|
||||
if ev.interval_half_periods and ev.sample_rate:
|
||||
for ch, hps in ev.interval_half_periods.items():
|
||||
interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps]
|
||||
if ev.interval_pvs:
|
||||
interval_values["Geo PVS in/s"] = list(ev.interval_pvs)
|
||||
times = None
|
||||
n = len(counts["Tran"])
|
||||
if ev.record_type == "Histogram" and ts is not None and ev.histogram_interval_sec and n:
|
||||
start = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
|
||||
ends = interval_times(start, ev.histogram_interval_sec, ev.stop_time, n)
|
||||
times = [t.strftime("%Y-%m-%d %H:%M:%S") for t in ends]
|
||||
# A peak's date and time are those of the interval holding it (first).
|
||||
for tag, series in (("TranPeak", counts["Tran"]), ("VertPeak", counts["Vert"]),
|
||||
("LongPeak", counts["Long"]), ("MicL", counts["MicL"]),
|
||||
("PeakVectorSum", ev.interval_pvs)):
|
||||
if series and len(series) == n:
|
||||
j = max(range(n), key=lambda q: abs(series[q]))
|
||||
values[f"{tag}Date"] = ends[j].strftime("%Y-%m-%d")
|
||||
values[f"{tag}Time"] = ends[j].strftime("%H:%M:%S")
|
||||
|
||||
return SfmSide(
|
||||
event=ev,
|
||||
values=values,
|
||||
notes=[v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v]
|
||||
if pi is not None else [],
|
||||
job_number=None,
|
||||
job_number=str(pi.job_number) if pi is not None and pi.job_number_enabled else None,
|
||||
channels=[ch for ch in _CHANNELS if counts[ch]],
|
||||
counts=counts,
|
||||
geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS,
|
||||
interval_values=interval_values,
|
||||
interval_times=times,
|
||||
)
|
||||
|
||||
|
||||
@@ -144,10 +251,12 @@ def _mic_converter(ref: XmlReport) -> Optional[Callable[[int], float]]:
|
||||
def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> FieldResult:
|
||||
if not printed.strip() or printed.strip() == "N/A":
|
||||
return FieldResult(tag, "no_reference", printed, None)
|
||||
if tag == "MicLPSPL":
|
||||
units = ref.event_units or ""
|
||||
key = ("MicLPSPL dB(L)" if "dB(L)" in units else
|
||||
"MicLPSPL psi(L)" if "psi(L)" in units else None)
|
||||
if tag in ("MicLPSPL", "MicTriggerLevel"):
|
||||
# A printed value that states its unit is compared in that unit:
|
||||
# K441LA17.IN0W's Units say psi(L), its MicTriggerLevel "125.0 dB(L)".
|
||||
units = printed if ("dB(L)" in printed or "psi(L)" in printed) else (ref.event_units or "")
|
||||
key = (f"{tag} dB(L)" if "dB(L)" in units else
|
||||
f"{tag} psi(L)" if "psi(L)" in units else None)
|
||||
value = sfm.values.get(key) if key else None
|
||||
else:
|
||||
value = sfm.values.get(tag)
|
||||
@@ -166,9 +275,11 @@ def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> Fie
|
||||
return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed))
|
||||
|
||||
|
||||
def _cell_diff(value: float, printed: str) -> Optional[float]:
|
||||
def _cell_diff(value: object, printed: str) -> Optional[float]:
|
||||
"""|value - printed| when the cell disagrees, else None; inf for a cell that
|
||||
is not a number."""
|
||||
is not a number. A word on SFM's side (">100", "N/A") must be printed."""
|
||||
if isinstance(value, str):
|
||||
return None if _same_text(value, printed) else float("inf")
|
||||
p = _printed_number(printed)
|
||||
if p is None:
|
||||
return float("inf")
|
||||
@@ -237,14 +348,19 @@ def series_pairs(sfm: SfmSide, ref: XmlReport,
|
||||
if field.startswith("intervals."):
|
||||
title = field[len("intervals."):]
|
||||
columns = ref.interval_columns or []
|
||||
convert = _interval_converter(title, sfm)
|
||||
counts = sfm.counts.get(title.partition(" ")[0], [])
|
||||
if convert is None or not counts or title not in columns:
|
||||
if title not in columns:
|
||||
return None
|
||||
i = columns.index(title)
|
||||
cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])]
|
||||
pairs = [(j, cell, convert(c)) for j, (cell, c) in enumerate(zip(cells, counts))]
|
||||
return pairs, abs(len(cells) - len(counts))
|
||||
values = sfm.interval_values.get(title)
|
||||
if values is None:
|
||||
convert = _interval_converter(title, sfm)
|
||||
counts = sfm.counts.get(title.partition(" ")[0], [])
|
||||
if convert is None or not counts:
|
||||
return None
|
||||
values = [convert(c) for c in counts]
|
||||
pairs = [(j, cell, v) for j, (cell, v) in enumerate(zip(cells, values))]
|
||||
return pairs, abs(len(cells) - len(values))
|
||||
return None
|
||||
|
||||
|
||||
@@ -254,7 +370,9 @@ def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> Fiel
|
||||
return FieldResult(field, "sfm_blank", f"{n_bw} rows", None)
|
||||
pairs, row_len = got
|
||||
diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None]
|
||||
n_sfm = len(sfm.counts.get(field.split(".", 1)[1].partition(" ")[0], []))
|
||||
title = field.split(".", 1)[1]
|
||||
n_sfm = (len(sfm.interval_values[title]) if title in sfm.interval_values
|
||||
else len(sfm.counts.get(title.partition(" ")[0], [])))
|
||||
return _series_result(field, n_bw, n_sfm, diffs, row_len)
|
||||
|
||||
|
||||
@@ -265,12 +383,21 @@ def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||
|
||||
|
||||
def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||
"""One result per column, plus the interval times, which SFM does not keep."""
|
||||
"""One result per column, plus the interval times."""
|
||||
n = len(ref.intervals or [])
|
||||
return ([FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)]
|
||||
return ([_compare_interval_times(sfm, ref, n)]
|
||||
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
|
||||
|
||||
|
||||
def _compare_interval_times(sfm: SfmSide, ref: XmlReport, n: int) -> FieldResult:
|
||||
if sfm.interval_times is None:
|
||||
return FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)
|
||||
diffs = [(j, float("inf")) for j, ((t, _), s) in enumerate(zip(ref.intervals or [], sfm.interval_times))
|
||||
if not _same_text(s, t)]
|
||||
return _series_result("intervals.Time", n, len(sfm.interval_times), diffs,
|
||||
abs(n - len(sfm.interval_times)))
|
||||
|
||||
|
||||
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]:
|
||||
"""Every field Blastware's report carries, set against what SFM produced.
|
||||
A mismatch a carve-out covers and applies to becomes `accepted`."""
|
||||
@@ -289,6 +416,9 @@ def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ())
|
||||
if sfm.job_number is None else
|
||||
FieldResult("JobNumber", "match" if _same_text(sfm.job_number, ref.job_number)
|
||||
else "mismatch", ref.job_number, sfm.job_number))
|
||||
elif sfm.job_number is not None:
|
||||
# SFM says the job number is shown; Blastware printed none.
|
||||
out.append(FieldResult("JobNumber", "mismatch", None, sfm.job_number))
|
||||
out.append(FieldResult("Channels", "match" if ref.channels == sfm.channels else "mismatch",
|
||||
" ".join(ref.channels), " ".join(sfm.channels)))
|
||||
if ref.sample_rows is not None:
|
||||
|
||||
@@ -68,6 +68,21 @@ def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
|
||||
got = series_pairs(sfm, ref, res.field)
|
||||
if got is None or got[1]:
|
||||
return False
|
||||
if res.field == "intervals.Geo PVS in/s":
|
||||
# Per interval, as PeakVectorSum: an OORANGE vector sum, SFM's sum within
|
||||
# three channels at the ceiling, and a channel Blastware itself clamped in
|
||||
# that interval. 17 / 17 DL2 cells, SFM 10.01 .. 17.33 (2026-11-03).
|
||||
cols = ref.interval_columns or []
|
||||
peaks = [cols.index(c) for c in ("Tran Peak in/s", "Vert Peak in/s", "Long Peak in/s")
|
||||
if c in cols]
|
||||
rows = ref.intervals or []
|
||||
differing = [(j, cell, v) for j, cell, v in got[0]
|
||||
if isinstance(v, str) or not matches_printed(v, cell)]
|
||||
return bool(differing) and all(
|
||||
cell.strip() == "OORANGE" and not isinstance(v, str)
|
||||
and r - _TOL <= v <= 3 ** 0.5 * r * 1.01
|
||||
and any(_clamped(rows[j][1][p], r) for p in peaks if p < len(rows[j][1]))
|
||||
for j, cell, v in differing)
|
||||
differing = [(cell, v) for _, cell, v in got[0] if not matches_printed(v, cell)]
|
||||
return bool(differing) and all(
|
||||
_clamped(cell, r) and _at_ceiling(v, r)
|
||||
@@ -79,11 +94,59 @@ SATURATION = Carveout(
|
||||
id="saturation",
|
||||
fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
|
||||
"samples.Tran", "samples.Vert", "samples.Long",
|
||||
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s"),
|
||||
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s",
|
||||
"intervals.Geo PVS in/s"),
|
||||
evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; "
|
||||
"the file holds counts past full scale (32016 counts = 10.005 in/s observed). "
|
||||
"scratch/verify_against_ascii.py, 2026-08-28."),
|
||||
"scratch/verify_against_ascii.py, 2026-08-28. An interval's vector sum prints "
|
||||
"OORANGE when it exceeds the range in an interval with a clamped channel: 17 / 17 "
|
||||
"DL2 cells, 2026-11-03."),
|
||||
applies=_saturation,
|
||||
)
|
||||
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION,)
|
||||
def _interval_count_is_duration(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
|
||||
"""Blastware's count exceeds the intervals in its own table, and SFM decoded
|
||||
exactly the table's."""
|
||||
p = _printed_number(res.bw or "")
|
||||
n = sfm.values.get("NumberofIntervals")
|
||||
rows = len(ref.intervals or [])
|
||||
return p is not None and n is not None and rows == n and p[0] > n
|
||||
|
||||
|
||||
INTERVAL_COUNT_IS_DURATION = Carveout(
|
||||
id="interval-count-is-duration",
|
||||
fields=("NumberofIntervals",),
|
||||
evidence=("Blastware's Number of Intervals is (stop - start) / interval from the file's "
|
||||
"footer times -- exact on T193KSWP.FF0H (2,880), M462KSWR.1R0H (1,650) and "
|
||||
"T193KY0A.740H (6,390). Its own interval table lists the intervals the file "
|
||||
"holds: one block (30 at 2 s) fewer when the unit never wrote the last minute. "
|
||||
"2026-11-02."),
|
||||
applies=_interval_count_is_duration,
|
||||
)
|
||||
|
||||
_MIC_UNITS = ("in/s and dB(L)", "in/s and psi(L)")
|
||||
|
||||
|
||||
def _units_is_a_display_preference(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
|
||||
"""Both sides say the event has a mic; they differ only in dB against psi."""
|
||||
return (" ".join((res.bw or "").split()) in _MIC_UNITS
|
||||
and sfm.values.get("Units") in _MIC_UNITS)
|
||||
|
||||
|
||||
UNITS_IS_A_DISPLAY_PREFERENCE = Carveout(
|
||||
id="units-is-a-display-preference",
|
||||
fields=("Units",),
|
||||
evidence=("dB(L) or psi(L) is Blastware's display preference on the PC when it wrote the "
|
||||
"report, not the unit's: in report-write order (the _XML.XML mtimes) DL2's 70,034 "
|
||||
"reports switch fleet-wide in 61 clean runs, every unit at once, and no byte or "
|
||||
"bit of the event file separates the two (k-240 .. k+520, nor the 1.2 KB before "
|
||||
"the footer). Instantel documents both settings: the unit's own Microphone "
|
||||
"Units (MiniMate Plus manual 716U0101 Rev 15 §3.9.7: psi(L), dB(L) or Pa(L), "
|
||||
"keypad Right Arrow + Setups) and Blastware's report preference (Blastware "
|
||||
"manual 714U0301 Rev 22 §4, Preferences > Units and Channel: Show Mic in dB / "
|
||||
"in Linear Units). 2026-11-03."),
|
||||
applies=_units_is_a_display_preference,
|
||||
)
|
||||
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION, INTERVAL_COUNT_IS_DURATION,
|
||||
UNITS_IS_A_DISPLAY_PREFERENCE)
|
||||
+314
-57
@@ -19,18 +19,19 @@ import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
|
||||
from .models import Event, PeakValues, ProjectInfo, Timestamp
|
||||
from .models import DeviceInfo, Event, PeakValues, ProjectInfo, Timestamp
|
||||
from . import blastware_file as _bw # avoid circular reference at module load
|
||||
from .bw_ascii_report import BwAsciiReport
|
||||
from . import waveform_codec as _wc
|
||||
from .waveform_codec import decode_waveform_v2, decoded_to_adc_counts
|
||||
from .histogram_codec import decode_histogram_body, interval_pvs
|
||||
from .histogram_codec import channels_from_records, decode_histogram_body, decode_histogram_body_full
|
||||
|
||||
# Reference pressure for dB(L) → psi conversion (20 µPa expressed in psi).
|
||||
# Same constant as sfm/sfm_webapp.html so server-side and browser-side
|
||||
@@ -51,7 +52,7 @@ SIDECAR_KIND = "sfm.event"
|
||||
# bumped without a `pip install` re-run — leading to confusing stale
|
||||
# version stamps in sidecars. Bump this constant and CHANGELOG.md
|
||||
# together at release time.
|
||||
TOOL_VERSION = "0.33.0" # setup + notes, record type, histogram PVS and mic from the file; gates the backfill regen
|
||||
TOOL_VERSION = "0.34.0" # file-only decode groups A-D, histogram times (#51); gates the backfill regen
|
||||
|
||||
try:
|
||||
# Best-effort: prefer the installed metadata when it's NEWER than the
|
||||
@@ -793,6 +794,45 @@ def _peaks_from_samples(samples: dict[str, list[int]],
|
||||
)
|
||||
|
||||
|
||||
# Blastware's g for peak acceleration, fitted: every printed acceleration in
|
||||
# DL2 bounds it, and together they leave [386.2236, 386.2240] in/s^2 -- 19,475 /
|
||||
# 19,479 values fit (the other 4: one odd file, O117I1NK.R70W, and one sample
|
||||
# mismatch). That is 9.81 m/s^2 (386.2205) plus an offset not explained, as
|
||||
# with the mic's fitted dB offset; 9.81 gives 19,423, the standard 9.80665 gives
|
||||
# 17,806 (2026-11-04).
|
||||
_ACCEL_IPS2_PER_G = 386.2238
|
||||
|
||||
|
||||
def _waveform_peak_detail(pv: PeakValues, samples: dict[str, list[int]], geo_fs_ins: float,
|
||||
sample_rate: int, pretrig: int) -> None:
|
||||
"""A waveform's time of peak per channel, the vector sum's time and each
|
||||
geophone's peak acceleration, on `pv`. Measured on 400 DL2 waveforms
|
||||
(2026-11-04):
|
||||
* time of peak = (first peak sample - pre-trigger samples) / sample rate,
|
||||
1,197 / 1,197; the vector-sum time is the same on sqrt(T^2 + V^2 + L^2),
|
||||
398 / 399
|
||||
* peak acceleration = the largest |v[i+1] - v[i]| x sample rate / g,
|
||||
with Blastware's fitted g -- the manuals: "subtracts two velocity
|
||||
readings and divides the result by the elapsed time between them"."""
|
||||
scale = geo_fs_ins / _GEO_INT16_FS
|
||||
geo = {}
|
||||
for ch in ("Tran", "Vert", "Long", "MicL"):
|
||||
c = samples.get(ch) or []
|
||||
if not c:
|
||||
continue
|
||||
i = max(range(len(c)), key=lambda k: abs(c[k]))
|
||||
setattr(pv, f"{ch.lower()}_time_of_peak", (i - pretrig) / sample_rate)
|
||||
if ch != "MicL":
|
||||
geo[ch] = c
|
||||
step = max((abs(c[k + 1] - c[k]) for k in range(len(c) - 1)), default=0)
|
||||
setattr(pv, f"{ch.lower()}_peak_accel_g", step * scale * sample_rate / _ACCEL_IPS2_PER_G)
|
||||
if len(geo) == 3:
|
||||
n = min(len(c) for c in geo.values())
|
||||
t, v, l = geo["Tran"], geo["Vert"], geo["Long"]
|
||||
j = max(range(n), key=lambda k: t[k] * t[k] + v[k] * v[k] + l[k] * l[k])
|
||||
pv.pvs_time = (j - pretrig) / sample_rate
|
||||
|
||||
|
||||
# STRT[18], the record-type byte (#41): 0x46 on every one of DL2's 6,577
|
||||
# waveform files and 0x0A on every one of its 63,535 histograms (measured
|
||||
# 2026-10-29). Manual / Event / Combo never occur there, so their bytes are
|
||||
@@ -862,6 +902,7 @@ _RECTIME_OFFSET_BEFORE_MARKER = 30
|
||||
# 2026-10-29). Offsets are from the first byte of the name.
|
||||
_SETUP_NAME_RE = re.compile(rb"\x1c\x08([\x20-\x7e]{1,40})\x00")
|
||||
_SAMPLE_RATE_BEFORE_NAME = 42 # uint16 BE, samples per second
|
||||
_INTERVAL_BEFORE_NAME = 40 # uint16 BE, histogram interval in seconds (2 / 5 / 15 / 60 / 300)
|
||||
_PRETRIG_BEFORE_NAME = 36 # float32 BE, seconds, negative (-0.25, -0.0625 ...)
|
||||
_RECTIME_BEFORE_NAME = 30 # float32 BE, seconds (the marker's offset above)
|
||||
_SAMPLE_RATES = (1024, 2048, 4096)
|
||||
@@ -895,17 +936,22 @@ def _ts8(b: bytes) -> Optional[datetime.datetime]:
|
||||
def _embedded_event_record(
|
||||
raw: bytes, end: int, start: Optional[datetime.datetime],
|
||||
stop: Optional[datetime.datetime], record_time: Optional[float],
|
||||
) -> tuple[Optional[datetime.datetime], str]:
|
||||
"""The trigger time from the instrument's embedded event record, or (None, why).
|
||||
) -> tuple[Optional[datetime.datetime], str, Optional[int]]:
|
||||
"""The trigger time and trigger source from the instrument's embedded event
|
||||
record, or (None, why, None).
|
||||
|
||||
Every `fe 80` before `end` (the footer) is a candidate. One counts only if
|
||||
its lead bytes match, both its times are well formed, the footer's session
|
||||
start <= trigger <= its stop, its stop is the footer's stop or a second
|
||||
before it, and its length agrees with the record time. Exactly one may
|
||||
pass: none, or more than one, is reported rather than guessed between.
|
||||
|
||||
The two bytes between the lead and `fe 80` are the trigger source, a uint16
|
||||
BE bitmask: 0x01 Tran, 0x02 Vert, 0x04 Long, 0x08 MicL, 0x200 Manual --
|
||||
Blastware's Trigger on 6,493 / 6,493 DL2 waveforms (2026-11-03).
|
||||
"""
|
||||
if start is None or stop is None:
|
||||
return None, "the footer has no start and stop to check one against"
|
||||
return None, "the footer has no start and stop to check one against", None
|
||||
found, rejected = [], 0
|
||||
i = raw.find(_EVENT_RECORD_MARKER, 6)
|
||||
while 0 <= i and i + 18 <= end:
|
||||
@@ -921,15 +967,62 @@ def _embedded_event_record(
|
||||
<= _EVENT_RECORD_SLACK_S[1])
|
||||
)
|
||||
if valid:
|
||||
found.append(trig)
|
||||
found.append((trig, int.from_bytes(raw[i - 2:i], "big")))
|
||||
else:
|
||||
rejected += 1
|
||||
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
|
||||
if len(found) == 1:
|
||||
return found[0], ""
|
||||
return found[0][0], "", found[0][1]
|
||||
if found:
|
||||
return None, f"{len(found)} candidates validate"
|
||||
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
|
||||
return None, f"{len(found)} candidates validate", None
|
||||
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None
|
||||
|
||||
|
||||
# A histogram's event record: the same lead, the source 0x0400, marker fe f5,
|
||||
# then its start and stop -- Blastware's Histogram Start / Stop on 63,490 /
|
||||
# 63,490 DL2 histograms. On all 63,500 its start is 0 or 1 s after the footer's
|
||||
# start and its stop 0 or 1 s before the footer's stop (2026-11-03).
|
||||
_HISTOGRAM_RECORD_MARKER = b"\xfe\xf5"
|
||||
_HISTOGRAM_RECORD_SOURCE = b"\x04\x00"
|
||||
|
||||
|
||||
def interval_times(start: datetime.datetime, interval_sec: int,
|
||||
stop: Optional[datetime.datetime], n: int) -> list[datetime.datetime]:
|
||||
"""Each histogram interval's time as Blastware prints it: the interval's
|
||||
end, start + (i + 1) x interval, capped at the stop. 2,308,524 / 2,308,524
|
||||
DL2 rows; and an event's peak date and time are its interval's (2026-11-03)."""
|
||||
out = []
|
||||
for i in range(n):
|
||||
t = start + datetime.timedelta(seconds=interval_sec * (i + 1))
|
||||
out.append(min(t, stop) if stop is not None else t)
|
||||
return out
|
||||
|
||||
|
||||
def _histogram_event_record(
|
||||
raw: bytes, end: int, start: Optional[datetime.datetime],
|
||||
stop: Optional[datetime.datetime],
|
||||
) -> tuple[Optional[datetime.datetime], Optional[datetime.datetime], str]:
|
||||
"""(start, stop) from a histogram's own event record, or (None, None, why).
|
||||
Exactly one record may validate against the footer's start and stop."""
|
||||
if start is None or stop is None:
|
||||
return None, None, "the footer has no start and stop to check one against"
|
||||
found, rejected = [], 0
|
||||
i = raw.find(_HISTOGRAM_RECORD_MARKER, 6)
|
||||
while 0 <= i and i + 18 <= end:
|
||||
a, b = _ts8(raw[i + 2:i + 10]), _ts8(raw[i + 10:i + 18])
|
||||
if (raw[i - 6:i - 2] == _EVENT_RECORD_LEAD and raw[i - 2:i] == _HISTOGRAM_RECORD_SOURCE
|
||||
and a is not None and b is not None and a <= b
|
||||
and 0 <= (a - start).total_seconds() <= 1
|
||||
and 0 <= (stop - b).total_seconds() <= 1):
|
||||
found.append((a, b))
|
||||
elif raw[i - 6:i - 2] == _EVENT_RECORD_LEAD:
|
||||
rejected += 1
|
||||
i = raw.find(_HISTOGRAM_RECORD_MARKER, i + 1)
|
||||
if len(found) == 1:
|
||||
return found[0][0], found[0][1], ""
|
||||
if found:
|
||||
return None, None, f"{len(found)} candidates validate"
|
||||
return None, None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
|
||||
|
||||
|
||||
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
||||
@@ -996,8 +1089,29 @@ def _setup_notes(raw: bytes) -> ProjectInfo:
|
||||
text = [p.decode("ascii", errors="replace").strip() or None for p in parts]
|
||||
text += [None] * (2 + 2 * _NOTE_SLOTS - len(text))
|
||||
project, client, operator, location = text[2:2 + 2 * _NOTE_SLOTS:2]
|
||||
enabled, number = _setup_job_number(raw, k)
|
||||
return ProjectInfo(setup_name=text[0], project=project, client=client,
|
||||
operator=operator, sensor_location=location)
|
||||
operator=operator, sensor_location=location,
|
||||
job_number_enabled=enabled, job_number=number)
|
||||
|
||||
|
||||
# The job number, in Series IV's 0x1A layout ([39] report flags, [40:42] the
|
||||
# number): flags at k - 9, bit 0x02 = shown; the number, uint16 BE, at k - 8,
|
||||
# kept while switched off. The flag matches Blastware's JobNumber on 2,997 /
|
||||
# 2,997 DL2 events that print one and 66,986 / 66,986 that don't, and every
|
||||
# printed value matches (all are 1; measured 2026-11-02).
|
||||
_REPORT_FLAGS_BEFORE_NAME = 9
|
||||
_JOB_NUMBER_BEFORE_NAME = 8
|
||||
_JOB_NUMBER_ON = 0x02
|
||||
|
||||
|
||||
def _setup_job_number(raw: bytes, k: int) -> tuple[Optional[bool], Optional[int]]:
|
||||
"""(shown, number) from the setup block whose name starts at k."""
|
||||
if k < _REPORT_FLAGS_BEFORE_NAME:
|
||||
return None, None
|
||||
flags = raw[k - _REPORT_FLAGS_BEFORE_NAME]
|
||||
j = k - _JOB_NUMBER_BEFORE_NAME
|
||||
return bool(flags & _JOB_NUMBER_ON), int.from_bytes(raw[j:j + 2], "big")
|
||||
|
||||
|
||||
# The geophone range sits in the setup's channel blocks, which follow the
|
||||
@@ -1026,6 +1140,83 @@ def _setup_geo_range(raw: bytes) -> tuple[Optional[int], Optional[str]]:
|
||||
return None, f"geophone range not read: channel range bytes {found}"
|
||||
|
||||
|
||||
# The identity block before the setup: what the live read gets from SUB FE
|
||||
# (DeviceInfo). Offsets back from k, the setup name; matched against every DL2
|
||||
# report 2026-11-03 -- serial, version and calibration 69,983 / 69,983, the
|
||||
# battery 69,729 plus 254 that Blastware rounds half up (6.25 -> "6.3 Volts").
|
||||
_SERIAL_BEFORE_NAME = 202 # ASCII, NUL-terminated
|
||||
_BATTERY_BEFORE_NAME = 190 # uint16 BE, hundredths of a volt
|
||||
_FIRMWARE_MINOR_BEFORE_NAME = 193 # 0x11 = 17 for S338.17, as SUB EA
|
||||
_FIRMWARE_BEFORE_NAME = 147 # "S338.17"
|
||||
_DSP_BEFORE_NAME = 138 # "10.72"
|
||||
_CALIBRATION_BEFORE_NAME = 132 # dd mm yyyy (BE)
|
||||
_CALIBRATED_BY_BEFORE_NAME = 128 # "Instantel"
|
||||
_MANUFACTURER_BEFORE_NAME = 94 # "Instantel"
|
||||
_MODEL_BEFORE_NAME = 72 # "MiniMate Plus" / "BlastMate III"
|
||||
|
||||
|
||||
def _cstr(raw: bytes, i: int, limit: int = 40) -> Optional[str]:
|
||||
if i < 0:
|
||||
return None
|
||||
j = raw.find(b"\x00", i, i + limit)
|
||||
s = raw[i:j if j >= 0 else i + limit].decode("ascii", errors="replace").strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _setup_identity(raw: bytes, k: int) -> tuple[Optional[DeviceInfo], Optional[float]]:
|
||||
"""(the unit's identity, the battery in volts) from the block before the
|
||||
setup name at k."""
|
||||
if k < _SERIAL_BEFORE_NAME:
|
||||
return None, None
|
||||
serial = _cstr(raw, k - _SERIAL_BEFORE_NAME, 16)
|
||||
if not serial:
|
||||
return None, None
|
||||
c = k - _CALIBRATION_BEFORE_NAME
|
||||
try:
|
||||
cal = datetime.date(int.from_bytes(raw[c + 2:c + 4], "big"), raw[c + 1], raw[c])
|
||||
except ValueError:
|
||||
cal = None
|
||||
info = DeviceInfo(
|
||||
serial=serial,
|
||||
firmware_minor=raw[k - _FIRMWARE_MINOR_BEFORE_NAME],
|
||||
firmware_version=_cstr(raw, k - _FIRMWARE_BEFORE_NAME, 9),
|
||||
dsp_version=_cstr(raw, k - _DSP_BEFORE_NAME, 6),
|
||||
manufacturer=_cstr(raw, k - _MANUFACTURER_BEFORE_NAME),
|
||||
model=_cstr(raw, k - _MODEL_BEFORE_NAME),
|
||||
calibration_date=cal,
|
||||
calibrated_by=_cstr(raw, k - _CALIBRATED_BY_BEFORE_NAME, 32),
|
||||
)
|
||||
b = k - _BATTERY_BEFORE_NAME
|
||||
return info, int.from_bytes(raw[b:b + 2], "big") / 100
|
||||
|
||||
|
||||
# Trigger settings, in Series IV's 0x1A layout again: the trigger-source bitmask
|
||||
# at k - 19 ([29]: 0x07 geophones, 0x08 mic), the stop mode at k - 31 ([17],
|
||||
# 0 = Fixed), and each channel block's trigger level, a float32 at label + 30 --
|
||||
# in/s for a geophone, psi for the mic. The mic block's type code at label + 4
|
||||
# is Series IV's (2 = linear). Against every DL2 waveform (2026-11-03): the geo
|
||||
# level 6,447 / 6,447, the mic level 4,403 / 4,403, and Blastware prints a level
|
||||
# exactly when its channel is a trigger source and the event was not Manual.
|
||||
_TRIGGER_SOURCES_BEFORE_NAME = 19
|
||||
_STOP_MODE_BEFORE_NAME = 31
|
||||
_TRIGGER_LEVEL_AFTER_LABEL = 30
|
||||
_MIC_TYPE_AFTER_LABEL = 4
|
||||
|
||||
|
||||
def _setup_trigger(raw: bytes, k: int) -> dict:
|
||||
out = {"trigger_sources": raw[k - _TRIGGER_SOURCES_BEFORE_NAME],
|
||||
"record_stop_mode": raw[k - _STOP_MODE_BEFORE_NAME]}
|
||||
t = raw.find(b"\x00\x00\x01Tran", k, k + _CHANNEL_BLOCK_SPAN)
|
||||
if t >= 0:
|
||||
p = t + 3 + _TRIGGER_LEVEL_AFTER_LABEL
|
||||
out["trigger_level_geo"] = struct.unpack_from(">f", raw, p)[0]
|
||||
m = raw.find(b"MicL", k, k + _CHANNEL_BLOCK_SPAN)
|
||||
if m >= 0:
|
||||
out["trigger_level_mic_psi"] = struct.unpack_from(">f", raw, m + _TRIGGER_LEVEL_AFTER_LABEL)[0]
|
||||
out["mic_type"] = int.from_bytes(raw[m + _MIC_TYPE_AFTER_LABEL:m + _MIC_TYPE_AFTER_LABEL + 4], "big")
|
||||
return out
|
||||
|
||||
|
||||
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
|
||||
"""Parse a Blastware event file into an Event: `decode_blastware_bytes` on its
|
||||
bytes, `name` defaulting to the file's own (see there -- never a time source)."""
|
||||
@@ -1077,22 +1268,34 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
|
||||
# Footer: locate the 0e 08 marker, validating the year is in a sane range.
|
||||
body_start = _bw._WAVEFORM_HEADER_SIZE + 21
|
||||
# The 0e 08 + plausible-year footer signature can occur inside the sample
|
||||
# stream. Collect every candidate and prefer the first whose body yields a
|
||||
# waveform record chain terminating on the 0x06 marker; fall back to the
|
||||
# first candidate otherwise. Blast radius measured 2026-08-25: changes the
|
||||
# chosen footer on exactly 1 of 1,388 series-3 waveform files
|
||||
# (BE17353/S353L4O5.OX0W, false positive at 3800, real footer at 8576).
|
||||
footer_candidates = []
|
||||
pos = body_start
|
||||
while True:
|
||||
pos = raw.find(b"\x0e\x08", pos)
|
||||
if pos < 0 or pos + 26 > len(raw):
|
||||
break
|
||||
yr = (raw[pos + 4] << 8) | raw[pos + 5]
|
||||
if 2015 <= yr <= 2050:
|
||||
footer_candidates.append(pos)
|
||||
pos += 1
|
||||
# The footer is the file's last 26 bytes whenever they are one -- 0e 08 and
|
||||
# two valid times: 70,041 / 70,041 DL2 files (measured 2026-11-03). Taking
|
||||
# the first "0e 08 + plausible year" instead found, on 14 of them, an
|
||||
# earlier record ~1.1 KB before the end holding the stop time and zeros: a
|
||||
# histogram then started at its own stop (a day late on BE9558's daily
|
||||
# histograms) and a waveform lost its stop, so its trigger time too.
|
||||
#
|
||||
# Otherwise the search below stands. The signature can occur inside the
|
||||
# sample stream, so it prefers the first candidate whose body yields a
|
||||
# waveform record chain terminating on the 0x06 marker, then the first
|
||||
# candidate (2026-08-25: BE17353/S353L4O5.OX0W, false positive at 3800,
|
||||
# real footer at 8576).
|
||||
end = len(raw) - 26
|
||||
if (end >= body_start and raw[end:end + 2] == b"\x0e\x08"
|
||||
and _bw._decode_ts_be(raw[end + 2:end + 10]) is not None
|
||||
and _bw._decode_ts_be(raw[end + 10:end + 18]) is not None):
|
||||
footer_candidates = [end]
|
||||
else:
|
||||
footer_candidates = []
|
||||
pos = body_start
|
||||
while True:
|
||||
pos = raw.find(b"\x0e\x08", pos)
|
||||
if pos < 0 or pos + 26 > len(raw):
|
||||
break
|
||||
yr = (raw[pos + 4] << 8) | raw[pos + 5]
|
||||
if 2015 <= yr <= 2050:
|
||||
footer_candidates.append(pos)
|
||||
pos += 1
|
||||
|
||||
footer_pos = -1
|
||||
for cand in footer_candidates:
|
||||
@@ -1149,18 +1352,40 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
# mode, synthetic test input), fall back to empty channels — the
|
||||
# rest of the event (timestamp, waveform_key, project strings) is
|
||||
# still recoverable and useful.
|
||||
decoded = decode_waveform_v2(body)
|
||||
# Discriminator for the timestamp logic below: a waveform (trigger) event
|
||||
# vs a histogram window. Keyed on the codec, not the filename — the
|
||||
# save_imported_bw path passes a tmp ".bw" name whose extension lies.
|
||||
is_waveform_body = decoded is not None
|
||||
if decoded is None:
|
||||
decoded = decode_histogram_body(body)
|
||||
#
|
||||
# The record type comes from the bytes: STRT[18] (#41), 0x46 / 0x0A on
|
||||
# 70,041 / 70,041 DL2 files. It picks the codec. Trying the waveform codec
|
||||
# first handed it BE9440 / BE9557 / BE17354's 2018 5 s histograms, which it
|
||||
# accepted and returned ~5x too many "samples" for. Only an unknown type
|
||||
# falls back to the old trial order. The filename's last letter is only a
|
||||
# cross-check -- SFM's own downloads have no name, and a manual download's
|
||||
# (".QZ0") carries no type at all.
|
||||
type_byte = strt_raw[18]
|
||||
record_type = _RECORD_TYPE_BY_STRT.get(type_byte)
|
||||
problems = []
|
||||
if record_type is None:
|
||||
problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]")
|
||||
hist_records = None
|
||||
if record_type == "Histogram":
|
||||
hist_records = decode_histogram_body_full(body)
|
||||
decoded = channels_from_records(hist_records)
|
||||
is_waveform_body = False
|
||||
elif record_type == "Waveform":
|
||||
decoded = decode_waveform_v2(body)
|
||||
is_waveform_body = True
|
||||
else:
|
||||
decoded = decode_waveform_v2(body)
|
||||
is_waveform_body = decoded is not None
|
||||
if decoded is None:
|
||||
hist_records = decode_histogram_body_full(body)
|
||||
decoded = channels_from_records(hist_records)
|
||||
if decoded is None:
|
||||
log.warning(
|
||||
"%s: body codec failed to decode (body starts %s) — "
|
||||
"raw_samples will be empty", label, body[:8].hex(" "),
|
||||
)
|
||||
if record_type is not None:
|
||||
problems.append(f"the {record_type.lower()} codec could not decode the body")
|
||||
samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
|
||||
else:
|
||||
samples = decoded_to_adc_counts(decoded)
|
||||
@@ -1169,13 +1394,8 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
ev = Event(index=-1)
|
||||
if strt_fields.get("waveform_key"):
|
||||
ev._waveform_key = bytes.fromhex(strt_fields["waveform_key"])
|
||||
# The record type comes from the bytes: STRT[18] (#41). The filename's
|
||||
# last letter is only a cross-check -- SFM's own downloads have no name,
|
||||
# and a manual download's (".QZ0") carries no type at all.
|
||||
type_byte = strt_raw[18]
|
||||
ev.record_type = _RECORD_TYPE_BY_STRT.get(type_byte)
|
||||
if ev.record_type is None:
|
||||
ev.decode_problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]")
|
||||
ev.record_type = record_type
|
||||
ev.decode_problems.extend(problems)
|
||||
named_type = derive_record_type_from_filename(name, default=None) if name else None
|
||||
if named_type is not None and ev.record_type is not None and named_type != ev.record_type:
|
||||
log.warning("%s: record type %s from the file disagrees with the filename's %s; "
|
||||
@@ -1189,6 +1409,11 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
ev.geo_range, range_problem = _setup_geo_range(raw)
|
||||
if range_problem:
|
||||
ev.decode_problems.append(range_problem + "; peaks assume the Normal range")
|
||||
k = _setup_name_at(raw)
|
||||
if k is not None:
|
||||
ev.device_info, ev.battery_volts = _setup_identity(raw, k)
|
||||
for attr, value in _setup_trigger(raw, k).items():
|
||||
setattr(ev, attr, value)
|
||||
if is_waveform_body:
|
||||
ev.rectime_seconds = _setup_record_time(raw)
|
||||
ev.total_samples = len(samples["Tran"]) or None
|
||||
@@ -1219,17 +1444,19 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
# embedded in the 5A stream (_embedded_event_record), so a waveform takes
|
||||
# it from there. Without a validated one the estimate stands, reported as a
|
||||
# decode problem -- never a filename's time, which is only a cross-check.
|
||||
# Histograms stay on ts1 although it runs a second early on 97% (their
|
||||
# record, marker fe f5, holds the exact start): in Blastware's timing a
|
||||
# waveform and its histogram share a second 209 times in prod's store, and
|
||||
# events is unique on (serial, timestamp) -- #51.
|
||||
# A histogram's footer start runs a second early on 97%. Its own event
|
||||
# record (marker fe f5) holds Blastware's exact start and stop, so it takes
|
||||
# them from there (#51); events are keyed unit + time + type, so a waveform
|
||||
# and its histogram may share a second.
|
||||
# ⚠ RETRACTED 2026-11-03: "histograms stay on ts1" -- that held only while
|
||||
# events were unique on (serial, timestamp).
|
||||
if is_waveform_body and ts2 is not None:
|
||||
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
|
||||
ts2.hour, ts2.minute, ts2.second)
|
||||
_rt = _parse_record_time_seconds(raw)
|
||||
_start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second)
|
||||
if ts1 is not None else None)
|
||||
_trig, _why = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
|
||||
_trig, _why, ev.triggered_by = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
|
||||
if _trig is not None:
|
||||
ev.timestamp_source = "event_record"
|
||||
else:
|
||||
@@ -1251,13 +1478,25 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
hour=_trig.hour, minute=_trig.minute, second=_trig.second,
|
||||
)
|
||||
elif ts1 is not None:
|
||||
_start, _hstop, _why = (_histogram_event_record(raw, footer_pos, ts1, ts2)
|
||||
if record_type == "Histogram" else (None, None, ""))
|
||||
if _start is not None:
|
||||
ev.timestamp_source = "event_record"
|
||||
ev.stop_time = _hstop
|
||||
else:
|
||||
_start = ts1
|
||||
ev.timestamp_source = "footer"
|
||||
if record_type == "Histogram":
|
||||
_problem = (f"no validated histogram event record ({_why}); the start is the "
|
||||
"footer's, a second early on 97% of measured files")
|
||||
ev.decode_problems.append(_problem)
|
||||
log.warning("%s: %s", label, _problem)
|
||||
ev.timestamp = Timestamp(
|
||||
raw=footer[2:10],
|
||||
flag=0x10,
|
||||
year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day,
|
||||
hour=ts1.hour, minute=ts1.minute, second=ts1.second,
|
||||
year=_start.year, unknown_byte=0, month=_start.month, day=_start.day,
|
||||
hour=_start.hour, minute=_start.minute, second=_start.second,
|
||||
)
|
||||
ev.timestamp_source = "footer"
|
||||
|
||||
ev.project_info = _setup_notes(raw)
|
||||
ev.raw_samples = samples
|
||||
@@ -1280,14 +1519,32 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
# The geophone full scale is the file's range; Normal when it wasn't read.
|
||||
geo_fs = _GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS)
|
||||
ev.peak_values = _peaks_from_samples(samples, geo_fs) if has_samples else None
|
||||
if not is_waveform_body and ev.peak_values is not None:
|
||||
# A histogram stores each interval's vector sum (squared); the event's
|
||||
# is the largest. Combining the channel peaks instead read high on 86%
|
||||
# of DL2's histograms -- they can come from different moments.
|
||||
pvs = interval_pvs(body)
|
||||
if pvs:
|
||||
ev.peak_values.peak_vector_sum = (
|
||||
max(pvs) * _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS)
|
||||
if (is_waveform_body and ev.peak_values is not None and ev.sample_rate
|
||||
and ev.pretrig_samples is not None):
|
||||
_waveform_peak_detail(ev.peak_values, samples, geo_fs, ev.sample_rate, ev.pretrig_samples)
|
||||
if ev.stop_time is None: # a histogram's record stop, else the footer's
|
||||
ev.stop_time = ts2
|
||||
if hist_records:
|
||||
# A histogram stores each interval's vector sum (squared), and each
|
||||
# channel's half-period: Blastware's per-interval Geo PVS (771,354 /
|
||||
# 771,354 DL2 cells) and frequency, (sample rate / 2) / half-period.
|
||||
unit_ins = _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS
|
||||
ev.interval_pvs = [math.sqrt(r["pvs_sq"]) * unit_ins for r in hist_records]
|
||||
ev.interval_half_periods = {
|
||||
ch: [r[key] for r in hist_records if r[key] is not None]
|
||||
for ch, key in (("Tran", "t_halfp"), ("Vert", "v_halfp"),
|
||||
("Long", "l_halfp"), ("MicL", "m_halfp"))}
|
||||
if not ev.interval_half_periods["MicL"]:
|
||||
del ev.interval_half_periods["MicL"]
|
||||
k = _setup_name_at(raw)
|
||||
if k is not None and k >= _INTERVAL_BEFORE_NAME:
|
||||
ev.histogram_interval_sec = int.from_bytes(
|
||||
raw[k - _INTERVAL_BEFORE_NAME:k - _INTERVAL_BEFORE_NAME + 2], "big") or None
|
||||
if not is_waveform_body and ev.peak_values is not None and ev.interval_pvs:
|
||||
# The event's vector sum is the largest interval's. Combining the
|
||||
# channel peaks instead read high on 86% of DL2's histograms -- they
|
||||
# can come from different moments.
|
||||
ev.peak_values.peak_vector_sum = max(ev.interval_pvs)
|
||||
ev._a5_frames = None # not recoverable from BW file
|
||||
|
||||
return ev
|
||||
@@ -156,10 +156,11 @@ _BLOCK_MARKER = 10
|
||||
# 16-count-unit output (1 unit = 0.005 in/s = 16 ADC counts).
|
||||
_GEO_LSB_INS = 0.005
|
||||
|
||||
# Frequency formula: freq_Hz = _FREQ_NUMERATOR / half_period_samples.
|
||||
# Empirically determined to be 512 (= sample_rate / 2, where sample rate
|
||||
# is 1024 sps for the standard MiniMate Plus configuration).
|
||||
_FREQ_NUMERATOR = 512
|
||||
# Frequency formula: freq_Hz = (sample_rate / 2) / half_period_samples.
|
||||
# ⚠ RETRACTED 2026-11-03 (#50): "a fixed numerator of 512". 512 is sample_rate
|
||||
# / 2 at 1024 sps only; at 2048 sps it halved every frequency. Measured on DL2:
|
||||
# 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048.
|
||||
_FREQ_NUMERATOR = 512 # sample_rate / 2 at the default 1024 sps
|
||||
|
||||
|
||||
def _is_data_block(block: bytes) -> bool:
|
||||
@@ -300,7 +301,11 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
|
||||
to get 1-count ADC values, then ``count / 32767 * 10.0`` for in/s)
|
||||
- Mic channel: use ``waveform_codec.mic_count_to_db(count)``
|
||||
"""
|
||||
records = _walk_auto(body)
|
||||
return channels_from_records(_walk_auto(body))
|
||||
|
||||
|
||||
def channels_from_records(records: Optional[List[dict]]) -> Optional[dict]:
|
||||
"""``decode_histogram_body``'s per-channel peaks, from records already walked."""
|
||||
if not records:
|
||||
return None
|
||||
return {
|
||||
@@ -338,17 +343,19 @@ def interval_pvs(body: bytes) -> Optional[List[float]]:
|
||||
return [math.sqrt(r["pvs_sq"]) for r in records] if records else None
|
||||
|
||||
|
||||
def half_period_to_hz(halfp: int) -> Optional[float]:
|
||||
"""Convert a half-period in samples to frequency in Hz.
|
||||
def half_period_to_hz(halfp: int, sample_rate: int = 1024) -> Optional[float]:
|
||||
"""Convert a half-period in samples to frequency in Hz:
|
||||
``(sample_rate / 2) / halfp``.
|
||||
|
||||
Returns ``None`` for half-period ≤ 5 — the device emits values in
|
||||
that range when the measured zero-crossing rate exceeds 100 Hz
|
||||
(the BW display reports `>100 Hz` for such cases). Callers can
|
||||
treat ``None`` as the `>100 Hz` sentinel.
|
||||
that range when the measured zero-crossing rate exceeds 100 Hz at
|
||||
1024 sps (the BW display reports `>100`, `>200` at 2048 sps). Callers
|
||||
can treat ``None`` as that sentinel. A half-period of 0 is Blastware's
|
||||
"N/A"; it also returns None.
|
||||
"""
|
||||
if halfp <= 5:
|
||||
return None
|
||||
return _FREQ_NUMERATOR / halfp
|
||||
return (sample_rate / 2) / halfp
|
||||
|
||||
|
||||
def geo_count_to_ins(count: int) -> float:
|
||||
@@ -439,16 +446,34 @@ def _stride(rec: int, n: int) -> int:
|
||||
|
||||
|
||||
def _records_plausible(body: bytes, off: int, rec: int, m: int) -> bool:
|
||||
"""Every record's zero word is 0000 -- what tells a 16-byte layout from a
|
||||
20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24)."""
|
||||
"""Every record's last 4 bytes are its vector sum squared, consistent with
|
||||
its channel peaks: at least the largest peak, at most sqrt(3) times it (one
|
||||
unit of rounding either way). That is what tells a 16-byte layout from a
|
||||
20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24);
|
||||
misread, those bytes are other fields. Holds on 34,502,955 / 34,502,955 DL2
|
||||
sub-minute intervals (2026-11-02).
|
||||
|
||||
⚠ RETRACTED 2026-11-02: "every record's zero word is 0000". It is the high
|
||||
word of the PVS², non-zero on any interval above 1.28 in/s, so a short
|
||||
histogram with one loud interval was not recognised at all (T193KR5M.X90H,
|
||||
K440HA3C.JM0H decoded to nothing)."""
|
||||
z = rec - 4
|
||||
for k in range(m):
|
||||
q = off + _MULTI_HEADER_LEN + rec * k
|
||||
if q + rec > len(body) or body[q + z] or body[q + z + 1]:
|
||||
if q + rec > len(body):
|
||||
return False
|
||||
peak = max((body[q + i] << 8) | body[q + i + 1] for i in (0, 4, 8))
|
||||
if not _pvs_consistent(peak, int.from_bytes(body[q + z:q + z + 4], "big")):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _pvs_consistent(peak: int, pvs_sq: int) -> bool:
|
||||
"""A record's vector sum squared against its largest geo peak, one unit of
|
||||
rounding either way: peak <= PVS <= sqrt(3) * peak."""
|
||||
return max(peak - 1, 0) ** 2 <= pvs_sq <= 3 * (peak + 1) ** 2
|
||||
|
||||
|
||||
def detect_multi_interval_layout(body: bytes) -> Optional[Tuple[int, int]]:
|
||||
"""``(record_len, per_block)`` of a multi-interval body, or None.
|
||||
|
||||
@@ -543,8 +568,8 @@ def walk_multi_interval_blocks(body: bytes,
|
||||
recs = [_decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
|
||||
for k in range(max(m, 0))]
|
||||
for k, r in enumerate(recs):
|
||||
if (r["meta_var"][:2] != b"\x00\x00"
|
||||
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
|
||||
peak = max(r["t_peak"], r["v_peak"], r["l_peak"])
|
||||
if not _pvs_consistent(peak, r["pvs_sq"]) or peak > _GEO_MAX_COUNTS:
|
||||
del recs[k:]
|
||||
break
|
||||
out.extend(recs)
|
||||
|
||||
@@ -300,6 +300,10 @@ class DeviceInfo:
|
||||
# ── From SUB 08 (EVENT_INDEX_RESPONSE) ────────────────────────────────────
|
||||
event_count: Optional[int] = None # stored event count from F7 response 🔶
|
||||
|
||||
# ── From a Blastware event file's identity block (2026-11-03) ─────────────
|
||||
calibration_date: Optional[datetime.date] = None # e.g. 2019-02-20 ✅
|
||||
calibrated_by: Optional[str] = None # e.g. "Instantel" ✅
|
||||
|
||||
def __str__(self) -> str:
|
||||
fw = self.firmware_version or f"?.{self.firmware_minor}"
|
||||
mdl = self.model or "MiniMate Plus"
|
||||
@@ -360,6 +364,15 @@ class PeakValues:
|
||||
vert_zc_above_range: bool = False
|
||||
long_zc_above_range: bool = False
|
||||
mic_zc_above_range: bool = False
|
||||
# A waveform's peak detail, from its samples (2026-11-04); None for a histogram.
|
||||
tran_time_of_peak: Optional[float] = None # s from the trigger; negative = pre-trigger
|
||||
vert_time_of_peak: Optional[float] = None
|
||||
long_time_of_peak: Optional[float] = None
|
||||
micl_time_of_peak: Optional[float] = None
|
||||
pvs_time: Optional[float] = None # s from the trigger, of the vector-sum peak
|
||||
tran_peak_accel_g: Optional[float] = None
|
||||
vert_peak_accel_g: Optional[float] = None
|
||||
long_peak_accel_g: Optional[float] = None
|
||||
|
||||
|
||||
# ── Project / operator metadata ───────────────────────────────────────────────
|
||||
@@ -379,6 +392,8 @@ class ProjectInfo:
|
||||
operator: Optional[str] = None # operator / user name
|
||||
sensor_location: Optional[str] = None # sensor location string
|
||||
notes: Optional[str] = None # extended notes
|
||||
job_number_enabled: Optional[bool] = None # Blastware prints the job number
|
||||
job_number: Optional[int] = None # kept while switched off
|
||||
|
||||
|
||||
# ── Compliance Config ──────────────────────────────────────────────────────────
|
||||
@@ -546,6 +561,20 @@ class Event:
|
||||
# Geophone range from the recording setup, as ComplianceConfig.geo_range:
|
||||
# 0 Normal (10 in/s full scale), 1 Sensitive (1.25 in/s). None: not read.
|
||||
geo_range: Optional[int] = None
|
||||
# From a Blastware event file (2026-11-03); None when not read.
|
||||
device_info: Optional["DeviceInfo"] = None # the unit, as SUB FE reports it
|
||||
battery_volts: Optional[float] = None # at the event
|
||||
triggered_by: Optional[int] = None # 0x01 Tran 0x02 Vert 0x04 Long 0x08 MicL 0x200 Manual
|
||||
trigger_sources: Optional[int] = None # setup bitmask: 0x07 geophones, 0x08 mic
|
||||
trigger_level_geo: Optional[float] = None # in/s, as ComplianceConfig.trigger_level_geo
|
||||
trigger_level_mic_psi: Optional[float] = None
|
||||
record_stop_mode: Optional[int] = None # 0 = Fixed
|
||||
mic_type: Optional[int] = None # 2 = Linear Weighting (as Series IV)
|
||||
stop_time: Optional[datetime.datetime] = None # the footer's stop
|
||||
# A histogram's per-interval detail (2026-11-03); None for a waveform.
|
||||
histogram_interval_sec: Optional[int] = None # as ComplianceConfig.histogram_interval_sec
|
||||
interval_half_periods: Optional[dict] = None # channel -> half-period per interval, samples
|
||||
interval_pvs: Optional[list] = None # each interval's vector sum, in/s
|
||||
|
||||
# Sensor self-check traces keyed by channel label — the short diagnostic
|
||||
# waveforms the unit records when it pulses each sensor before monitoring
|
||||
|
||||
+147
-44
@@ -142,9 +142,14 @@ _WRITE_TAIL = {SUB_EVENT_INDEX_WRITE: b"\x02\x00", SUB_TRIGGER_CONFIG_WRITE: b"\
|
||||
SUB_CALL_HOME_WRITE: b"\x00\x00"}
|
||||
|
||||
|
||||
def write_image(sub: int, data: bytes) -> bytes:
|
||||
def write_image(sub: int, data: bytes, *, escaped: bool = True) -> bytes:
|
||||
"""The whole block a write sends: `data` unescaped, N + 2 bytes.
|
||||
|
||||
`escaped=False`: `data` is already logical (every block read since phase 5 --
|
||||
read_event_index, read_compliance_content, read_trigger_config,
|
||||
read_waveform_data_raw -- returns unescaped bytes), so it is NOT unescaped
|
||||
again: a logical `10 02` (job number 4098) would otherwise collapse.
|
||||
|
||||
A config block starts with its own length N (uint16 BE) and is written as N
|
||||
bytes plus two -- on every Blastware write on record. `data` may be the
|
||||
block as a read returned it (N bytes, or N + 2) and may still hold the
|
||||
@@ -152,7 +157,7 @@ def write_image(sub: int, data: bytes) -> bytes:
|
||||
Anything else is refused before a byte is sent: a block one byte longer than
|
||||
its header says is what an edit beside a kept escape byte leaves behind.
|
||||
"""
|
||||
image = unescape_reply(bytes(data))
|
||||
image = unescape_reply(bytes(data)) if escaped else bytes(data)
|
||||
if len(image) < 2:
|
||||
raise ValueError(f"write SUB 0x{sub:02X}: {len(image)} bytes is not a whole block")
|
||||
n = int.from_bytes(image[:2], "big")
|
||||
@@ -165,6 +170,81 @@ def write_image(sub: int, data: bytes) -> bytes:
|
||||
return image
|
||||
|
||||
|
||||
class ImageRefused(ValueError):
|
||||
"""A write refused before any byte was sent: the image is not a whole block."""
|
||||
|
||||
|
||||
# ── The settings block (SUB 1A), as content ─────────────────────────────────
|
||||
#
|
||||
# Measured 2026-11-03 on BE9441's 10-26 recording (12 reads, both Blastware's
|
||||
# 4 x 512 + 42 pattern and SFM's 1024 + 1024 + 42): unescape each data frame and
|
||||
# take data[11:]; every frame but the last then starts with one `00` that is not
|
||||
# content. Dropped, the frames join into 2,090 bytes that start with their own
|
||||
# length N = 2090 -- Series IV's 0x1A content layout -- and the read after each
|
||||
# of Blastware's two writes equals the image it had just written.
|
||||
# tests/test_s3_settings_read.py.
|
||||
|
||||
COMPLIANCE_CONTENT_LEN = 2090
|
||||
# SFM's 1A read: (offset = the content length asked for, page) per data frame.
|
||||
_COMPLIANCE_READ_STEPS = ((0x0400, 0x00), (0x0400, 0x04), (0x002A, 0x08))
|
||||
|
||||
|
||||
def assemble_compliance_content(frames: "list[bytes]", lengths: "Optional[tuple]" = None) -> bytes:
|
||||
"""Join a 1A read's data frames (each S3Frame.data, kept escapes and all, in
|
||||
order) into the logical settings block. Judges nothing: a monitoring unit's
|
||||
device-info answer assembles too -- `is_compliance_content` tells them apart.
|
||||
|
||||
`lengths`: the content each frame was asked for (SFM's read: 1024, 1024, 42).
|
||||
Each frame then gives exactly that. Measured at the bench 2026-11-04 (BE9441):
|
||||
when a frame's checksum byte is itself escaped (02 / 03 / 04), the parser keeps
|
||||
the escape's 0x10 and strips only the byte after it, so the frame arrives one
|
||||
byte long, ending in a lone 0x10. That one byte is dropped; any other leftover
|
||||
is kept, and the block then fails is_compliance_content."""
|
||||
parts = [unescape_reply(bytes(f))[11:] for f in frames]
|
||||
parts = [p[1:] for p in parts[:-1]] + parts[-1:]
|
||||
if lengths is not None and len(lengths) == len(parts):
|
||||
parts = [p[:n] if p[n:] == b"\x10" else p for p, n in zip(parts, lengths)]
|
||||
return b"".join(parts)
|
||||
|
||||
|
||||
def is_compliance_content(block: bytes) -> bool:
|
||||
"""Whether `block` is the settings block: 2,090 bytes headed by N = 2090."""
|
||||
return (len(block) == COMPLIANCE_CONTENT_LEN
|
||||
and int.from_bytes(block[0:2], "big") == COMPLIANCE_CONTENT_LEN)
|
||||
|
||||
|
||||
def is_call_home_block(raw: bytes) -> bool:
|
||||
"""Whether a 0x2C reply payload is the call-home block: it starts with its own
|
||||
length N = 0x7C (00 7C DC on every read on record) and is N (or N + 2) bytes
|
||||
unescaped. A MONITORING MiniMate answers the read with its device-info block
|
||||
instead (00 00 00 08 'Instantel' ..., measured 2026-11-03 on BE9441), which
|
||||
fails this."""
|
||||
image = unescape_reply(bytes(raw))
|
||||
n = DATA_LENGTHS[SUB_CALL_HOME]
|
||||
return len(image) >= 3 and int.from_bytes(image[:2], "big") == n and len(image) in (n, n + 2)
|
||||
|
||||
|
||||
def call_home_enabled(raw: bytes) -> Optional[bool]:
|
||||
"""The call-home switch of a `0x2C` reply payload, read UNESCAPED (an escaped
|
||||
byte before it would move the raw index -- bench finding #1's lesson): byte 5,
|
||||
0x01 on / 0x00 off (measured 2026-04-20, BE11529). Anything else is None."""
|
||||
image = unescape_reply(bytes(raw))
|
||||
if len(image) <= 5:
|
||||
return None
|
||||
return {0x01: True, 0x00: False}.get(image[5])
|
||||
|
||||
|
||||
def call_home_image(raw: bytes, enabled: bool) -> bytes:
|
||||
"""The `0x7E` image that turns call-home on or off: the block as read
|
||||
(`write_image`, N + 2 bytes, unescaped) with byte 5 set to 0x01 / 0x00 and
|
||||
every other byte as the unit sent it. Refuses a byte 5 never measured."""
|
||||
image = write_image(SUB_CALL_HOME_WRITE, raw)
|
||||
if image[5] not in (0x00, 0x01):
|
||||
raise ValueError(f"call-home byte 5 is 0x{image[5]:02X} -- not a value ever measured "
|
||||
"(0x00 off / 0x01 on); nothing built")
|
||||
return image[:5] + bytes([0x01 if enabled else 0x00]) + image[6:]
|
||||
|
||||
|
||||
# Default timeout values (seconds).
|
||||
# MiniMate Plus is a slow device — keep these generous.
|
||||
DEFAULT_RECV_TIMEOUT = 10.0
|
||||
@@ -553,6 +633,10 @@ class MiniMateProtocol:
|
||||
data_rsp = self._recv_one(expected_sub=rsp_sub)
|
||||
|
||||
raw = unescape_reply(data_rsp.data)[11:] # unescaped, as read_event_index
|
||||
# An escaped checksum byte leaves its 0x10 behind (bench 2026-11-04; see
|
||||
# assemble_compliance_content): one stray byte beyond what was asked is dropped.
|
||||
if len(raw) == length + 1 and raw[-1:] == b"\x10":
|
||||
raw = raw[:-1]
|
||||
log.debug("read_waveform_data_raw: got %d bytes", len(raw))
|
||||
return raw
|
||||
|
||||
@@ -993,6 +1077,25 @@ class MiniMateProtocol:
|
||||
|
||||
return bytes(config)
|
||||
|
||||
def read_compliance_content(self) -> bytes:
|
||||
"""The 1A read as the logical settings block (see assemble_compliance_content).
|
||||
|
||||
The same requests as read_compliance_config -- probe, then B / C / D -- but
|
||||
strict: a data frame that does not arrive raises, and there is no tail
|
||||
drain, so a short read is never assembled. Returns whatever assembled,
|
||||
unjudged; a MONITORING unit answers with its device-info block, which
|
||||
is_compliance_content() rejects.
|
||||
"""
|
||||
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE)
|
||||
self._send(build_bw_frame(SUB_COMPLIANCE, 0, bytes([0, 0, 0, 0, 0, 0, 0, 0x64, 0, 0])))
|
||||
self._recv_one(expected_sub=rsp_sub)
|
||||
frames = []
|
||||
for offset, page in _COMPLIANCE_READ_STEPS:
|
||||
self._send(build_bw_frame(SUB_COMPLIANCE, offset,
|
||||
bytes([0, 0, page, 0, 0, 0, 0, 0x64, 0, 0])))
|
||||
frames.append(self._recv_one(expected_sub=rsp_sub).data)
|
||||
return assemble_compliance_content(frames, lengths=tuple(o for o, _ in _COMPLIANCE_READ_STEPS))
|
||||
|
||||
# ── Write commands (SUBs 68–83) ───────────────────────────────────────────
|
||||
|
||||
def recv_write_ack(
|
||||
@@ -1050,25 +1153,26 @@ class MiniMateProtocol:
|
||||
self._send(frame)
|
||||
return self.recv_write_ack(expected_sub=rsp_sub)
|
||||
|
||||
def _write_block(self, sub: int, data: bytes, params: bytes = bytes(10)) -> S3Frame:
|
||||
def _write_block(self, sub: int, data: bytes, params: bytes = bytes(10), *,
|
||||
escaped: bool = True) -> S3Frame:
|
||||
"""Send one config block as a write and return its ack (0xFF - sub)."""
|
||||
image = write_image(sub, data)
|
||||
image = write_image(sub, data, escaped=escaped)
|
||||
frame = build_bw_write_frame(sub, image, params=params)
|
||||
log.debug("write SUB=0x%02X: %d-byte image", sub, len(image))
|
||||
self._send(frame)
|
||||
return self.recv_write_ack(expected_sub=_expected_rsp_sub(sub))
|
||||
|
||||
def write_event_index(self, data: bytes) -> S3Frame:
|
||||
def write_event_index(self, data: bytes, *, escaped: bool = True) -> S3Frame:
|
||||
"""SUB 68: write the event-index block (as SUB 08 read it). Ack 0x97;
|
||||
callers follow with write_confirm(SUB_WRITE_CONFIRM_B). See write_image."""
|
||||
return self._write_block(SUB_EVENT_INDEX_WRITE, data)
|
||||
return self._write_block(SUB_EVENT_INDEX_WRITE, data, escaped=escaped)
|
||||
|
||||
def write_waveform_data(self, data: bytes) -> S3Frame:
|
||||
def write_waveform_data(self, data: bytes, *, escaped: bool = True) -> S3Frame:
|
||||
"""SUB 69: write the waveform-data block (as SUB 09 read it). Ack 0x96;
|
||||
callers follow with write_confirm C then A. See write_image."""
|
||||
return self._write_block(SUB_WAVEFORM_DATA_WRITE, data)
|
||||
return self._write_block(SUB_WAVEFORM_DATA_WRITE, data, escaped=escaped)
|
||||
|
||||
def write_compliance_config_raw(self, data: bytes) -> None:
|
||||
def write_compliance_config_raw(self, data: bytes, *, escaped: bool = True) -> None:
|
||||
"""SUB 71: write the compliance image in addressed chunks, then confirm (72).
|
||||
|
||||
Measured: the image is 2,092 bytes (its header N = 2,090, plus 2), sent as
|
||||
@@ -1079,7 +1183,7 @@ class MiniMateProtocol:
|
||||
both. (Retracted: "exactly 3 chunks, offset 0x1004, params 00 00 00 10 04"
|
||||
-- the length 0x0400 and address 0x0400, read with their escape bytes.)
|
||||
"""
|
||||
image = write_image(SUB_COMPLIANCE_WRITE, data)
|
||||
image = write_image(SUB_COMPLIANCE_WRITE, data, escaped=escaped)
|
||||
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE_WRITE)
|
||||
for addr in range(0, len(image), _COMPLIANCE_CHUNK):
|
||||
params = bytes([0x00, 0x00, (addr >> 8) & 0xFF, addr & 0xFF]) + bytes(6)
|
||||
@@ -1090,10 +1194,10 @@ class MiniMateProtocol:
|
||||
self.recv_write_ack(expected_sub=rsp_sub)
|
||||
self.write_confirm(SUB_WRITE_CONFIRM_A)
|
||||
|
||||
def write_trigger_config(self, data: bytes) -> S3Frame:
|
||||
def write_trigger_config(self, data: bytes, *, escaped: bool = True) -> S3Frame:
|
||||
"""SUB 82: write the trigger block (as SUB 0x2E read it). Ack 0x7D;
|
||||
callers follow with write_confirm(SUB_TRIGGER_CONFIRM). See write_image."""
|
||||
return self._write_block(SUB_TRIGGER_CONFIG_WRITE, data)
|
||||
return self._write_block(SUB_TRIGGER_CONFIG_WRITE, data, escaped=escaped)
|
||||
|
||||
def read_trigger_config(self) -> bytes:
|
||||
"""SUB 0x2E two-step read: the 26-byte trigger block that SUB 82 writes.
|
||||
@@ -1151,41 +1255,40 @@ class MiniMateProtocol:
|
||||
|
||||
def write_call_home_config(self, data: bytes) -> None:
|
||||
"""
|
||||
Write the auto call home configuration (SUB 0x7E → 0x7F confirm).
|
||||
Write the call-home block as a read returned it (SUB 0x7E, then 0x7F).
|
||||
|
||||
Write sequence (confirmed from 4-20-26 call home settings captures):
|
||||
SUB 0x7E write 127-byte payload → device acks SUB 0x81
|
||||
SUB 0x7F confirm (no data) → device acks SUB 0x80
|
||||
|
||||
The 127-byte write payload = 125-byte read payload + b'\\x00\\x00'.
|
||||
The offset field = data[1] + 2 = 0x7C + 2 = 0x7E = 126.
|
||||
|
||||
Write frame format: build_bw_write_frame (minimal DLE stuffing — only
|
||||
BW_CMD is doubled; all other bytes are RAW). The \\x10\\x03 sequence
|
||||
within the payload is preserved as-is (device interprets DLE+ETX as the
|
||||
literal value 0x03 per the inner-frame terminator convention).
|
||||
|
||||
Args:
|
||||
data: 127-byte write payload (read payload + \\x00\\x00 footer).
|
||||
Must start with [0x00][0x7C][...] (standard header).
|
||||
|
||||
Raises:
|
||||
ValueError: if data is not exactly 127 bytes or lacks expected header.
|
||||
ProtocolError: on timeout or wrong response SUB.
|
||||
`data` is the 0x2C read payload (125 B, the parser's kept escape bytes
|
||||
in -- num_retries 3 arrives as 10 03), optionally + 00 00. `write_image`
|
||||
removes the escapes once and makes the 126-byte image (N = 0x7C, + 2);
|
||||
`write_call_home_image` sends it. The legacy multi-field path.
|
||||
"""
|
||||
rsp_sub_confirm = _expected_rsp_sub(SUB_CALL_HOME_CONFIRM) # 0xFF - 0x7F = 0x80
|
||||
# 2026-10-27 (#46): the read payload holds the parser's kept escape bytes
|
||||
# (num_retries 3 arrives as 10 03); write_image removes them, so the
|
||||
# 127-byte "read + 00 00" goes out as its 126-byte image (N = 0x7C, + 2),
|
||||
# escaped like every request. No Blastware call-home write is on record
|
||||
# here to compare against -- inferred from the 77 other write frames.
|
||||
self._write_block(SUB_CALL_HOME_WRITE, data)
|
||||
log.debug("write_call_home_config: write acked; sending confirm 0x7F")
|
||||
self.write_call_home_image(write_image(SUB_CALL_HOME_WRITE, data))
|
||||
|
||||
confirm_frame = build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")
|
||||
self._send(confirm_frame)
|
||||
self.recv_write_ack(expected_sub=rsp_sub_confirm)
|
||||
log.debug("write_call_home_config: confirm acked — done")
|
||||
def write_call_home_image(self, image: bytes) -> None:
|
||||
"""
|
||||
Send a call-home image that is already built (`call_home_image`:
|
||||
unescaped, N + 2 bytes) -- 0x7E, ack 0x81, then the 0x7F confirm, ack 0x80.
|
||||
|
||||
Never through `write_image` again: unescaping is not idempotent, and a
|
||||
real 0x10 before 02/03/04 in the image -- a call-in time of 16:02-16:04
|
||||
-- would lose its 0x10 (phase-4 final review, 2026-11-02). Measured: the
|
||||
frames equal Blastware's 2026-04-20 enable / disable writes (BE11529),
|
||||
tests/test_s3_call_home_bw_frames.py and test_s3_call_home_wire.py.
|
||||
|
||||
Raises ImageRefused, before any byte is sent, unless the image is a whole
|
||||
block: its header N plus the two trailing bytes.
|
||||
"""
|
||||
image = bytes(image)
|
||||
n = int.from_bytes(image[:2], "big") if len(image) >= 2 else -1
|
||||
if len(image) != n + 2:
|
||||
raise ImageRefused(f"write SUB 0x{SUB_CALL_HOME_WRITE:02X}: {len(image)} bytes, but its "
|
||||
f"header says {n} (+ 2) -- not a whole image; nothing sent")
|
||||
self._send(build_bw_write_frame(SUB_CALL_HOME_WRITE, image))
|
||||
self.recv_write_ack(expected_sub=_expected_rsp_sub(SUB_CALL_HOME_WRITE))
|
||||
log.debug("write_call_home_image: write acked; sending confirm 0x7F")
|
||||
self._send(build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b""))
|
||||
self.recv_write_ack(expected_sub=_expected_rsp_sub(SUB_CALL_HOME_CONFIRM))
|
||||
log.debug("write_call_home_image: confirm acked — done")
|
||||
|
||||
# ── Monitoring ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
"""
|
||||
poc_set_project.py — POC test for set_project_info() against a live MiniMate Plus.
|
||||
|
||||
Usage:
|
||||
python poc_set_project.py [--host IP] [--port PORT]
|
||||
|
||||
Default target: BE11529 at 63.43.212.232:9034
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format="%(asctime)s %(levelname)-7s %(name)s %(message)s",
|
||||
datefmt="%H:%M:%S",
|
||||
)
|
||||
log = logging.getLogger("poc_set_project")
|
||||
|
||||
from minimateplus import MiniMateClient
|
||||
from minimateplus.transport import TcpTransport
|
||||
|
||||
|
||||
DEFAULT_HOST = "63.43.212.232"
|
||||
DEFAULT_PORT = 9034
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description="POC: write project info to MiniMate Plus")
|
||||
ap.add_argument("--host", default=DEFAULT_HOST, help="Modem IP address")
|
||||
ap.add_argument("--port", type=int, default=DEFAULT_PORT, help="TCP port")
|
||||
ap.add_argument("--project", default="POC Write Test")
|
||||
ap.add_argument("--client-name", default="Terra-Mechanics Inc.")
|
||||
ap.add_argument("--operator", default="B. Harrison")
|
||||
ap.add_argument("--seis-loc", default="Lab Bench - POC")
|
||||
ap.add_argument("--notes", default="set_project_info POC 2026-04-07")
|
||||
args = ap.parse_args()
|
||||
|
||||
log.info("Connecting to %s:%d", args.host, args.port)
|
||||
transport = TcpTransport(args.host, port=args.port)
|
||||
|
||||
with MiniMateClient(transport=transport, timeout=60.0) as client:
|
||||
log.info("Performing POLL handshake + identity read …")
|
||||
info = client.connect()
|
||||
log.info("Connected: serial=%s firmware=%s", info.serial, info.firmware_version)
|
||||
|
||||
log.info("Calling set_project_info() …")
|
||||
client.set_project_info(
|
||||
project=args.project,
|
||||
client_name=args.client_name,
|
||||
operator=args.operator,
|
||||
seis_loc=args.seis_loc,
|
||||
notes=args.notes,
|
||||
)
|
||||
log.info("set_project_info() returned — write sequence complete")
|
||||
|
||||
log.info("Done. Reconnect Blastware to verify the fields were written.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(0)
|
||||
except Exception as exc:
|
||||
log.exception("Fatal: %s", exc)
|
||||
sys.exit(1)
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "seismo-relay"
|
||||
version = "0.33.0"
|
||||
version = "0.34.0"
|
||||
description = "Python client and REST server for MiniMate Plus seismographs"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
|
||||
@@ -73,7 +73,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
conn.row_factory = sqlite3.Row
|
||||
|
||||
rows = list(conn.execute(
|
||||
"SELECT id, serial, timestamp, blastware_filename "
|
||||
"SELECT id, serial, timestamp, record_type, blastware_filename "
|
||||
" FROM events "
|
||||
" WHERE serial = 'UNKNOWN' "
|
||||
" ORDER BY timestamp",
|
||||
@@ -98,10 +98,11 @@ def main(argv: list[str] | None = None) -> int:
|
||||
unresolved += 1
|
||||
continue
|
||||
|
||||
# Check for an existing row at the target (serial, timestamp).
|
||||
# Check for an existing row at the target key (serial, timestamp,
|
||||
# record_type -- #51).
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM events WHERE serial = ? AND timestamp = ?",
|
||||
(new_serial, ts),
|
||||
"SELECT id FROM events WHERE serial = ? AND timestamp = ? AND record_type IS ?",
|
||||
(new_serial, ts, row["record_type"]),
|
||||
).fetchone()
|
||||
action: str
|
||||
if existing is None:
|
||||
|
||||
+77
-22
@@ -36,6 +36,7 @@ from __future__ import annotations
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sqlite3
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -107,7 +108,7 @@ CREATE TABLE IF NOT EXISTS events (
|
||||
shape_offset_pre REAL, -- pre-trigger baseline median (in/s)
|
||||
shape_offset_spread REAL, -- max(pre,mid,end) - min(...) in in/s; small = constant/DC
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
UNIQUE(serial, timestamp)
|
||||
UNIQUE(serial, timestamp, record_type) -- unit + time + type (#51); see Migration 3
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_serial ON events(serial);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
||||
@@ -194,7 +195,7 @@ class SeismoDb:
|
||||
row = conn.execute(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
||||
).fetchone()
|
||||
if row and "UNIQUE(serial, timestamp)" not in row[0]:
|
||||
if row and "UNIQUE(serial, timestamp" not in row[0]: # neither key form yet
|
||||
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp)")
|
||||
conn.executescript("""
|
||||
ALTER TABLE events RENAME TO events_old;
|
||||
@@ -348,6 +349,33 @@ class SeismoDb:
|
||||
""")
|
||||
log.info("_migrate: monitor_log table rebuilt OK")
|
||||
|
||||
# Migration 3 (#51, 2026-11-03): events UNIQUE (serial, timestamp) ->
|
||||
# (serial, timestamp, record_type). A unit records a waveform and a
|
||||
# histogram in the same second legitimately -- 209 times in prod's
|
||||
# 2026-09-30 store once histograms carry Blastware's start -- and the old
|
||||
# key could hold only one. The table is rebuilt from its own current
|
||||
# definition with only the key swapped, so every column added by the
|
||||
# migrations above, every row and every id is kept (Terra-View reads
|
||||
# rows by id); its indexes are recreated. One transaction.
|
||||
row = conn.execute(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
||||
).fetchone()
|
||||
if row and "UNIQUE(serial, timestamp)" in row[0]:
|
||||
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp, record_type)")
|
||||
indexes = [r[0] for r in conn.execute(
|
||||
"SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='events' "
|
||||
"AND sql IS NOT NULL")]
|
||||
table = re.sub(r'^CREATE TABLE\s+("?)events\1', "CREATE TABLE events_rekeyed",
|
||||
row[0].replace("UNIQUE(serial, timestamp)",
|
||||
"UNIQUE(serial, timestamp, record_type)", 1))
|
||||
conn.executescript("BEGIN;\n" + table + ";\n"
|
||||
"INSERT INTO events_rekeyed SELECT * FROM events;\n"
|
||||
"DROP TABLE events;\n"
|
||||
"ALTER TABLE events_rekeyed RENAME TO events;\n"
|
||||
+ "".join(sql + ";\n" for sql in indexes)
|
||||
+ "COMMIT;")
|
||||
log.info("_migrate: events table re-keyed OK (%d indexes recreated)", len(indexes))
|
||||
|
||||
@staticmethod
|
||||
def _iso(dt: Optional[datetime.datetime]) -> Optional[str]:
|
||||
return dt.isoformat() if dt is not None else None
|
||||
@@ -507,7 +535,8 @@ class SeismoDb:
|
||||
device_family: Optional[str] = None,
|
||||
) -> tuple[int, int]:
|
||||
"""
|
||||
Insert triggered events. Silently skips duplicates (serial+timestamp).
|
||||
Insert triggered events. Silently skips duplicates (serial + timestamp +
|
||||
record_type: a waveform and a histogram may share a second, #51).
|
||||
Returns (inserted, skipped).
|
||||
|
||||
``waveform_records`` (optional): dict keyed by event waveform_key (hex)
|
||||
@@ -515,7 +544,7 @@ class SeismoDb:
|
||||
{"filename": str, "filesize": int, "a5_pickle_filename": str}
|
||||
|
||||
For events whose key is in this dict, the matching columns are
|
||||
populated. If a row with the same (serial, timestamp) already exists
|
||||
populated. If a row with the same (serial, timestamp, record_type) already exists
|
||||
(dedup hit), the matching waveform record is upserted onto the
|
||||
existing row so a re-download via the live endpoint refreshes the
|
||||
file metadata.
|
||||
@@ -558,18 +587,27 @@ class SeismoDb:
|
||||
# No validated event record: the time may be a second off,
|
||||
# so it is never allowed to move, merge into or duplicate
|
||||
# a row (_estimate_guard). The file is already stored.
|
||||
why = self._estimate_guard(conn, serial, rec.get("filename"), ts)
|
||||
why = self._estimate_guard(conn, serial, rec.get("filename"), ts,
|
||||
ev.record_type)
|
||||
if why:
|
||||
log.warning("insert_events: %s %s: %s", serial,
|
||||
rec.get("filename") or key, why)
|
||||
skipped += 1
|
||||
continue
|
||||
elif rec.get("filename") and ts and \
|
||||
self._restamp_by_file(conn, serial, rec["filename"], ts) is False:
|
||||
self._restamp_by_file(conn, serial, rec["filename"], ts,
|
||||
ev.record_type) is False:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
if ev.record_type is None and conn.execute(
|
||||
"SELECT 1 FROM events WHERE serial = ? AND timestamp = ? "
|
||||
"AND record_type IS NULL", (serial, ts)).fetchone():
|
||||
# A UNIQUE key treats NULLs as distinct, so an untyped
|
||||
# event would never collide: it still refreshes the
|
||||
# untyped row at its second, as under the old key.
|
||||
raise sqlite3.IntegrityError("untyped event already stored")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO events
|
||||
@@ -629,7 +667,7 @@ class SeismoDb:
|
||||
inserted += 1
|
||||
except sqlite3.IntegrityError:
|
||||
skipped += 1
|
||||
# UPSERT path: a row for this (serial, timestamp) already
|
||||
# UPSERT path: a row for this (serial, timestamp, record_type) already
|
||||
# exists. Refresh every device-authoritative field from
|
||||
# the new data so that a re-import with better data (e.g.
|
||||
# a watcher re-forward where the previous attempt missed
|
||||
@@ -682,7 +720,7 @@ class SeismoDb:
|
||||
shape_offset_axis = COALESCE(?, shape_offset_axis),
|
||||
shape_offset_pre = COALESCE(?, shape_offset_pre),
|
||||
shape_offset_spread = COALESCE(?, shape_offset_spread)
|
||||
WHERE serial = ? AND timestamp = ?
|
||||
WHERE serial = ? AND timestamp = ? AND record_type IS ?
|
||||
""",
|
||||
(
|
||||
pv.tran if pv else None,
|
||||
@@ -719,6 +757,7 @@ class SeismoDb:
|
||||
rec.get("shape_offset_spread") if rec else None,
|
||||
serial,
|
||||
ts,
|
||||
ev.record_type,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -728,11 +767,11 @@ class SeismoDb:
|
||||
|
||||
@staticmethod
|
||||
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
|
||||
ts: Optional[str]) -> Optional[str]:
|
||||
ts: Optional[str], record_type: Optional[str] = None) -> Optional[str]:
|
||||
"""Why an event whose time is only an estimate must not be written, or None.
|
||||
|
||||
An estimate (the decoder found no validated event record) may be a
|
||||
second off, and (serial, timestamp) is the table's key. So it never
|
||||
second off, and (serial, timestamp, record_type) is the table's key. So it never
|
||||
moves a row, never lands on another event's row, and never adds a second
|
||||
row for an event already stored -- each refusal is logged by the caller,
|
||||
and the event's file and sidecar are already in the store. Its own
|
||||
@@ -747,8 +786,8 @@ class SeismoDb:
|
||||
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
|
||||
f"time {ts} does not move or duplicate it")
|
||||
holder = conn.execute(
|
||||
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
|
||||
(serial, ts)).fetchone()
|
||||
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
|
||||
"AND record_type IS ?", (serial, ts, record_type)).fetchone()
|
||||
if holder is not None and (named is None or holder[0] != named):
|
||||
return (f"its estimated time {ts} is held by {holder[0] or 'another event'}; "
|
||||
"not merged into it")
|
||||
@@ -756,8 +795,9 @@ class SeismoDb:
|
||||
|
||||
@staticmethod
|
||||
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
|
||||
ts: str) -> Optional[bool]:
|
||||
"""Move this file's row to `ts` when it sits under another time.
|
||||
ts: str, record_type: Optional[str] = None) -> Optional[bool]:
|
||||
"""Move this file's row to `ts` (and `record_type`) when it sits under
|
||||
another time or type.
|
||||
|
||||
The events table is unique on (serial, timestamp), so an event re-stored
|
||||
with a corrected time -- every Series-3 waveform after the event-time fix,
|
||||
@@ -768,6 +808,10 @@ class SeismoDb:
|
||||
stored as "imported.bw" -- so only a Blastware name is matched. Of
|
||||
several rows for one file, a reviewed one with a time moves first.
|
||||
|
||||
The type moves the same way: before v0.33.0 a row's type came from the
|
||||
filename, and with the type in the key (#51) a re-import under the file's
|
||||
own type would otherwise add a second row.
|
||||
|
||||
Returns True when the row was moved; None when there was nothing to move
|
||||
(no row for this file elsewhere, or this file's own row already holds
|
||||
`ts`), so the caller goes on as before; False when a different stored
|
||||
@@ -778,18 +822,20 @@ class SeismoDb:
|
||||
return None
|
||||
mine = conn.execute(
|
||||
"SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? "
|
||||
"AND (timestamp IS NULL OR timestamp != ?) "
|
||||
"AND (timestamp IS NULL OR timestamp != ? OR record_type IS NOT ?) "
|
||||
"ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
|
||||
(serial, filename, ts),
|
||||
(serial, filename, ts, record_type),
|
||||
).fetchone()
|
||||
if mine is None:
|
||||
return None
|
||||
holder = conn.execute(
|
||||
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
|
||||
(serial, ts),
|
||||
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
|
||||
"AND record_type IS ?",
|
||||
(serial, ts, record_type),
|
||||
).fetchone()
|
||||
if holder is None:
|
||||
conn.execute("UPDATE events SET timestamp = ? WHERE id = ?", (ts, mine[0]))
|
||||
conn.execute("UPDATE events SET timestamp = ?, record_type = ? WHERE id = ?",
|
||||
(ts, record_type, mine[0]))
|
||||
log.info("insert_events: %s %s moved from %s to %s (corrected event time)",
|
||||
serial, filename, mine[1], ts)
|
||||
return True
|
||||
@@ -808,7 +854,8 @@ class SeismoDb:
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def find_event_by_blastware_name(self, serial: str, filename: str) -> Optional[dict]:
|
||||
def find_event_by_blastware_name(self, serial: str, filename: str,
|
||||
record_type: Optional[str] = None) -> Optional[dict]:
|
||||
"""The row stored under `filename`'s Blastware name, or None.
|
||||
|
||||
A Blastware name encodes the serial and the event's second
|
||||
@@ -819,6 +866,10 @@ class SeismoDb:
|
||||
itself and the letterless form -- not the other letter, since in
|
||||
Histogram+Continuous a waveform can trigger in the second a histogram
|
||||
starts. Any other name ("imported.bw") matches nothing.
|
||||
|
||||
`record_type`: only a row of that type -- or an untyped one, which may be
|
||||
this event -- matches (#51: a same-second waveform / histogram twin shares
|
||||
the letterless name). Compared ignoring case.
|
||||
"""
|
||||
if blastware_filename_time(filename) is None:
|
||||
return None
|
||||
@@ -828,10 +879,14 @@ class SeismoDb:
|
||||
else:
|
||||
forms = (name, name + "W", name + "H")
|
||||
with self._connect() as conn:
|
||||
typed, args = "", (serial, *forms)
|
||||
if record_type is not None:
|
||||
typed = " AND (record_type IS NULL OR UPPER(record_type) = UPPER(?))"
|
||||
args = (*args, record_type)
|
||||
row = conn.execute(
|
||||
f"SELECT * FROM events WHERE serial = ? AND UPPER(blastware_filename) IN "
|
||||
f"({', '.join('?' * len(forms))}) ORDER BY rowid LIMIT 1",
|
||||
(serial, *forms),
|
||||
f"({', '.join('?' * len(forms))}){typed} ORDER BY rowid LIMIT 1",
|
||||
args,
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
@@ -9,19 +9,29 @@ import threading
|
||||
import time
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from .errors import ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
|
||||
from .errors import BadRequest, ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
|
||||
from .events import parse_event_id
|
||||
from .locks import UnitLocks
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo,
|
||||
UnitSettings, UnitStatus)
|
||||
from .s3 import Series3Adapter, default_s3_client_factory
|
||||
from .s4 import (
|
||||
Series4Session, default_s4_client_factory, s4_change_monitoring, s4_download_event, s4_identify, s4_list_events,
|
||||
s4_settings, s4_status,
|
||||
Series4Session, default_s4_client_factory, s4_call_home_state, s4_change_call_home, s4_change_monitoring,
|
||||
s4_change_settings,
|
||||
s4_download_event, s4_identify, s4_list_events, s4_settings, s4_status,
|
||||
)
|
||||
from .series import normalise_serial, series_for_serial
|
||||
|
||||
log = logging.getLogger("sfm.device_access")
|
||||
|
||||
# A config write is read back at once, not after a sensor check: up to three
|
||||
# reads, a second apart -- not the start/stop window.
|
||||
_CALL_HOME_VERIFY_TIMEOUT_S = 3.0
|
||||
_CALL_HOME_VERIFY_INTERVAL_S = 1.0
|
||||
# A settings read-back is one block read (seconds over cellular): two tries, a second apart.
|
||||
_SETTINGS_VERIFY_TIMEOUT_S = 2.0
|
||||
_SETTINGS_VERIFY_INTERVAL_S = 1.0
|
||||
|
||||
|
||||
class DeviceAccess:
|
||||
def __init__(
|
||||
@@ -109,6 +119,59 @@ class DeviceAccess:
|
||||
lambda c, s: s4_change_monitoring(c, s, address=address, **kw),
|
||||
change=True)
|
||||
|
||||
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
|
||||
return self._dispatch(address, serial,
|
||||
lambda a, s: self._s3.call_home_state(a, s),
|
||||
lambda c, s: s4_call_home_state(c, s))
|
||||
|
||||
def set_call_home(self, address: UnitAddress, serial: str, *, enabled: bool,
|
||||
dry_run: bool = False, even_if_already: bool = False,
|
||||
caller: str = "api") -> ChangeResult:
|
||||
"""Turn the unit's automatic call-home on or off (spec row 9): audited,
|
||||
identity-checked, never retried, read back."""
|
||||
serial = normalise_serial(serial)
|
||||
series_for_serial(serial) # BadRequest (422) before the audit check
|
||||
if not dry_run and self._audit is None:
|
||||
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
|
||||
"without one (nothing sent)")
|
||||
kw = dict(enabled=enabled, dry_run=dry_run, even_if_already=even_if_already,
|
||||
audit=self._audit, caller=caller, sleep=self._sleep,
|
||||
verify_timeout_s=_CALL_HOME_VERIFY_TIMEOUT_S,
|
||||
verify_interval_s=_CALL_HOME_VERIFY_INTERVAL_S)
|
||||
return self._dispatch(
|
||||
address, serial,
|
||||
lambda a, s: self._s3.change_call_home(a, s, **kw),
|
||||
lambda c, s: s4_change_call_home(c, s, address=address, **kw),
|
||||
change=True)
|
||||
|
||||
def change_settings(self, address: UnitAddress, serial: str, *, changes: dict,
|
||||
revision: Optional[str], dry_run: bool = False,
|
||||
caller: str = "api") -> ChangeResult:
|
||||
"""Change the unit's settings (spec row 10, phase 5). A dry run is the
|
||||
preview: old -> new per field and a `revision`. A live change needs that
|
||||
revision; it is audited, identity-checked, sent once, never retried, and
|
||||
read back. Refused before any I/O: no changes, a live call without a
|
||||
revision, no audit log."""
|
||||
serial = normalise_serial(serial)
|
||||
series_for_serial(serial) # BadRequest (422) before anything else
|
||||
if not isinstance(changes, dict) or not changes:
|
||||
raise BadRequest("no settings to change -- nothing sent")
|
||||
if not dry_run and not revision:
|
||||
raise BadRequest("preview first: a live change needs the revision from its preview "
|
||||
"-- nothing sent")
|
||||
if not dry_run and self._audit is None:
|
||||
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
|
||||
"without one (nothing sent)")
|
||||
kw = dict(changes=changes, revision=revision, dry_run=dry_run, audit=self._audit,
|
||||
caller=caller, sleep=self._sleep,
|
||||
verify_timeout_s=_SETTINGS_VERIFY_TIMEOUT_S,
|
||||
verify_interval_s=_SETTINGS_VERIFY_INTERVAL_S)
|
||||
return self._dispatch(
|
||||
address, serial,
|
||||
lambda a, s: self._s3.change_settings(a, s, **kw),
|
||||
lambda c, s: s4_change_settings(c, s, address=address, **kw),
|
||||
change=True)
|
||||
|
||||
def held_serial(self, address: UnitAddress) -> Optional[str]:
|
||||
"""Serial of the OPEN held Series-4 line at this address, else None. No I/O."""
|
||||
with self._sessions_guard:
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
"""The series-independent core of a start/stop request.
|
||||
"""The series-independent core of a change request: start/stop monitoring,
|
||||
call-home on/off. A `ChangeKind` says what the change is called and which state
|
||||
read back means it took.
|
||||
|
||||
Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once ->
|
||||
read back -> audit). Each series supplies only its own pieces as callables:
|
||||
@@ -20,6 +22,7 @@ never taken there.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, List, NoReturn, Optional
|
||||
|
||||
from .errors import (
|
||||
@@ -41,7 +44,43 @@ def _never(exc: BaseException) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_already: bool,
|
||||
@dataclass(frozen=True)
|
||||
class ChangeKind:
|
||||
"""What a change is called (the audit row's action, the messages' subject),
|
||||
the state `read_state` returns once it took, and the past tense for messages."""
|
||||
action: str
|
||||
want: str
|
||||
became: str
|
||||
|
||||
|
||||
def monitoring_change(start: bool) -> ChangeKind:
|
||||
return (ChangeKind("start monitoring", "monitoring", "started") if start
|
||||
else ChangeKind("stop monitoring", "idle", "stopped"))
|
||||
|
||||
|
||||
def call_home_change(enabled: bool) -> ChangeKind:
|
||||
return (ChangeKind("enable call-home", "enabled", "enabled") if enabled
|
||||
else ChangeKind("disable call-home", "disabled", "disabled"))
|
||||
|
||||
|
||||
def settings_change() -> ChangeKind:
|
||||
"""A settings change (phase 5): its "state" is a read-back verdict --
|
||||
"as asked" (the unit holds what was written), "unchanged", or "differs"."""
|
||||
return ChangeKind("change settings", "as asked", "applied")
|
||||
|
||||
|
||||
def _take_snapshot(snapshot: Optional[Callable[[], Dict[str, Any]]]) -> Optional[Dict[str, Any]]:
|
||||
"""The caller's record of what the unit holds after the change -- for the
|
||||
result and the audit row only. It never decides the outcome."""
|
||||
if snapshot is None:
|
||||
return None
|
||||
try:
|
||||
return dict(snapshot())
|
||||
except Exception as exc: # noqa: BLE001 -- a record, never a verdict
|
||||
return {"error": str(exc)}
|
||||
|
||||
|
||||
def run_change(*, kind: ChangeKind, serial: str, series: int, dry_run: bool, even_if_already: bool,
|
||||
audit: Any, address: UnitAddress, caller: str,
|
||||
sleep: Callable[[float], None], verify_timeout_s: float, verify_interval_s: float,
|
||||
read_serial: Callable[[], str],
|
||||
@@ -50,10 +89,9 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
|
||||
send: Callable[[], Dict[str, Any]],
|
||||
is_refusal: Callable[[BaseException], bool] = _never,
|
||||
is_ring: Callable[[BaseException], bool] = _never,
|
||||
pre_send: Optional[Callable[[], None]] = None) -> ChangeResult:
|
||||
action = "start monitoring" if start else "stop monitoring"
|
||||
want = "monitoring" if start else "idle"
|
||||
became = "started" if start else "stopped"
|
||||
pre_send: Optional[Callable[[], None]] = None,
|
||||
snapshot: Optional[Callable[[], Dict[str, Any]]] = None) -> ChangeResult:
|
||||
action, want, became = kind.action, kind.want, kind.became
|
||||
|
||||
reported = normalise_serial(read_serial())
|
||||
if reported != serial:
|
||||
@@ -175,13 +213,18 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; the unit is now calling home",
|
||||
states=states([before], after))
|
||||
lost_detail: Dict[str, Any] = {"error": f"no clean ack: {exc}"}
|
||||
lost_states = states([before], after)
|
||||
snap = _take_snapshot(snapshot) # what the unit holds is what tells whether it landed
|
||||
if snap is not None:
|
||||
lost_detail["snapshot"] = lost_states["snapshot"] = snap
|
||||
finish(f"{action} was sent but the acknowledgement was lost ({exc}); the unit "
|
||||
f"now reads {after}",
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=states([before], after))
|
||||
error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=lost_states)
|
||||
return ChangeResult(dry_run=False, sent=True, outcome="failed",
|
||||
verified="not_checked", state_after=after, audit_id=cid,
|
||||
detail={"error": f"no clean ack: {exc}"}, **base)
|
||||
detail=lost_detail, **base)
|
||||
|
||||
seen = [before]
|
||||
|
||||
@@ -229,9 +272,13 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
|
||||
detail["note"] = note
|
||||
if error is None:
|
||||
error = note
|
||||
row_states = states(seen, last_poll())
|
||||
snap = _take_snapshot(snapshot)
|
||||
if snap is not None:
|
||||
detail["snapshot"] = row_states["snapshot"] = snap
|
||||
finish(f"{action} was sent and verified" if ok else
|
||||
f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}",
|
||||
outcome=outcome, verified=verified, ack=ack, error=error,
|
||||
sent=SENT_ACKNOWLEDGED, states=states(seen, last_poll()))
|
||||
sent=SENT_ACKNOWLEDGED, states=row_states)
|
||||
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
|
||||
state_after=seen[-1], audit_id=cid, detail=detail, **base)
|
||||
@@ -88,6 +88,18 @@ class EventNotFound(DeviceError):
|
||||
http_status = 404
|
||||
|
||||
|
||||
class SettingsChanged(DeviceError):
|
||||
"""The unit's settings changed since the preview the request names (a keypad
|
||||
edit, another program, or a preview of another unit). Nothing was sent."""
|
||||
http_status = 409
|
||||
|
||||
|
||||
class ChangeRefused(DeviceError):
|
||||
"""A change SFM will not send to this unit, and why -- its factory setup, a
|
||||
schedule that would undo it, a block SFM has not seen. Nothing was sent."""
|
||||
http_status = 409
|
||||
|
||||
|
||||
class StaleEvent(DeviceError):
|
||||
"""The event at that key is not the one listed -- the unit was erased, or
|
||||
its memory wrapped, since the list was read."""
|
||||
|
||||
@@ -69,6 +69,18 @@ class UnitSettings:
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CallHomeState:
|
||||
"""A unit's call-home switch, read by serial (phase 4). `enabled` is None when
|
||||
the enable byte is not a value ever measured; `detail` keeps `byte5` and the
|
||||
whole `block` (hex) as read."""
|
||||
serial: str
|
||||
series: int
|
||||
enabled: Optional[bool]
|
||||
dial_string: Optional[str]
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EventRef:
|
||||
"""One stored event, as listed. `event_id` is opaque: pass it back to
|
||||
|
||||
+247
-23
@@ -10,14 +10,27 @@ from typing import Any, Callable, Optional
|
||||
from minimateplus import MiniMateClient
|
||||
from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter
|
||||
from minimateplus.event_file_io import _GEO_INT16_FS
|
||||
from minimateplus.framing import build_bw_write_frame
|
||||
from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING
|
||||
from minimateplus.framing import build_bw_write_frame, unescape_reply
|
||||
from micromate.setup_block import decode_setup
|
||||
from micromate.setup_fields import (
|
||||
SettingsValueError, changes_bytes, check_changes, editable_fields, encode_setup, field_rows,
|
||||
field_values, settings_state,
|
||||
)
|
||||
from micromate.setup_fields import revision as settings_revision
|
||||
from minimateplus.protocol import (
|
||||
SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, SUB_COMPLIANCE_WRITE, SUB_EVENT_INDEX_WRITE,
|
||||
SUB_START_MONITORING, SUB_STOP_MONITORING, SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE,
|
||||
ImageRefused, call_home_enabled, call_home_image, is_call_home_block, is_compliance_content,
|
||||
write_image,
|
||||
)
|
||||
from minimateplus.transport import TcpTransport
|
||||
|
||||
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate
|
||||
from .change import run_change
|
||||
from .errors import (BadRequest, ChangeRefused, DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported,
|
||||
SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit, translate)
|
||||
from .change import call_home_change, monitoring_change, run_change, settings_change
|
||||
from .events import iso_of, make_event_id, stamp_of
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
|
||||
UnitInfo, UnitSettings, UnitStatus)
|
||||
|
||||
log = logging.getLogger("sfm.device_access")
|
||||
|
||||
@@ -27,9 +40,42 @@ S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "H
|
||||
|
||||
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
|
||||
|
||||
# A MiniMate call-home write goes out only once SFM's 0x7E / 0x7F frames are
|
||||
# reproduced from Blastware's own; shut, a live change is refused before any
|
||||
# connection (a dry run still works). OPEN since 2026-11-02:
|
||||
# tests/test_s3_call_home_bw_frames.py rebuilds Blastware's enable and disable
|
||||
# writes (BE11529, 2026-04-20) byte for byte from the unit's own reads.
|
||||
S3_CALL_HOME_FRAME_VERIFIED = True
|
||||
|
||||
# Measured 2026-11-03 (BE9441): while monitoring, a MiniMate answers the 0x2C read
|
||||
# with its device-info block, as it answers 1A -- its call-home settings cannot be
|
||||
# read, so they cannot be changed (SFM writes back only a block it just read).
|
||||
S3_CALL_HOME_WHILE_MONITORING = ("did not return its call-home settings -- a MiniMate answers the "
|
||||
"call-home read with its device-info block while monitoring; "
|
||||
"stop monitoring first, then change call-home")
|
||||
|
||||
# The 0x1C flag byte (section[1]): the only values ever measured. 0x10 is
|
||||
# BE11529 monitoring (2026-04-08); 0x0B is BE9441 recording a histogram,
|
||||
# confirmed at the unit (2026-10-26). Anything else is refused for a change.
|
||||
# Measured 2026-11-03 (BE9441's 10-26 recording, 5 / 5 reads): while monitoring, a
|
||||
# MiniMate answers the 1A settings read with its device-info block.
|
||||
S3_SETTINGS_WHILE_MONITORING = ("did not return its settings -- a MiniMate answers this way "
|
||||
"while monitoring; stop monitoring first (a stop makes it call in "
|
||||
"if call-home is on)")
|
||||
# Blastware's settings write, in its order (push_config_raw): event index, the
|
||||
# settings block in addressed chunks, trigger, waveform data, with their confirms.
|
||||
_S3_SETTINGS_STEPS = ((0x68, "event index (as read)"), (0x73, "confirm B"),
|
||||
(0x71, "settings block"), (0x72, "confirm A"),
|
||||
(0x82, "trigger block (as read)"), (0x83, "trigger confirm"),
|
||||
(0x69, "waveform data (as read)"), (0x74, "confirm C"), (0x72, "confirm A"))
|
||||
_S3_TAIL_WARNING = ("the two bytes after the settings block go out as 00 00 (Blastware sends "
|
||||
"its own constant; the unit took it at the bench 2026-11-04)")
|
||||
# Measured at the bench 2026-11-04 (BE9441): a write sent while the setup menu was open
|
||||
# was acknowledged and read back, then lost when the operator pressed Cancel or Save --
|
||||
# the menu writes its own copy of the whole block back.
|
||||
_S3_MENU_WARNING = ("if someone is in this unit's setup menu, this change is lost when they "
|
||||
"leave it (Cancel or Save writes the menu's copy back)")
|
||||
|
||||
S3_RUN_STATES = {0x00: "idle", 0x10: "monitoring", 0x0B: "monitoring"}
|
||||
|
||||
|
||||
@@ -257,7 +303,7 @@ class Series3Adapter:
|
||||
return s3_run_state(client.get_monitor_status())
|
||||
|
||||
return run_change(
|
||||
serial=serial, series=3, start=start, dry_run=dry_run,
|
||||
kind=monitoring_change(start), serial=serial, series=3, dry_run=dry_run,
|
||||
even_if_already=even_if_already, audit=audit, address=address, caller=caller,
|
||||
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=read_serial,
|
||||
@@ -330,29 +376,207 @@ class Series3Adapter:
|
||||
)
|
||||
return self._run(address, op)
|
||||
|
||||
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
|
||||
"""The unit's call-home switch and dial string (0x2C), after a wake. Like
|
||||
status, it reads no serial: the one shown is the one requested."""
|
||||
def op(client: Any) -> CallHomeState:
|
||||
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
|
||||
raw = client.read_call_home_raw()
|
||||
image = unescape_reply(raw)
|
||||
detail = {"byte5": f"0x{image[5]:02X}" if len(image) > 5 else None,
|
||||
"block": bytes(raw).hex(), "serial_verified": False}
|
||||
if not is_call_home_block(raw):
|
||||
detail["reason"] = f"the unit {S3_CALL_HOME_WHILE_MONITORING}"
|
||||
return CallHomeState(serial=serial, series=3, enabled=None, dial_string=None, detail=detail)
|
||||
dial = bytes(image[6:46]).split(b"\x00", 1)[0].decode("ascii", errors="replace") or None
|
||||
return CallHomeState(serial=serial, series=3, enabled=call_home_enabled(raw),
|
||||
dial_string=dial, detail=detail)
|
||||
return self._run(address, op)
|
||||
|
||||
def change_call_home(self, address: UnitAddress, serial: str, *, enabled: bool, dry_run: bool,
|
||||
even_if_already: bool, audit: Any, caller: str,
|
||||
sleep: Callable[[float], None], verify_timeout_s: float,
|
||||
verify_interval_s: float) -> ChangeResult:
|
||||
"""Series-3 pieces for the shared core: read 0x2C, set byte 5 of the
|
||||
unescaped image, send it (0x7E) and confirm (0x7F), re-read. One attempt,
|
||||
never retried; refused live until the frame is verified against Blastware."""
|
||||
if not dry_run and not S3_CALL_HOME_FRAME_VERIFIED:
|
||||
raise NotSupported("a MiniMate call-home write waits until its frame has been "
|
||||
"reproduced from a Blastware capture -- nothing sent")
|
||||
what = "call-home " + ("enable" if enabled else "disable")
|
||||
|
||||
def op(client: Any) -> ChangeResult:
|
||||
reads: list = []
|
||||
images: list = []
|
||||
|
||||
def read_serial() -> str:
|
||||
return client.connect().serial or "" # a fresh connection: the 0x15 read
|
||||
|
||||
def read_state() -> str:
|
||||
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
|
||||
raw = client.read_call_home_raw()
|
||||
if not is_call_home_block(raw):
|
||||
raise UnitStateUnknown(f"{serial} {S3_CALL_HOME_WHILE_MONITORING} -- nothing sent")
|
||||
reads.append(raw)
|
||||
on = call_home_enabled(raw)
|
||||
if on is None:
|
||||
image = unescape_reply(raw)
|
||||
return f"unknown(0x{image[5]:02X})" if len(image) > 5 else "unknown(short)"
|
||||
return "enabled" if on else "disabled"
|
||||
|
||||
def describe_plan() -> dict:
|
||||
try:
|
||||
image = call_home_image(reads[-1], enabled)
|
||||
except ValueError as exc:
|
||||
images[:] = []
|
||||
return {"action": what, "steps": [], "warnings": [f"{exc}; nothing would be sent"]}
|
||||
images[:] = [image]
|
||||
warnings = []
|
||||
if image == write_image(SUB_CALL_HOME_WRITE, reads[-1]):
|
||||
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
|
||||
" -- this write changes nothing")
|
||||
return {"action": what, "warnings": warnings, "steps": [
|
||||
{"sub": f"0x{SUB_CALL_HOME_WRITE:02X}", "what": "call-home config write",
|
||||
"data_len": len(image), "frame": build_bw_write_frame(SUB_CALL_HOME_WRITE, image).hex()},
|
||||
{"sub": f"0x{SUB_CALL_HOME_CONFIRM:02X}", "what": "call-home config confirm",
|
||||
"data_len": 0, "frame": build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"").hex()}]}
|
||||
|
||||
def send() -> dict:
|
||||
client.write_call_home_image(images[0])
|
||||
return {"subs": [f"0x{0xFF - SUB_CALL_HOME_WRITE:02X}", f"0x{0xFF - SUB_CALL_HOME_CONFIRM:02X}"]}
|
||||
|
||||
def snapshot() -> dict:
|
||||
before = write_image(SUB_CALL_HOME_WRITE, reads[0])
|
||||
after = write_image(SUB_CALL_HOME_WRITE, reads[-1])
|
||||
return {"before": before.hex(), "after": after.hex(),
|
||||
"changed_offsets": [i for i in range(min(len(before), len(after)))
|
||||
if before[i] != after[i]]}
|
||||
|
||||
return run_change(
|
||||
kind=call_home_change(enabled), serial=serial, series=3, dry_run=dry_run,
|
||||
even_if_already=even_if_already, audit=audit, address=address, caller=caller,
|
||||
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=read_serial, read_state=read_state,
|
||||
describe_plan=describe_plan, send=send, snapshot=snapshot,
|
||||
# raised before the frame goes out: audited as nothing sent
|
||||
is_refusal=lambda e: isinstance(e, ImageRefused))
|
||||
return self._run(address, op, retry=False)
|
||||
|
||||
def change_settings(self, address: UnitAddress, serial: str, *, changes: dict,
|
||||
revision: Optional[str], dry_run: bool, audit: Any, caller: str,
|
||||
sleep: Callable[[float], None], verify_timeout_s: float,
|
||||
verify_interval_s: float) -> ChangeResult:
|
||||
"""Series-3 pieces for the shared core (phase 5): read the four settings
|
||||
blocks, patch the settings block's fields (micromate.setup_fields), send
|
||||
Blastware's sequence through push_config_raw with the other three blocks
|
||||
as read, re-read the settings. One attempt, never retried.
|
||||
|
||||
Refused before anything is sent: a monitoring unit (it answers 1A with its
|
||||
device-info block); a value the unit does not allow (BadRequest); a live
|
||||
call whose `revision` is not this read's (SettingsChanged)."""
|
||||
def op(client: Any) -> ChangeResult:
|
||||
st: dict = {}
|
||||
reads: list = []
|
||||
|
||||
def read_serial() -> str:
|
||||
return client.connect().serial or "" # a fresh connection: the 0x15 read
|
||||
|
||||
def read_state() -> str:
|
||||
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
|
||||
if st:
|
||||
now = client.read_compliance_content()
|
||||
if not is_compliance_content(now):
|
||||
raise MalformedReply("the read-back did not return the settings block")
|
||||
reads.append(now)
|
||||
return settings_state(st["setup"], st["image"], now, series=3)
|
||||
blocks = client.read_settings_blocks()
|
||||
setup = blocks["compliance"]
|
||||
if not is_compliance_content(setup):
|
||||
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")
|
||||
try:
|
||||
normal = check_changes(setup, 3, changes)
|
||||
except SettingsValueError as exc:
|
||||
raise BadRequest(f"{exc} -- nothing sent") from exc
|
||||
# What the preview showed: the settings block and the changes. The other
|
||||
# three blocks are re-read here and sent back as read (the trigger block's
|
||||
# byte 5 "differs by unit and session", #46).
|
||||
rev = settings_revision([setup, changes_bytes(normal)])
|
||||
if not dry_run and revision != rev:
|
||||
raise SettingsChanged(f"{serial}'s settings, or the changes asked for, are not "
|
||||
"the ones previewed -- preview again; nothing sent")
|
||||
image = encode_setup(setup, 3, normal)
|
||||
blocked = []
|
||||
for sub, block in ((SUB_EVENT_INDEX_WRITE, blocks["event_index"]),
|
||||
(SUB_COMPLIANCE_WRITE, image),
|
||||
(SUB_TRIGGER_CONFIG_WRITE, blocks["trigger"]),
|
||||
(SUB_WAVEFORM_DATA_WRITE, blocks["waveform"])):
|
||||
try:
|
||||
write_image(sub, block, escaped=False) # push_config_raw's own check
|
||||
except ValueError as exc:
|
||||
blocked.append(f"this unit's {exc} -- SFM has not seen a block like it")
|
||||
st.update(blocks=blocks, setup=setup, image=image, changes=normal, revision=rev,
|
||||
blocked=blocked)
|
||||
reads.append(setup)
|
||||
return settings_state(setup, image, setup, series=3)
|
||||
|
||||
def describe_plan() -> dict:
|
||||
b = st["blocks"]
|
||||
lens = {0x68: len(b["event_index"]), 0x71: len(st["image"]) + 2,
|
||||
0x82: len(b["trigger"]), 0x69: len(b["waveform"])}
|
||||
if st["blocked"] and not dry_run:
|
||||
raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent")
|
||||
steps = [] if st["blocked"] else [
|
||||
{"sub": f"0x{sub:02X}", "what": what, "data_len": lens.get(sub, 0)}
|
||||
for sub, what in _S3_SETTINGS_STEPS]
|
||||
return {"action": "settings write", "blocked": list(st["blocked"]), "steps": steps,
|
||||
"fields": field_rows(st["setup"], st["image"], 3, st["changes"]),
|
||||
"revision": st["revision"], "warnings": [_S3_MENU_WARNING, _S3_TAIL_WARNING]}
|
||||
|
||||
def send() -> dict:
|
||||
b = st["blocks"]
|
||||
client.push_config_raw(b["event_index"], st["image"], b["trigger"], b["waveform"],
|
||||
escaped=False) # every block read is logical
|
||||
return {"subs": [f"0x{0xFF - sub:02X}" for sub, _ in _S3_SETTINGS_STEPS]}
|
||||
|
||||
def snapshot() -> dict:
|
||||
before, after = st["setup"], reads[-1]
|
||||
return {"fields": field_rows(before, st["image"], 3, st["changes"], now=after),
|
||||
"before": before.hex(), "after": after.hex(),
|
||||
"changed_offsets": [i for i in range(min(len(before), len(after)))
|
||||
if before[i] != after[i]]}
|
||||
|
||||
return run_change(
|
||||
kind=settings_change(), serial=serial, series=3, dry_run=dry_run,
|
||||
even_if_already=False, audit=audit, address=address, caller=caller, sleep=sleep,
|
||||
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=read_serial, read_state=read_state, describe_plan=describe_plan,
|
||||
send=send, snapshot=snapshot,
|
||||
# raised before the first frame goes out: audited as nothing sent
|
||||
is_refusal=lambda e: isinstance(e, ImageRefused))
|
||||
return self._run(address, op, retry=False)
|
||||
|
||||
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
|
||||
"""The 1A read assembled into the logical block and decoded by the shared
|
||||
settings codec (phase 5)."""
|
||||
def op(client: Any) -> UnitSettings:
|
||||
info = client.connect()
|
||||
self._check(info.serial, serial, address)
|
||||
cc = info.compliance_config
|
||||
if cc is None:
|
||||
raise MalformedReply("could not read the unit's settings (SUB 0x1A)")
|
||||
mode = None
|
||||
if cc.recording_mode is not None:
|
||||
mode = S3_MODES.get(cc.recording_mode, f"unknown (0x{cc.recording_mode:02x})")
|
||||
notes = {
|
||||
label: value for label, value in (
|
||||
("Project", cc.project), ("Client", cc.client), ("User Name", cc.operator),
|
||||
("Seis Loc", cc.sensor_location), ("Extended Notes", cc.notes),
|
||||
) if value is not None
|
||||
}
|
||||
content = client.read_compliance_content()
|
||||
if not is_compliance_content(content):
|
||||
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING}")
|
||||
v = field_values(content, 3)
|
||||
name = decode_setup(content + bytes(2), verify=False).name # Series 3 reads no CRC
|
||||
labels = {d["field"]: d["label"] for d in editable_fields(content, 3)}
|
||||
notes = {labels[f]: v[f] for f in ("note_1", "note_2", "note_3", "note_4")}
|
||||
code = content[5]
|
||||
return UnitSettings(
|
||||
serial=info.serial, series=3, setup_name=cc.setup_name, record_mode=mode,
|
||||
sample_rate=cc.sample_rate, record_time_s=cc.record_time,
|
||||
histogram_interval_s=cc.histogram_interval_sec, geo_trigger_ips=cc.trigger_level_geo,
|
||||
serial=info.serial, series=3, setup_name=name or None,
|
||||
record_mode=S3_MODES.get(code, f"unknown (0x{code:02x})"),
|
||||
sample_rate=v["sample_rate"], record_time_s=v["record_time_s"],
|
||||
histogram_interval_s=v["histogram_interval_s"], geo_trigger_ips=v["geo_trigger_ips"],
|
||||
notes=notes,
|
||||
detail={"record_mode_code": cc.recording_mode, "alarm_level_geo": cc.alarm_level_geo,
|
||||
"geo_range": cc.geo_range},
|
||||
detail={"record_mode_code": code, "alarm_level_geo": v["geo_alarm_ips"],
|
||||
"geo_range": v["geo_range"], "editable": editable_fields(content, 3)},
|
||||
)
|
||||
return self._run(address, op)
|
||||
|
||||
|
||||
+221
-7
@@ -19,16 +19,31 @@ from typing import Any, Callable, Optional, TypeVar
|
||||
from micromate.client import MicromateClient
|
||||
from micromate.opcodes import OpcodeRefused
|
||||
from micromate.protocol import THOR_CHUNK_SIZE
|
||||
from micromate.writes import plan_start_monitoring, plan_stop_monitoring
|
||||
from micromate.protocol import ProtocolError as _MMProtocolError
|
||||
from micromate.schedule import parse_schedule, schedule_conflicts
|
||||
from micromate.setup_block import decode_setup
|
||||
from micromate.setup_fields import (
|
||||
SettingsValueError, changes_bytes, check_changes, editable_fields, encode_setup, field_rows,
|
||||
settings_state,
|
||||
)
|
||||
from micromate.setup_fields import revision as settings_revision
|
||||
from micromate.writes import (
|
||||
is_call_home_content, plan_call_home_enabled, plan_setup_push, plan_start_monitoring,
|
||||
plan_stop_monitoring,
|
||||
)
|
||||
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
|
||||
|
||||
from .errors import (
|
||||
AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound,
|
||||
MalformedReply, StaleEvent, WrongUnit, translate,
|
||||
AuditIncomplete, BadRequest, CallHomeInProgress, ChangeRefused, ChangeUnconfirmed, DeviceError,
|
||||
EventNotFound, MalformedReply, SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit,
|
||||
translate,
|
||||
)
|
||||
from .change import (
|
||||
CALL_HOME_MESSAGE, call_home_change, monitoring_change, run_change, settings_change,
|
||||
)
|
||||
from .change import CALL_HOME_MESSAGE, run_change
|
||||
from .events import iso_of, make_event_id, stamp_of
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
|
||||
UnitInfo, UnitSettings, UnitStatus)
|
||||
from .series import normalise_serial
|
||||
|
||||
log = logging.getLogger("sfm.device_access")
|
||||
@@ -265,7 +280,8 @@ def s4_status(client: Any, serial: str, run_state: bool = False) -> UnitStatus:
|
||||
|
||||
|
||||
def s4_settings(client: Any, serial: str) -> UnitSettings:
|
||||
s = client.get_setup()
|
||||
content = client.get_setup_content()
|
||||
s = decode_setup(content)
|
||||
return UnitSettings(
|
||||
serial=serial, series=4, setup_name=s.name, record_mode=s.record_mode_name,
|
||||
sample_rate=s.sample_rate, record_time_s=s.record_time_s,
|
||||
@@ -290,6 +306,7 @@ def s4_settings(client: Any, serial: str) -> UnitSettings:
|
||||
"distance_ft": s.distance_ft,
|
||||
"charge_weight_lb": s.charge_weight_lb,
|
||||
"scaled_distance": s.scaled_distance,
|
||||
"editable": editable_fields(content, 4),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -357,7 +374,8 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
||||
|
||||
return run_change(
|
||||
serial=serial, series=4, start=start, dry_run=dry_run, even_if_already=even_if_already,
|
||||
kind=monitoring_change(start), serial=serial, series=4, dry_run=dry_run,
|
||||
even_if_already=even_if_already,
|
||||
audit=audit, address=address, caller=caller, sleep=sleep,
|
||||
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=lambda: client.serial(refresh=True),
|
||||
@@ -369,3 +387,199 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
# out. One transport read: RingWatchTransport over Tcp/SerialTransport,
|
||||
# each with a 10 ms read timeout, so it returns at once on a quiet line.
|
||||
pre_send=lambda: client.read_unsolicited())
|
||||
|
||||
|
||||
def _dial_string(block: bytes) -> Optional[str]:
|
||||
raw = bytes(block[6:46]).split(b"\x00", 1)[0]
|
||||
return raw.decode("ascii", errors="replace") or None
|
||||
|
||||
|
||||
def _changed_offsets(before: bytes, after: bytes) -> list:
|
||||
return [i for i in range(max(len(before), len(after)))
|
||||
if (before[i] if i < len(before) else None) != (after[i] if i < len(after) else None)]
|
||||
|
||||
|
||||
# Measured 2026-11-03 (UM20147): monitoring, a Micromate returns its real call-home
|
||||
# block and ACKS a write, but does not apply it -- its own menu: "Feature disabled
|
||||
# while monitoring". So SFM refuses before sending one it would ignore.
|
||||
S4_CALL_HOME_WHILE_MONITORING = ("is monitoring -- a Micromate ignores call-home changes while "
|
||||
"monitoring (its own menu: 'Feature disabled while monitoring'); "
|
||||
"stop monitoring first, then change call-home")
|
||||
_NOT_CALL_HOME = "returned a block that is not its call-home block (header {}, not 007c)"
|
||||
|
||||
|
||||
def s4_call_home_state(client: Any, serial: str) -> CallHomeState:
|
||||
"""Bit 0 of content[5] is the enable (UM12947 reads 0x05 / 0x04, UM20147 0x01)."""
|
||||
block = client.get_call_home_content()
|
||||
detail = {"byte5": f"0x{block[5]:02X}" if len(block) > 5 else None, "block": block.hex()}
|
||||
if not is_call_home_content(block):
|
||||
detail["reason"] = "the unit " + _NOT_CALL_HOME.format(block[0:2].hex())
|
||||
return CallHomeState(serial=serial, series=4, enabled=None, dial_string=None, detail=detail)
|
||||
return CallHomeState(serial=serial, series=4, enabled=bool(block[5] & 0x01),
|
||||
dial_string=_dial_string(block), detail=detail)
|
||||
|
||||
|
||||
def s4_change_call_home(client: Any, serial: str, *, enabled: bool, dry_run: bool,
|
||||
even_if_already: bool, audit: Any, address: UnitAddress,
|
||||
caller: str, sleep: Callable[[float], None],
|
||||
verify_timeout_s: float, verify_interval_s: float) -> ChangeResult:
|
||||
"""Series-4 pieces for the shared core: read 0x2C, flip bit 0 of [5], send the
|
||||
rest back byte for byte, re-read. The plan is built from the read run_change
|
||||
made just before it (spec: build the plan on the same line, right before
|
||||
sending), and that same plan is the one sent."""
|
||||
reads: list = []
|
||||
planned: list = []
|
||||
|
||||
def read_state() -> str:
|
||||
run = client.read_run_state().name
|
||||
if run == "calling_home" or run.startswith("unknown"):
|
||||
return run # the core refuses both; a write waits for a known state
|
||||
if run == "monitoring" and not reads:
|
||||
raise UnitStateUnknown(f"{serial} {S4_CALL_HOME_WHILE_MONITORING} -- nothing sent")
|
||||
block = client.get_call_home_content()
|
||||
if not is_call_home_content(block):
|
||||
raise UnitStateUnknown(f"{serial} " + _NOT_CALL_HOME.format(block[0:2].hex())
|
||||
+ " -- nothing sent")
|
||||
reads.append(block)
|
||||
return "enabled" if block[5] & 0x01 else "disabled"
|
||||
|
||||
def describe_plan() -> dict:
|
||||
planned[:] = [plan_call_home_enabled(reads[-1], enabled)]
|
||||
return planned[0].describe()
|
||||
|
||||
def send() -> dict:
|
||||
acks = client.protocol.execute(planned[0])
|
||||
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
||||
|
||||
def snapshot() -> dict:
|
||||
before, after = reads[0], reads[-1]
|
||||
return {"before": before.hex(), "after": after.hex(),
|
||||
"changed_offsets": _changed_offsets(before, after)}
|
||||
|
||||
return run_change(
|
||||
kind=call_home_change(enabled), serial=serial, series=4, dry_run=dry_run,
|
||||
even_if_already=even_if_already, audit=audit, address=address, caller=caller, sleep=sleep,
|
||||
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=lambda: client.serial(refresh=True),
|
||||
read_state=read_state, describe_plan=describe_plan, send=send,
|
||||
is_refusal=lambda e: isinstance(e, OpcodeRefused),
|
||||
is_ring=lambda e: isinstance(e, RingDetected),
|
||||
pre_send=lambda: client.read_unsolicited(),
|
||||
snapshot=snapshot)
|
||||
|
||||
|
||||
# ── Changing settings (phase 5) ──────────────────────────────────────────────
|
||||
|
||||
S4_SETTINGS_WHILE_MONITORING = ("is monitoring -- stop it first (a stop makes it call in if "
|
||||
"call-home is on)")
|
||||
_EDIT_BUFFER_WARNING = ("this reads the unit's keypad edit buffer: if someone is in its menu, "
|
||||
"their unsaved edits are sent too")
|
||||
_FACTORY = "factory.mmb"
|
||||
|
||||
|
||||
def s4_change_settings(client: Any, serial: str, *, changes: dict, revision: Optional[str],
|
||||
dry_run: bool, audit: Any, address: UnitAddress, caller: str,
|
||||
sleep: Callable[[float], None], verify_timeout_s: float,
|
||||
verify_interval_s: float) -> ChangeResult:
|
||||
"""Series-4 pieces for the shared core: read the name, preferences, trigger
|
||||
and setup blocks and the schedule; patch the setup's fields
|
||||
(micromate.setup_fields); send THOR's setup push under the active setup's own
|
||||
name; read the setup back. The plan is built from the read run_change made
|
||||
just before it, and that same plan is the one sent.
|
||||
|
||||
Refused before anything is sent: a monitoring unit; values the unit does not
|
||||
allow (BadRequest); a live call whose `revision` is not this read's
|
||||
(SettingsChanged); the factory setup, a schedule that would load another
|
||||
setup, an unreadable schedule, or a block SFM has not seen (ChangeRefused,
|
||||
shown as `blocked` in a preview)."""
|
||||
st: dict = {}
|
||||
reads: list = []
|
||||
|
||||
def first_read() -> str:
|
||||
name = client.get_active_setup_raw()
|
||||
prefs = client.get_prefs_content()
|
||||
trigger = client.get_trigger_content()
|
||||
setup = client.get_setup_content()
|
||||
try:
|
||||
normal = check_changes(setup, 4, changes)
|
||||
except SettingsValueError as exc:
|
||||
raise BadRequest(f"{exc} -- nothing sent") from exc
|
||||
# What the preview showed: the target name, the setup block, the changes. The
|
||||
# preferences and trigger blocks are re-read here and sent back as read.
|
||||
rev = settings_revision([name.encode("ascii", "replace"), setup, changes_bytes(normal)])
|
||||
if not dry_run and revision != rev:
|
||||
raise SettingsChanged(f"{serial}'s settings, or the changes asked for, are not the ones "
|
||||
"previewed -- preview again; nothing sent")
|
||||
image = encode_setup(setup, 4, normal)
|
||||
blocked: list = []
|
||||
warnings = [_EDIT_BUFFER_WARNING]
|
||||
if name.strip().casefold() == _FACTORY:
|
||||
blocked.append("this unit is running its factory setup; load any other setup on "
|
||||
"its keypad, then try again")
|
||||
try:
|
||||
entries = parse_schedule(client.read_schedule())
|
||||
except (_MMProtocolError, ValueError) as exc:
|
||||
blocked.append(f"could not read this unit's schedule ({exc}) -- SFM will not change "
|
||||
"a unit whose schedule it cannot check")
|
||||
else:
|
||||
conflicts = schedule_conflicts(entries, name)
|
||||
for e in conflicts:
|
||||
blocked.append(f"this unit's schedule loads {e.setup} at {e.time}, which would "
|
||||
"replace this change")
|
||||
for e in entries:
|
||||
if "start_with_setup" in e.actions and e not in conflicts:
|
||||
warnings.append(f"the unit's schedule loads this setup at {e.time}; the "
|
||||
"change survives it")
|
||||
plan = None
|
||||
try:
|
||||
plan = plan_setup_push(prefs, trigger, image, name)
|
||||
except ValueError as exc:
|
||||
blocked.append(f"this unit's {exc} -- SFM has not seen a block like it")
|
||||
st.update(name=name, prefs=prefs, trigger=trigger, setup=setup, image=image,
|
||||
changes=normal, revision=rev, blocked=blocked, warnings=warnings, plan=plan)
|
||||
reads.append(setup)
|
||||
return settings_state(setup, image, setup, series=4)
|
||||
|
||||
def read_state() -> str:
|
||||
run = client.read_run_state().name
|
||||
if run == "calling_home" or run.startswith("unknown"):
|
||||
return run # the core refuses both; a write waits for a known state
|
||||
if not st:
|
||||
if run == "monitoring":
|
||||
raise UnitStateUnknown(f"{serial} {S4_SETTINGS_WHILE_MONITORING} -- nothing sent")
|
||||
return first_read()
|
||||
now = client.get_setup_content()
|
||||
reads.append(now)
|
||||
return settings_state(st["setup"], st["image"], now, series=4)
|
||||
|
||||
def describe_plan() -> dict:
|
||||
ok = st["plan"] is not None and not st["blocked"]
|
||||
d = st["plan"].describe() if ok else {"action": "setup push", "steps": [], "warnings": []}
|
||||
d["warnings"] = list(st["warnings"]) + list(d.get("warnings", []))
|
||||
d.update(fields=field_rows(st["setup"], st["image"], 4, st["changes"]),
|
||||
revision=st["revision"], blocked=list(st["blocked"]))
|
||||
if st["blocked"] and not dry_run:
|
||||
raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent")
|
||||
return d
|
||||
|
||||
def send() -> dict:
|
||||
acks = client.protocol.execute(st["plan"])
|
||||
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
|
||||
|
||||
def snapshot() -> dict:
|
||||
before, after = st["setup"], reads[-1]
|
||||
return {"fields": field_rows(before, st["image"], 4, st["changes"], now=after),
|
||||
"before": before.hex(), "after": after.hex(),
|
||||
"changed_offsets": _changed_offsets(before, after),
|
||||
"prefs": st["prefs"].hex(), "trigger": st["trigger"].hex()}
|
||||
|
||||
return run_change(
|
||||
kind=settings_change(), serial=serial, series=4, dry_run=dry_run, even_if_already=False,
|
||||
audit=audit, address=address, caller=caller, sleep=sleep,
|
||||
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=lambda: client.serial(refresh=True),
|
||||
read_state=read_state, describe_plan=describe_plan, send=send,
|
||||
is_refusal=lambda e: isinstance(e, OpcodeRefused),
|
||||
is_ring=lambda e: isinstance(e, RingDetected),
|
||||
pre_send=lambda: client.read_unsolicited(),
|
||||
snapshot=snapshot)
|
||||
@@ -32,6 +32,16 @@ Layout written to `<filename>.h5`:
|
||||
client str
|
||||
operator str
|
||||
sensor_location str
|
||||
job_number int (only when read; kept while not shown)
|
||||
job_number_enabled bool (Blastware prints the job number)
|
||||
battery_volts, triggered_by, trigger_sources, trigger_level_geo_ips,
|
||||
trigger_level_mic_psi, firmware_version, dsp_version, model,
|
||||
calibration_date (ISO), calibrated_by
|
||||
(each only when read from the event file)
|
||||
histogram_interval_sec int (histograms)
|
||||
/intervals (histograms, when read)
|
||||
half_period/<ch> uint16 samples per interval; Hz = (sample rate / 2) / it
|
||||
pvs_ips float32 each interval's vector sum, in/s
|
||||
peak_tran_ips float (from 0C; authoritative)
|
||||
peak_vert_ips float
|
||||
peak_long_ips float
|
||||
@@ -257,6 +267,27 @@ def write_event_hdf5(
|
||||
attrs["client"] = (pi.client if pi else "") or ""
|
||||
attrs["operator"] = (pi.operator if pi else "") or ""
|
||||
attrs["sensor_location"] = (pi.sensor_location if pi else "") or ""
|
||||
if pi is not None and getattr(pi, "job_number", None) is not None:
|
||||
attrs["job_number"] = int(pi.job_number)
|
||||
attrs["job_number_enabled"] = bool(pi.job_number_enabled)
|
||||
# Read from a Blastware file's identity and setup blocks; absent when not read.
|
||||
for attr, value in (
|
||||
("battery_volts", getattr(event, "battery_volts", None)),
|
||||
("triggered_by", getattr(event, "triggered_by", None)),
|
||||
("trigger_sources", getattr(event, "trigger_sources", None)),
|
||||
("trigger_level_geo_ips", getattr(event, "trigger_level_geo", None)),
|
||||
("trigger_level_mic_psi", getattr(event, "trigger_level_mic_psi", None)),
|
||||
("histogram_interval_sec", getattr(event, "histogram_interval_sec", None)),
|
||||
):
|
||||
if value is not None:
|
||||
attrs[attr] = value
|
||||
di = getattr(event, "device_info", None)
|
||||
if di is not None:
|
||||
for attr in ("firmware_version", "dsp_version", "model", "calibrated_by"):
|
||||
if getattr(di, attr, None):
|
||||
attrs[attr] = getattr(di, attr)
|
||||
if getattr(di, "calibration_date", None) is not None:
|
||||
attrs["calibration_date"] = di.calibration_date.isoformat()
|
||||
attrs["peak_tran_ips"] = float(pv.tran if pv and pv.tran is not None else 0.0)
|
||||
attrs["peak_vert_ips"] = float(pv.vert if pv and pv.vert is not None else 0.0)
|
||||
attrs["peak_long_ips"] = float(pv.long if pv and pv.long is not None else 0.0)
|
||||
@@ -278,6 +309,22 @@ def write_event_hdf5(
|
||||
compression="gzip", compression_opts=4, shuffle=True,
|
||||
)
|
||||
|
||||
# /intervals — a histogram's per-interval detail as the file holds it:
|
||||
# each channel's half-period in samples (frequency = (sample rate / 2)
|
||||
# / half-period; 0 is Blastware's "N/A") and each interval's vector sum.
|
||||
half_periods = getattr(event, "interval_half_periods", None)
|
||||
interval_pvs = getattr(event, "interval_pvs", None)
|
||||
if half_periods or interval_pvs:
|
||||
igrp_iv = f.create_group("intervals")
|
||||
if half_periods:
|
||||
hgrp = igrp_iv.create_group("half_period")
|
||||
for ch, hps in half_periods.items():
|
||||
hgrp.create_dataset(ch, data=np.asarray(hps, dtype="uint16"),
|
||||
compression="gzip", compression_opts=4, shuffle=True)
|
||||
if interval_pvs:
|
||||
igrp_iv.create_dataset("pvs_ips", data=np.asarray(interval_pvs, dtype="float32"),
|
||||
compression="gzip", compression_opts=4, shuffle=True)
|
||||
|
||||
# /samples_int16 — optional raw ADC counts (preserved for analysis
|
||||
# tools that want pre-conversion data). Cheap to include.
|
||||
if include_int16:
|
||||
|
||||
+72
-35
@@ -66,36 +66,41 @@ def _already_stored(dl: DownloadedEvent, row: dict) -> EventDownload:
|
||||
)
|
||||
|
||||
|
||||
def _overlay_s3_record(ev: Any, unit_peaks: Any, geo_range: Any) -> None:
|
||||
"""The unit's own 0C values over the file's, where the file's are not yet right.
|
||||
def _file_geo_range(bw_bytes: bytes) -> Any:
|
||||
"""The geophone range a Blastware file was recorded at (0 Normal, 1 Sensitive),
|
||||
or None when it does not read -- or the file does not decode at all."""
|
||||
from minimateplus import event_file_io
|
||||
try:
|
||||
return event_file_io.decode_blastware_bytes(bw_bytes).geo_range
|
||||
except Exception: # noqa: BLE001 -- the store reports it
|
||||
return None
|
||||
|
||||
* Mic: always the unit's -- the file reads it as 0 (its psi conversion is an
|
||||
open checker finding).
|
||||
* Channel peaks and vector sum: the file's when the unit's settings confirm
|
||||
Normal range (`geo_range` 0). The file reads them as the unit stored them
|
||||
-- K441LTON.900: 0.200 / 0.385 / 0.255 and 0.385, as Blastware's report,
|
||||
since the decode checker's fix (625bc39, 2026-10-31) -- while the 0C summary
|
||||
is read at fixed offsets and can shift (BE9441 read 0 and -0.0 for vector
|
||||
sums, bench #4). But the file reader computes every peak as if the range
|
||||
were Normal, so a Sensitive unit's come out 8x off (the checker's 33
|
||||
waveforms): for Sensitive, or a range not read (a monitoring unit's 1A
|
||||
carries no settings), the unit's own peaks stand, as before -- a vector
|
||||
sum below the largest channel peak is impossible and is not kept.
|
||||
|
||||
The 0C peaks remain the download *check* (verify_s3_download) either way.
|
||||
def _overlay_s3_record(ev: Any, unit_peaks: Any, unit_range: Any) -> None:
|
||||
"""The unit's own 0C peaks over the file's -- only where the file cannot be trusted.
|
||||
|
||||
The file reads everything Blastware reports (checked on 70,042 events): the
|
||||
channel peaks and the vector sum, scaled by the geophone range in its own
|
||||
setup block (4844135), and the mic (5644dbd). The 0C summary is read at
|
||||
fixed offsets and can shift -- BE9441's read 0 and -0.0 for vector sums
|
||||
(bench #4) -- so the file's values stand.
|
||||
|
||||
Except when the file's range does not read (`ev.geo_range` None; never seen
|
||||
in DL2): the decoder then assumes Normal, 8x off for a Sensitive unit. Then
|
||||
the unit's settings decide: Normal confirmed (`unit_range` 0) keeps the
|
||||
file's peaks; Sensitive or unread keeps the unit's own, as before -- a vector
|
||||
sum below the largest channel peak is impossible and is not kept. The mic
|
||||
is the file's either way: its scale does not depend on the geophone range.
|
||||
"""
|
||||
if unit_peaks is None or getattr(ev, "geo_range", None) is not None:
|
||||
return
|
||||
if unit_range in (0, "normal"):
|
||||
return
|
||||
from minimateplus.models import PeakValues
|
||||
|
||||
if unit_peaks is None:
|
||||
return
|
||||
if ev.peak_values is None:
|
||||
ev.peak_values = PeakValues()
|
||||
pv = ev.peak_values
|
||||
micl = getattr(unit_peaks, "micl", None)
|
||||
if micl is not None:
|
||||
pv.micl = micl
|
||||
if geo_range in (0, "normal"):
|
||||
return
|
||||
for name in ("tran", "vert", "long"):
|
||||
value = getattr(unit_peaks, name, None)
|
||||
if value is not None:
|
||||
@@ -129,16 +134,43 @@ def _overlay_s4_record(ev: Any, record: dict) -> None:
|
||||
ev.project_info.sensor_location = location
|
||||
|
||||
|
||||
def _download_record_type(dl: DownloadedEvent) -> Optional[str]:
|
||||
"""The download's own record type -- "Waveform" / "Histogram", as every stored
|
||||
row has it -- from its file: a Series-3 file's STRT[18], a Series-4 name's
|
||||
IDFW / IDFH. None when it does not read (then any row at its second counts)."""
|
||||
if dl.series == 4:
|
||||
ext = dl.filename.rsplit(".", 1)[-1].upper()
|
||||
return {"IDFW": "Waveform", "IDFH": "Histogram"}.get(ext)
|
||||
if not dl.bw_bytes:
|
||||
return None
|
||||
try:
|
||||
from minimateplus.event_file_io import decode_blastware_bytes
|
||||
return decode_blastware_bytes(dl.bw_bytes).record_type
|
||||
except Exception: # noqa: BLE001 -- a check, not a decode
|
||||
return None
|
||||
|
||||
|
||||
def _same_type(row_type: Optional[str], mine: Optional[str]) -> bool:
|
||||
"""An untyped row, or a download whose type does not read, matches
|
||||
conservatively: it may be this event."""
|
||||
return row_type is None or mine is None or row_type.casefold() == mine.casefold()
|
||||
|
||||
|
||||
def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload:
|
||||
# Never merge: a row for (serial, timestamp) means the event is stored, and
|
||||
# whoever stored it first keeps it. No store call, no insert, no sidecar.
|
||||
# Never merge: a row for (serial, timestamp, record type) means the event is
|
||||
# stored, and whoever stored it first keeps it. No store call, no insert, no
|
||||
# sidecar. The type matters since #51: a waveform and a histogram recorded in
|
||||
# the same second (Histogram + Continuous) are two events.
|
||||
kind = _download_record_type(dl)
|
||||
if dl.timestamp is not None:
|
||||
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1)
|
||||
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=10)
|
||||
rows = [r for r in rows if _same_type(r.get("record_type"), kind)]
|
||||
if rows:
|
||||
return _already_stored(dl, rows[0])
|
||||
# A histogram's row is stored at its file's time, a second before the unit's
|
||||
# on most (#51), so the time above misses it; its Blastware name does not.
|
||||
row = db.find_event_by_blastware_name(dl.serial, dl.filename)
|
||||
# The Blastware name encodes the event's second (a second guard; before #51 a
|
||||
# histogram's row sat a second off the unit's time). Both twins share the
|
||||
# letterless name, so it too is held to the type.
|
||||
row = db.find_event_by_blastware_name(dl.serial, dl.filename, record_type=kind)
|
||||
if row is not None:
|
||||
return _already_stored(dl, row)
|
||||
if dl.series == 4:
|
||||
@@ -149,18 +181,23 @@ def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownlo
|
||||
family = "series4"
|
||||
else:
|
||||
# The same path production's watcher uses for Blastware's own files: the
|
||||
# event is decoded from the file (samples, histogram, setup-block sample
|
||||
# rate and record time), not from the live 5A decode. The unit's 0C mic
|
||||
# goes over the file's, and its peaks too unless Normal range is
|
||||
# confirmed (_overlay_s3_record).
|
||||
# event is decoded from the file -- samples, histogram, peaks, vector sum,
|
||||
# mic, sample rate, record time and the geophone range it was recorded
|
||||
# at -- not from the live 5A decode. The unit's 0C summary is the
|
||||
# download check (verify_s3_download); it fills in only when the file's
|
||||
# range does not read (_overlay_s3_record).
|
||||
if not dl.bw_bytes:
|
||||
raise IngestError(f"{dl.filename}: the download carried no event file; nothing was stored")
|
||||
geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None
|
||||
unit_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None
|
||||
# The file's range is the setting when it recorded; the live 1A is the
|
||||
# unit's setting now, which may have changed since -- the fallback only.
|
||||
# None lets the store scale by the file's own range.
|
||||
ev, rec = store.save_imported_bw(dl.bw_bytes, source_path=Path(dl.filename),
|
||||
serial_hint=dl.serial, source_kind="sfm-live",
|
||||
geo_range=geo_range if geo_range is not None else "normal")
|
||||
geo_range=None if _file_geo_range(dl.bw_bytes) is not None
|
||||
else unit_range)
|
||||
if ev is not None and dl.event is not None:
|
||||
_overlay_s3_record(ev, getattr(dl.event, "peak_values", None), geo_range)
|
||||
_overlay_s3_record(ev, getattr(dl.event, "peak_values", None), unit_range)
|
||||
family = "series3"
|
||||
if ev is None or ev._waveform_key is None:
|
||||
raise IngestError(f"{dl.filename}: stored the file but could not build a database row")
|
||||
|
||||
+138
-136
@@ -50,13 +50,14 @@ import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Mapping, Optional
|
||||
from typing import Any, Dict, Mapping, Optional
|
||||
|
||||
# FastAPI / Pydantic
|
||||
try:
|
||||
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel
|
||||
import uvicorn
|
||||
except ImportError:
|
||||
@@ -85,7 +86,7 @@ from sfm import db_snapshot
|
||||
from sfm.event_ingest import backfill_series3_event, persist_download
|
||||
import dataclasses
|
||||
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
|
||||
from sfm.device_access.errors import BadRequest
|
||||
from sfm.device_access.errors import BadRequest, ChangeUnconfirmed
|
||||
from sfm.device_access.series import normalise_serial, series_for_serial
|
||||
from sfm.audit import DbAudit
|
||||
|
||||
@@ -118,6 +119,20 @@ app.add_middleware(
|
||||
)
|
||||
|
||||
|
||||
class _PageScripts(StaticFiles):
|
||||
"""sfm/static/: the web page's JavaScript (no inline JS -- a stack-wide rule,
|
||||
2026-11-02). `no-cache` makes the browser revalidate on every load, a cheap
|
||||
304, so a page served by a new SFM never runs an old SFM's cached script."""
|
||||
|
||||
async def get_response(self, path, scope):
|
||||
response = await super().get_response(path, scope)
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
app.mount("/static", _PageScripts(directory=str(Path(__file__).parent / "static")), name="static")
|
||||
|
||||
|
||||
# ── DB ────────────────────────────────────────────────────────────────────────
|
||||
# Shared SeismoDb instance. Path can be overridden by --db-path at startup,
|
||||
# or defaults to bridges/captures/seismo_relay.db relative to the repo root.
|
||||
@@ -385,9 +400,20 @@ def _via_device_access(fn) -> dict:
|
||||
def _change_response(fn) -> JSONResponse:
|
||||
"""Run a start/stop; the ChangeResult is the body, its outcome picks the status.
|
||||
|
||||
DeviceError mapping is _via_device_access's -- not repeated here.
|
||||
DeviceError mapping is _via_device_access's -- not repeated here. A change
|
||||
that went out, or may have (ChangeUnconfirmed), keeps that status and message
|
||||
and adds `sent` ("acknowledged" / "unknown") and `audit_id`, so a client can
|
||||
tell it from a failure that sent nothing without matching the wording
|
||||
(bench finding #10, 2026-11-02).
|
||||
"""
|
||||
body = _via_device_access(fn)
|
||||
try:
|
||||
body = _via_device_access(fn)
|
||||
except HTTPException as exc:
|
||||
cause = exc.__cause__
|
||||
if not isinstance(cause, ChangeUnconfirmed):
|
||||
raise
|
||||
return JSONResponse(status_code=exc.status_code,
|
||||
content={"detail": exc.detail, "sent": cause.sent, "audit_id": cause.audit_id})
|
||||
# An allow-list: only a dry run, a skip, or a change read back as made is a 200.
|
||||
ok = (body["outcome"] in ("dry_run", "skipped")
|
||||
or (body["outcome"] == "sent" and body["verified"] == "ok"))
|
||||
@@ -399,6 +425,8 @@ _SERIAL_AWARE_PATHS = frozenset({
|
||||
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
|
||||
"/device/events", "/device/events/download",
|
||||
"/device/monitor/start", "/device/monitor/stop",
|
||||
"/device/call_home/state", "/device/call_home/enable", "/device/call_home/disable",
|
||||
"/device/settings/change",
|
||||
})
|
||||
|
||||
|
||||
@@ -1085,145 +1113,61 @@ def device_event_blastware_file(
|
||||
|
||||
# ── Write endpoints ───────────────────────────────────────────────────────────
|
||||
|
||||
class DeviceConfigBody(BaseModel):
|
||||
"""
|
||||
Request body for POST /device/config.
|
||||
|
||||
All fields are optional — only supplied (non-null) fields are written to
|
||||
the device. All other config bytes are round-tripped verbatim.
|
||||
|
||||
Recording parameters
|
||||
--------------------
|
||||
recording_mode : Recording mode enum. Values: 0=Single Shot, 1=Continuous, 3=Histogram, 4=Histogram+Continuous.
|
||||
sample_rate : Samples per second. Valid values: 1024, 2048, 4096.
|
||||
record_time : Record duration in seconds (e.g. 1.0, 2.0, 3.0).
|
||||
|
||||
Trigger / alarm thresholds and range (geo channels)
|
||||
----------------------------------------------------
|
||||
trigger_level_geo : Trigger threshold in in/s (e.g. 0.5).
|
||||
alarm_level_geo : Alarm threshold in in/s (e.g. 1.0).
|
||||
geo_range : Geophone range/sensitivity. 0=Normal 10.000 in/s, 1=Sensitive 1.250 in/s.
|
||||
Project / operator strings (max 41 ASCII characters each)
|
||||
----------------------------
|
||||
project : Project description.
|
||||
client_name : Client / company name.
|
||||
operator : Operator / technician name.
|
||||
seis_loc : Sensor location description.
|
||||
notes : Extended notes.
|
||||
"""
|
||||
# Recording parameters
|
||||
recording_mode: Optional[int] = None
|
||||
sample_rate: Optional[int] = None
|
||||
record_time: Optional[float] = None
|
||||
histogram_interval_sec: Optional[int] = None # seconds: 2, 5, 15, 60, 300, 900 (mode-gated)
|
||||
# Threshold parameters / geo range
|
||||
trigger_level_geo: Optional[float] = None
|
||||
alarm_level_geo: Optional[float] = None
|
||||
geo_range: Optional[int] = None # 0=Normal 10.000 in/s, 1=Sensitive 1.250 in/s
|
||||
# Project / operator strings
|
||||
project: Optional[str] = None
|
||||
client_name: Optional[str] = None
|
||||
operator: Optional[str] = None
|
||||
seis_loc: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
_CONFIG_RETIRED = ("retired: change a unit's settings by serial with POST /device/settings/change "
|
||||
"(audited, previewed, read back)")
|
||||
|
||||
|
||||
@app.post("/device/config")
|
||||
def device_config(
|
||||
body: DeviceConfigBody,
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: int = Query(38400, description="Serial baud rate"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
|
||||
) -> dict:
|
||||
"""
|
||||
Read the current device config, apply any supplied changes to the compliance
|
||||
block, and write the full config back.
|
||||
|
||||
Only non-null fields in the JSON body are modified. All other config bytes
|
||||
are round-tripped verbatim from the device.
|
||||
|
||||
Supply either *port* (serial) or *host* (TCP/modem).
|
||||
|
||||
Example body (all fields optional — include only what you want to change):
|
||||
{
|
||||
"recording_mode": 1,
|
||||
"sample_rate": 1024,
|
||||
"record_time": 3.0,
|
||||
"trigger_level_geo": 0.5,
|
||||
"alarm_level_geo": 1.0,
|
||||
"project": "Bridge Inspection 2026",
|
||||
"client_name": "City of Portland",
|
||||
"operator": "Brian Harrison",
|
||||
"seis_loc": "South Abutment",
|
||||
"notes": "Pre-blast baseline"
|
||||
}
|
||||
|
||||
Returns:
|
||||
{"status": "ok", "updated_fields": {...}} on success.
|
||||
|
||||
Raises:
|
||||
502 on protocol errors (timeout, bad ack, etc.).
|
||||
422 if neither port nor host is provided.
|
||||
"""
|
||||
changed = body.model_dump(exclude_none=True)
|
||||
conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud)
|
||||
log.info("POST /device/config port=%s host=%s fields=%s", port, host, list(changed.keys()))
|
||||
|
||||
try:
|
||||
def _do():
|
||||
with _build_client(port, baud, host, tcp_port) as client:
|
||||
info = client.connect()
|
||||
_require_series3(info.serial, serial)
|
||||
client.apply_config(
|
||||
recording_mode=body.recording_mode,
|
||||
sample_rate=body.sample_rate,
|
||||
record_time=body.record_time,
|
||||
histogram_interval_sec=body.histogram_interval_sec,
|
||||
trigger_level_geo=body.trigger_level_geo,
|
||||
alarm_level_geo=body.alarm_level_geo,
|
||||
geo_range=body.geo_range,
|
||||
project=body.project,
|
||||
client_name=body.client_name,
|
||||
operator=body.operator,
|
||||
seis_loc=body.seis_loc,
|
||||
notes=body.notes,
|
||||
)
|
||||
_run_with_retry(_do, is_tcp=_is_tcp(host))
|
||||
except HTTPException:
|
||||
raise
|
||||
except ProtocolError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Protocol error: {exc}") from exc
|
||||
except OSError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Connection error: {exc}") from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=f"Device error: {exc}") from exc
|
||||
|
||||
# Config was written to the device — the cached compliance config is now stale.
|
||||
conn_key = SFMCache.make_conn_key(host, tcp_port, port, baud)
|
||||
get_cache().mark_config_dirty(conn_key)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"updated_fields": changed,
|
||||
}
|
||||
def device_config() -> JSONResponse:
|
||||
"""Retired (phase 5, 2026-11-03). It wrote a MiniMate's settings through an
|
||||
encoder #46 found wrong, unaudited, with no read-back, retrying the whole
|
||||
write on a TCP error. Use POST /device/settings/change."""
|
||||
return JSONResponse(status_code=410, content={"detail": _CONFIG_RETIRED})
|
||||
|
||||
|
||||
# Keep the old endpoint alive under its old URL for anything already calling it
|
||||
@app.post("/device/config/project")
|
||||
def device_config_project(
|
||||
body: DeviceConfigBody,
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: int = Query(38400, description="Serial baud rate"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
|
||||
def device_config_project() -> JSONResponse:
|
||||
"""Retired with POST /device/config -- use POST /device/settings/change."""
|
||||
return JSONResponse(status_code=410, content={"detail": _CONFIG_RETIRED})
|
||||
|
||||
|
||||
class SettingsChangeBody(BaseModel):
|
||||
"""POST /device/settings/change. `changes` maps field -> new value, using
|
||||
the field names in GET /device/settings' `detail.editable`. `revision` is the
|
||||
one a dry run (the preview) returned; a live change without it is refused."""
|
||||
changes: Dict[str, Any]
|
||||
revision: Optional[str] = None
|
||||
|
||||
|
||||
@app.post("/device/settings/change")
|
||||
def device_settings_change(
|
||||
body: SettingsChangeBody,
|
||||
serial: str = Query(..., description=_SERIAL_DOC),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
|
||||
) -> dict:
|
||||
"""Deprecated alias for POST /device/config — use that instead."""
|
||||
return device_config(body=body, port=port, baud=baud, host=host, tcp_port=tcp_port, serial=serial)
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud rate"),
|
||||
dry_run: bool = Query(False, description="Preview: old -> new and a revision; send nothing"),
|
||||
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
|
||||
):
|
||||
"""Change a unit's settings by serial, both series (spec row 10, phase 5).
|
||||
|
||||
Preview first (`dry_run=true`): it reads the unit and returns, per field, the
|
||||
value it holds and the value it would get, any warnings, anything that blocks
|
||||
the change, and a `revision`. Then send the same body live with that
|
||||
revision: identity read first, refused if the unit is monitoring or its
|
||||
settings changed since the preview (409), sent once, never retried, read back.
|
||||
Statuses as /device/monitor/start; a change that went out but was not
|
||||
confirmed carries `sent` and `audit_id`."""
|
||||
resp = _change_response(lambda: _device_access().change_settings(
|
||||
_unit_address(port, baud, host, tcp_port), serial, changes=body.changes,
|
||||
revision=body.revision, dry_run=dry_run, caller=caller or "api"))
|
||||
if not dry_run:
|
||||
try: # a by-host read must not serve stale settings
|
||||
get_cache().mark_config_dirty(_live_cache.make_conn_key(host, tcp_port, port, baud))
|
||||
except Exception as exc: # noqa: BLE001 -- the change's answer stands
|
||||
log.warning("could not mark the cached config dirty: %s", exc)
|
||||
return resp
|
||||
|
||||
|
||||
# ── Monitoring endpoints ───────────────────────────────────────────────────────
|
||||
@@ -2029,6 +1973,64 @@ def device_monitor_stop(
|
||||
# ── Call home config endpoints ───────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.get("/device/call_home/state")
|
||||
def device_call_home_state(
|
||||
serial: str = Query(..., description=_SERIAL_DOC),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud rate"),
|
||||
) -> dict:
|
||||
"""The unit's call-home switch and dial string, by serial, both series (phase 4).
|
||||
|
||||
`enabled` is null when the enable byte is not a value ever measured;
|
||||
`detail` keeps `byte5` and the whole block as read."""
|
||||
return _via_device_access(lambda: _device_access().call_home_state(
|
||||
_unit_address(port, baud, host, tcp_port), serial))
|
||||
|
||||
|
||||
def _set_call_home(enabled: bool, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller):
|
||||
return _change_response(lambda: _device_access().set_call_home(
|
||||
_unit_address(port, baud, host, tcp_port), serial, enabled=enabled, dry_run=dry_run,
|
||||
even_if_already=even_if_already, caller=caller or "api"))
|
||||
|
||||
|
||||
@app.post("/device/call_home/enable")
|
||||
def device_call_home_enable(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud rate"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
serial: str = Query(..., description=_SERIAL_DOC),
|
||||
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
|
||||
even_if_already: bool = Query(False, description="Send even if call-home is already on"),
|
||||
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
|
||||
):
|
||||
"""Turn the unit's automatic call-home ON (spec row 9), by serial, both series.
|
||||
|
||||
The same audited change as /device/monitor/start: identity read first (a
|
||||
different unit is a 409, nothing sent), the 0x2C block read, one write that
|
||||
changes only the enable byte (0x7E + 0x7F), never retried, then read back.
|
||||
Statuses as /device/monitor/start; a change that went out but was not
|
||||
confirmed carries `sent` and `audit_id`."""
|
||||
return _set_call_home(True, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller)
|
||||
|
||||
|
||||
@app.post("/device/call_home/disable")
|
||||
def device_call_home_disable(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
baud: Optional[int] = Query(None, description="Serial baud rate"),
|
||||
host: Optional[str] = Query(None, description="TCP host — modem IP"),
|
||||
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
|
||||
serial: str = Query(..., description=_SERIAL_DOC),
|
||||
dry_run: bool = Query(False, description="Return the planned frames; send nothing"),
|
||||
even_if_already: bool = Query(False, description="Send even if call-home is already off"),
|
||||
caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"),
|
||||
):
|
||||
"""Turn the unit's automatic call-home OFF -- as /device/call_home/enable."""
|
||||
return _set_call_home(False, port, baud, host, tcp_port, serial, dry_run, even_if_already, caller)
|
||||
|
||||
|
||||
@app.get("/device/call_home")
|
||||
def device_call_home_get(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"),
|
||||
|
||||
+32
-2442
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,271 @@
|
||||
/* <device-routing> */
|
||||
// Every rule that decides where a /device/ request goes, or whether a
|
||||
// series-specific control is live. Pure functions -- no DOM, no fetch -- so
|
||||
// tests/test_webapp_device_routing.py runs them in Node (phase 1c, 2026-10-29).
|
||||
// A control follows the unit's own /device/info answer, never a typed serial
|
||||
// alone: 0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate.
|
||||
|
||||
const SERIES_BY_PREFIX = [['UM', 4], ['BE', 3], ['BA', 3]]; // sfm/device_access/series.py
|
||||
|
||||
function normSerial(serial) { return String(serial || '').trim().toUpperCase(); }
|
||||
|
||||
function seriesFromSerial(serial) {
|
||||
const s = normSerial(serial);
|
||||
for (const [prefix, series] of SERIES_BY_PREFIX) {
|
||||
if (s.startsWith(prefix) && s.length > prefix.length) return series;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function unitQuery(unit) {
|
||||
const parts = [];
|
||||
const s = normSerial(unit.serial);
|
||||
if (s) parts.push(`serial=${encodeURIComponent(s)}`);
|
||||
parts.push(`host=${encodeURIComponent(unit.host || '')}`);
|
||||
parts.push(`tcp_port=${encodeURIComponent(unit.tcpPort)}`);
|
||||
return parts.join('&');
|
||||
}
|
||||
|
||||
// action -> [method, path, needs a serial (no legacy equivalent)]
|
||||
const DEVICE_ROUTES = {
|
||||
info: ['GET', '/device/info', false],
|
||||
status: ['GET', '/device/monitor/status', false],
|
||||
settings: ['GET', '/device/settings', true],
|
||||
events: ['GET', '/device/events', false],
|
||||
download: ['POST', '/device/events/download', true],
|
||||
start: ['POST', '/device/monitor/start', false],
|
||||
stop: ['POST', '/device/monitor/stop', false],
|
||||
hangup: ['POST', '/device/hangup', true],
|
||||
storage_range: ['GET', '/device/events/storage_range', false],
|
||||
index: ['GET', '/device/events/index', false],
|
||||
erase: ['POST', '/device/events/erase', false],
|
||||
rescue: ['POST', '/device/rescue', false],
|
||||
blind_stop: ['POST', '/device/stop_monitoring_blind', false],
|
||||
slow_drip: ['POST', '/device/stop_monitoring_slow_drip', false],
|
||||
call_home_read: ['GET', '/device/call_home', false],
|
||||
call_home_write: ['POST', '/device/call_home', false],
|
||||
call_home_state: ['GET', '/device/call_home/state', true],
|
||||
call_home_on: ['POST', '/device/call_home/enable', true],
|
||||
call_home_off: ['POST', '/device/call_home/disable', true],
|
||||
settings_change: ['POST', '/device/settings/change', true],
|
||||
event_waveform: ['GET', '/device/event/{index}/waveform', false],
|
||||
event_file: ['GET', '/device/event/{index}/blastware_file', false],
|
||||
};
|
||||
|
||||
function deviceUrl(action, unit, params = {}) {
|
||||
const route = DEVICE_ROUTES[action];
|
||||
if (!route) throw new Error(`unknown device action: ${action}`);
|
||||
const [method, template, needsSerial] = route;
|
||||
if (needsSerial && !normSerial(unit.serial)) return null;
|
||||
const rest = { ...params };
|
||||
let path = template;
|
||||
if (path.includes('{index}')) { // the legacy per-event routes
|
||||
if (rest.index === undefined) throw new Error(`${action} needs params.index`);
|
||||
path = path.replace('{index}', encodeURIComponent(rest.index));
|
||||
delete rest.index;
|
||||
}
|
||||
// Hang-up releases whatever line is held at the address: no serial.
|
||||
let query = action === 'hangup' ? unitQuery({ ...unit, serial: '' }) : unitQuery(unit);
|
||||
for (const [k, v] of Object.entries(rest)) query += `&${k}=${encodeURIComponent(v)}`;
|
||||
return { method, path: `${path}?${query}` };
|
||||
}
|
||||
|
||||
function confirmedSeries(unit) {
|
||||
const c = unit.confirmed;
|
||||
if (!c) return null;
|
||||
const typed = normSerial(unit.serial);
|
||||
if (!typed) return c.series; // a legacy identify, no serial typed
|
||||
return typed === normSerial(c.serial) ? c.series : null;
|
||||
}
|
||||
|
||||
function controlsFor(unit) {
|
||||
const series = confirmedSeries(unit);
|
||||
const serialMode = Boolean(normSerial(unit.serial));
|
||||
return {
|
||||
startStop: serialMode && (series === 3 || series === 4),
|
||||
hangup: series === 4,
|
||||
diagnostics: series === 3,
|
||||
// by host, the legacy read is Series 3's; by serial, both series (phase 4)
|
||||
callHomeRead: series === 3 || (serialMode && series === 4),
|
||||
callHomeChange: serialMode && (series === 3 || series === 4),
|
||||
configWrite: serialMode && (series === 3 || series === 4),
|
||||
callHomeWrite: false,
|
||||
reasons: { configWrite: 'By serial only: Preview, then Send (audited).',
|
||||
callHomeWrite: 'By serial: use Call-home On / Off (audited). Other call-home fields wait for the THOR round.' },
|
||||
};
|
||||
}
|
||||
|
||||
function changeSummary(body) {
|
||||
const id8 = String(body.audit_id || '').slice(0, 8);
|
||||
if (body.outcome === 'dry_run') {
|
||||
const subs = ((body.plan || {}).steps || []).map(s => s.sub).join(', ');
|
||||
return `${body.action}: dry run — would send ${subs}`;
|
||||
}
|
||||
if (body.action === 'change settings') { // phase 5: the state is a read-back verdict
|
||||
if (body.outcome === 'skipped') return 'change settings: the unit already holds these — nothing sent';
|
||||
if (body.outcome === 'sent' && body.verified === 'ok') {
|
||||
return `change settings: confirmed — the unit holds what was sent (audit ${id8})`;
|
||||
}
|
||||
if (body.verified === 'mismatch') {
|
||||
return `change settings: sent, but the unit reads ${body.state_after} — see what it holds (audit ${id8})`;
|
||||
}
|
||||
}
|
||||
if (body.outcome === 'skipped') return `${body.action}: already ${body.state_before} — nothing sent`;
|
||||
if (body.outcome === 'sent' && body.verified === 'ok') {
|
||||
return `${body.action}: confirmed — ${body.state_before} → ${body.state_after} (audit ${id8})`;
|
||||
}
|
||||
return `${body.action}: ${body.outcome}, ${body.verified} (audit ${id8})`;
|
||||
}
|
||||
|
||||
// What a chip and the peaks bar show for an event, from either shape: the
|
||||
// shared EventRef (serial mode) or the legacy event (host/port mode).
|
||||
function eventView(ev) {
|
||||
const label = typeof ev.timestamp === 'string' ? ev.timestamp.replace('T', ' ')
|
||||
: (ev.timestamp && ev.timestamp.display) || `Event ${ev.index}`;
|
||||
let peaks = null;
|
||||
if (ev.peaks_ips || ev.peak_vector_sum_ips != null) {
|
||||
const p = ev.peaks_ips || {};
|
||||
peaks = { tran: p.tran ?? null, vert: p.vert ?? null, long: p.long ?? null,
|
||||
pvs: ev.peak_vector_sum_ips ?? null, micPsi: null };
|
||||
} else if (ev.peak_values) {
|
||||
const pv = ev.peak_values;
|
||||
peaks = { tran: pv.tran_in_s ?? null, vert: pv.vert_in_s ?? null, long: pv.long_in_s ?? null,
|
||||
pvs: pv.peak_vector_sum ?? null, micPsi: pv.micl_psi ?? null };
|
||||
}
|
||||
return { label, title: ev.record_type || '', peaks };
|
||||
}
|
||||
|
||||
// What the Config tab's serial-mode Read shows for a UnitSettings reply.
|
||||
function settingsRows(st) {
|
||||
const dash = v => (v == null || v === '' ? '—' : v);
|
||||
const hi = st.histogram_interval_s;
|
||||
const rows = [
|
||||
['Setup Name', dash(st.setup_name)],
|
||||
['Record Mode', dash(st.record_mode)],
|
||||
['Sample Rate', st.sample_rate != null ? `${st.sample_rate} sps` : '—'],
|
||||
['Record Time', st.record_time_s != null ? `${st.record_time_s.toFixed(2)} s` : '—'],
|
||||
['Histogram Interval', hi == null ? '—' : hi < 60 ? `${hi} s` : `${hi / 60} min`],
|
||||
['Geo Trigger', st.geo_trigger_ips != null ? `${st.geo_trigger_ips.toFixed(4)} in/s` : '—'],
|
||||
];
|
||||
const notes = Object.entries(st.notes || {});
|
||||
if (!notes.length) rows.push(['Notes', '—']);
|
||||
for (const [k, v] of notes) rows.push([`Note: ${k}`, dash(v)]);
|
||||
return rows;
|
||||
}
|
||||
|
||||
// The legacy per-index routes (Load / Save / Download, prev/next, the arrow
|
||||
// keys) address events by position on the MiniMate path: live only for a list
|
||||
// loaded without a serial that has events.
|
||||
function perIndexLive({ bySerial, count }) { return !bySerial && count > 0; }
|
||||
|
||||
// A unit's own string (setup name, project, an error naming a serial) placed
|
||||
// into markup must stay text.
|
||||
function escapeHtml(v) {
|
||||
return String(v ?? '').replace(/[&<>"']/g,
|
||||
c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
}
|
||||
|
||||
function downloadSummary(body) {
|
||||
if (body.inserted === false) return `already stored — ${body.stored_filename}`;
|
||||
return `stored ${body.stored_filename}, ${body.filesize} bytes, check: ${(body.detail || {}).check}`;
|
||||
}
|
||||
|
||||
// A Micromate's version string lives in 0x01, undecoded; which firmware line it
|
||||
// runs comes free with every reply (bench finding #12).
|
||||
const FIRMWARE_LINES = { thor: 'Thor line (version not read)', blastware: 'Blastware line (version not read)' };
|
||||
function firmwareLabel(info) {
|
||||
const i = info || {};
|
||||
return i.firmware_version || i.firmware || FIRMWARE_LINES[(i.detail || {}).firmware_line] || '—';
|
||||
}
|
||||
|
||||
// A failed device request's message. A 504 is a unit that took the connection
|
||||
// but never answered: while THOR polls a Micromate, SFM's connection is accepted
|
||||
// and gets 0 bytes (measured 2026-10-29, bench finding #16). The hint is left
|
||||
// off once a change was sent -- its own message says what happened.
|
||||
const NO_REPLY_HINT = 'the connection opened, so the modem is reachable — another program (THOR or '
|
||||
+ "Blastware) may be holding this unit's line, or the unit is busy (e.g. its sensor check)";
|
||||
function errorDetail(body, statusText) {
|
||||
const b = body || {}, d = b.detail;
|
||||
return b.outcome ? changeSummary(b) : typeof d === 'string' ? d : d ? (d.message || JSON.stringify(d)) : statusText;
|
||||
}
|
||||
function deviceErrorText(status, body, unit, statusText) {
|
||||
const text = errorDetail(body, statusText);
|
||||
return status === 504 && !(body || {}).sent && unit && unit.host ? `${text} — ${NO_REPLY_HINT}` : text;
|
||||
}
|
||||
|
||||
// A change that went out (or may have) is not "failed": its body carries `sent`
|
||||
// (ChangeUnconfirmed, bench finding #10), and its message says what the unit
|
||||
// did and names the audit record. `label` is the whole name: "Start monitoring",
|
||||
// "Enable call-home".
|
||||
function changeErrorText(label, status, body, unit, statusText) {
|
||||
if ((body || {}).sent) return `${label} not confirmed: ${errorDetail(body, statusText)}`;
|
||||
return `${label} failed: ${deviceErrorText(status, body, unit, statusText)}`;
|
||||
}
|
||||
|
||||
// By serial, settings are read-only until phase 5: no empty legacy edit form or
|
||||
// legacy tables, and the settings box shows from the start (#6, #12).
|
||||
function serialPanes(bySerial, settingsRead) {
|
||||
return { configForm: !bySerial, settingsBox: bySerial, settingsPlaceholder: bySerial && !settingsRead,
|
||||
legacyDeviceTables: !bySerial, callHomeForm: !bySerial, callHomeBox: bySerial };
|
||||
}
|
||||
|
||||
// A unit's call-home switch, read by serial (phase 4). `enabled` null is an
|
||||
// enable byte never measured -- shown with the byte, never as On or Off.
|
||||
function callHomeRows(state) {
|
||||
const s = state || {};
|
||||
const d = s.detail || {};
|
||||
const sw = s.enabled === true ? 'On' : s.enabled === false ? 'Off'
|
||||
: d.reason || `Unknown (byte 5 = ${d.byte5 ?? '?'})`;
|
||||
return [['Call-home', sw], ['Dial string', s.dial_string || '—'], ['Series', s.series]];
|
||||
}
|
||||
// ── The Config tab's edit form, by serial (phase 5) ──────────────────────────
|
||||
|
||||
// The fields the server says this unit can change, in its order, with their
|
||||
// limits (UnitSettings.detail.editable).
|
||||
function settingsFormFields(st) {
|
||||
return (((st || {}).detail || {}).editable || []).map(f => ({ ...f }));
|
||||
}
|
||||
|
||||
// Only what the operator changed, typed as the server expects. Numbers compare
|
||||
// as numbers (0.30 is 0.3); a number that does not parse is left out (the
|
||||
// preview shows exactly what would change); read-only fields never count.
|
||||
function settingsChanges(fields, edited) {
|
||||
const out = {};
|
||||
const e = edited || {};
|
||||
for (const f of fields || []) {
|
||||
if (f.readonly || !(f.field in e)) continue;
|
||||
let v = e[f.field];
|
||||
if (f.kind === 'number' || (f.kind === 'choice' && typeof f.value === 'number')) {
|
||||
if (v === '' || v == null) continue;
|
||||
v = Number(v);
|
||||
if (!Number.isFinite(v) || v === Number(f.value)) continue;
|
||||
} else if (f.kind === 'bool') {
|
||||
v = Boolean(v);
|
||||
if (v === Boolean(f.value)) continue;
|
||||
} else {
|
||||
v = String(v);
|
||||
if (v === String(f.value == null ? '' : f.value)) continue;
|
||||
}
|
||||
out[f.field] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const _dash = v => (v == null || v === '' ? '—' : v);
|
||||
|
||||
// A preview (dry run): one row per field, [label, the unit holds, it would get].
|
||||
function settingsPreviewRows(body) {
|
||||
return Object.values(((body || {}).plan || {}).fields || {}).map(r => [r.label, _dash(r.old), _dash(r.new)]);
|
||||
}
|
||||
|
||||
// Why a preview would not be sent ('' when nothing blocks it).
|
||||
function settingsBlockedText(body) {
|
||||
return (((body || {}).plan || {}).blocked || []).join('; ');
|
||||
}
|
||||
|
||||
// After a send: [label, the unit held, SFM sent, the unit now holds].
|
||||
function settingsResultRows(body) {
|
||||
const fields = ((((body || {}).detail || {}).snapshot || {}).fields) || {};
|
||||
return Object.values(fields).map(r => [r.label, _dash(r.old), _dash(r.new), _dash(r.now)]);
|
||||
}
|
||||
/* </device-routing> */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -345,14 +345,15 @@ class WaveformStore:
|
||||
exc,
|
||||
)
|
||||
|
||||
# If we have a report, overlay its device-authoritative fields
|
||||
# (peaks, project, sample_rate, record_time) onto the Event
|
||||
# BEFORE handing it to db.insert_events(). Without this overlay
|
||||
# the DB row gets `peak_values` from _peaks_from_samples(), which
|
||||
# runs the still-undecoded waveform codec on the BW body and
|
||||
# produces ±10 in/s saturation values on every channel for every
|
||||
# event. The sidecar JSON had the correct values via
|
||||
# event_to_sidecar_dict(bw_report=...) but the DB columns didn't.
|
||||
# If we have a report, overlay its fields (peaks, project,
|
||||
# sample_rate, record_time) onto the Event BEFORE handing it to
|
||||
# db.insert_events(). The file decode reads these itself now (the
|
||||
# decode checker compares it with Blastware's XML reports, DL2's
|
||||
# 70,042 events); the overlay stays because production keeps a
|
||||
# paired Blastware report as the record until the file-only decode
|
||||
# has no blanks. The sidecar's `bw_report` block keeps the report's
|
||||
# own values either way. (The old reason -- an undecoded codec
|
||||
# giving ±10 in/s -- has not held since the 2026-08 codec fixes.)
|
||||
if bw_report is not None:
|
||||
try:
|
||||
event_file_io.apply_report_to_event(ev, bw_report)
|
||||
|
||||
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from micromate.models import MicromateDeviceInfo, MicromateEventRef, MicromateState
|
||||
@@ -16,6 +17,76 @@ from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStat
|
||||
|
||||
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
|
||||
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
|
||||
PUSH_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-writes" / "setup-push-overwrite-test1.json"
|
||||
|
||||
|
||||
def s4_push_reads() -> dict:
|
||||
"""UM12947's reads (content, by SUB) just before THOR's setup push: 0x08 prefs,
|
||||
0x2E trigger, 0x1A setup, 0x41 active name."""
|
||||
import json
|
||||
ex = json.loads(PUSH_FIXTURE.read_text())["exchanges"]
|
||||
start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA)
|
||||
return {e["sub"]: bytes.fromhex(e["response_data"])[11:] for e in ex[:start]}
|
||||
|
||||
|
||||
_S3_BLOCKS = None
|
||||
|
||||
|
||||
def s3_settings_blocks() -> dict:
|
||||
"""BE9441's four settings blocks on 2026-10-26, as SFM's reads return them:
|
||||
the 1A read Blastware took right after its second write (assembled, 2,090 B),
|
||||
and the event index / trigger / waveform blocks that write sent back (each a
|
||||
write is the read plus two bytes)."""
|
||||
global _S3_BLOCKS
|
||||
if _S3_BLOCKS is None:
|
||||
from minimateplus.framing import S3FrameParser
|
||||
from minimateplus.protocol import assemble_compliance_content
|
||||
from test_minimate_write_frames import WRITES, _payload
|
||||
fix = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
|
||||
reads, cur = [], None
|
||||
for f in S3FrameParser().feed((fix / "unit_replies.bin").read_bytes()):
|
||||
if f.sub != 0xE5:
|
||||
continue
|
||||
if len(f.data) == 11:
|
||||
cur = []
|
||||
reads.append(cur)
|
||||
else:
|
||||
cur.append(bytes(f.data))
|
||||
sent = {_payload(f)[2]: _payload(f)[16:] for f in WRITES[13:26]}
|
||||
_S3_BLOCKS = {"event_index": sent[0x68][:-2], "compliance": assemble_compliance_content(reads[2]),
|
||||
"trigger": sent[0x82][:-2], "waveform": sent[0x69][:-2]}
|
||||
return dict(_S3_BLOCKS)
|
||||
|
||||
|
||||
def s3_device_info_answer(serial: bytes = b"BE9441") -> bytes:
|
||||
"""What a MONITORING MiniMate returns for a 1A read, assembled: its device-info
|
||||
block (BE9441 10-26: reads 3-7 start 0e 'BE9441'), 2,090 bytes."""
|
||||
return (b"\x0e" + serial).ljust(2090, b"\x00")
|
||||
|
||||
|
||||
def schedule_record(time_slot: int, action: int, setup: str = "") -> bytes:
|
||||
"""One 260-byte schedule.dat record (micromate.schedule's layout)."""
|
||||
rec = bytearray(260)
|
||||
rec[4], rec[5], rec[6], rec[7] = time_slot, 3, action, len(setup)
|
||||
rec[8:8 + len(setup)] = setup.encode("ascii")
|
||||
return bytes(rec)
|
||||
THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
|
||||
|
||||
|
||||
def s3_call_home_raw(byte5: int = 0x01) -> bytes:
|
||||
"""A MiniMate's 0x2C reply payload as S3FrameParser returns it (125 B, the
|
||||
num_retries 3 kept as 10 03), laid out as the 4-20-26 captures measured
|
||||
(BE11529): header 00 7C DC, [5] the enable, [6:46] the dial string."""
|
||||
raw = b"\x00\x7c\xdc\x00\x00" + bytes([byte5]) + b"RADIO RING".ljust(40, b"\x00")
|
||||
raw += bytes(117 - len(raw)) + b"\x10\x03"
|
||||
return raw + bytes(125 - len(raw))
|
||||
|
||||
|
||||
def um12947_call_home(enabled: bool = True) -> bytes:
|
||||
"""UM12947's own 126-byte call-home content, as THOR read it (0x05 on, 0x04 off)."""
|
||||
ex = json.loads((THOR_WRITES / "call-home-enable-disable.json").read_text())["exchanges"]
|
||||
reads = [bytes.fromhex(e["response_data"])[11:] for e in ex if e["sub"] == 0x2C]
|
||||
return next(r for r in reads if r[5] == (0x05 if enabled else 0x04))
|
||||
|
||||
|
||||
from minimateplus.protocol import TimeoutError as mmp_TimeoutError # noqa: E402
|
||||
@@ -79,13 +150,18 @@ def default_s3_events():
|
||||
class FakeMiniMateClient(_Base):
|
||||
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
|
||||
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None,
|
||||
bare_requests_ignored=False, **kw):
|
||||
bare_requests_ignored=False, call_home_raw=None, settings_blocks=None,
|
||||
monitoring_settings=False, **kw):
|
||||
super().__init__(**kw)
|
||||
self.serial = serial
|
||||
self.settings_blocks = s3_settings_blocks() if settings_blocks is None else dict(settings_blocks)
|
||||
self.monitoring_settings = monitoring_settings
|
||||
self.pushed = None
|
||||
# As a monitoring MiniMate (measured 2026-04-08): on a fresh connection a
|
||||
# read before SESSION_RESET + POLL goes unanswered. Off unless a test asks.
|
||||
self.bare_requests_ignored = bare_requests_ignored
|
||||
self._woken = False
|
||||
self.call_home_raw = s3_call_home_raw() if call_home_raw is None else call_home_raw
|
||||
# read_serial()'s answer (connect() keeps answering `serial`), and errors
|
||||
# raised by wake() once a write has gone out -- the read-back's wakes.
|
||||
self.serial_reported = serial if serial_reported is None else serial_reported
|
||||
@@ -138,6 +214,31 @@ class FakeMiniMateClient(_Base):
|
||||
self._bare_read("read_serial")
|
||||
return self.serial_reported
|
||||
|
||||
def read_call_home_raw(self) -> bytes:
|
||||
self._bare_read("read_call_home_raw")
|
||||
return self.call_home_raw
|
||||
|
||||
def write_call_home_image(self, image: bytes) -> None:
|
||||
self._write("call_home")
|
||||
self.call_home_raw = bytes(image) # read back as the unit would store it
|
||||
|
||||
def read_compliance_content(self) -> bytes:
|
||||
self._bare_read("read_compliance_content")
|
||||
return s3_device_info_answer() if self.monitoring_settings else self.settings_blocks["compliance"]
|
||||
|
||||
def read_settings_blocks(self) -> dict:
|
||||
self._bare_read("read_settings_blocks")
|
||||
blocks = dict(self.settings_blocks)
|
||||
if self.monitoring_settings:
|
||||
blocks["compliance"] = s3_device_info_answer()
|
||||
return blocks
|
||||
|
||||
def push_config_raw(self, event_index, compliance, trigger, waveform, *, escaped=False) -> None:
|
||||
self.pushed_escaped = escaped
|
||||
self.pushed = (bytes(event_index), bytes(compliance), bytes(trigger), bytes(waveform))
|
||||
self._write("push_config_raw")
|
||||
self.settings_blocks["compliance"] = bytes(compliance)[:2090] # read back as the unit stores it
|
||||
|
||||
def get_monitor_status(self) -> MonitorStatus:
|
||||
self._bare_read("get_monitor_status")
|
||||
state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0]
|
||||
@@ -237,15 +338,39 @@ class _FakeProtocol:
|
||||
self._owner.executed.append(plan)
|
||||
if self._owner.execute_error is not None:
|
||||
raise self._owner.execute_error
|
||||
for st in plan.steps:
|
||||
if st.sub == 0x7E: # the unit stores the block and moves [118:120] itself
|
||||
old = self._owner.call_home
|
||||
self._owner.call_home = bytes(st.data[:118]) + bytes(~b & 0xFF for b in old[118:120]) \
|
||||
+ bytes(st.data[120:])
|
||||
if st.sub == 0x71: # the unit stores the setup and computes its own CRC
|
||||
from micromate.setup_block import with_crc
|
||||
old = self._owner.setup
|
||||
self._owner.setup = with_crc(old[:3] + bytes(st.data[3:2090]) + old[2090:2092])
|
||||
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
|
||||
|
||||
def read_call_home_config(self):
|
||||
self._owner._step("read_call_home_config")
|
||||
return bytes(11) + self._owner.call_home
|
||||
|
||||
|
||||
class FakeMicromateClient(_Base):
|
||||
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
|
||||
unsolicited=b"", event_refs=None, run_states=None,
|
||||
serial_reported=None, execute_error=None, **kw):
|
||||
serial_reported=None, execute_error=None, call_home=None, setup=None,
|
||||
prefs=None, trigger=None, active_name=None, schedule_body=None,
|
||||
schedule_error=None, **kw):
|
||||
super().__init__(**kw)
|
||||
self.unit_serial = serial # not `serial`: that is the client's method
|
||||
self.call_home = um12947_call_home() if call_home is None else call_home
|
||||
push = s4_push_reads()
|
||||
self.setup = SETUP_FIXTURE.read_bytes()[11:] if setup is None else setup
|
||||
self.prefs = push[0x08] if prefs is None else prefs
|
||||
self.trigger = push[0x2E] if trigger is None else trigger
|
||||
self.active_name = (push[0x41].split(b"\x00")[0].decode("ascii")
|
||||
if active_name is None else active_name)
|
||||
self.schedule_body = bytes(524) if schedule_body is None else schedule_body
|
||||
self.schedule_error = schedule_error
|
||||
self.run_states = list(run_states) if run_states else [0x00]
|
||||
self.serial_reported = serial if serial_reported is None else serial_reported
|
||||
self.execute_error = execute_error
|
||||
@@ -272,6 +397,10 @@ class FakeMicromateClient(_Base):
|
||||
self._step("serial")
|
||||
return self.serial_reported if refresh else self.unit_serial
|
||||
|
||||
def get_call_home_content(self) -> bytes:
|
||||
self._step("get_call_home_content")
|
||||
return self.call_home
|
||||
|
||||
def read_run_state(self):
|
||||
from micromate.models import MicromateRunState
|
||||
self._step("read_run_state")
|
||||
@@ -293,7 +422,29 @@ class FakeMicromateClient(_Base):
|
||||
|
||||
def get_setup(self):
|
||||
self._step("get_setup")
|
||||
return decode_setup(SETUP_FIXTURE.read_bytes()[11:])
|
||||
return decode_setup(self.setup)
|
||||
|
||||
def get_setup_content(self) -> bytes:
|
||||
self._step("get_setup_content")
|
||||
return self.setup
|
||||
|
||||
def get_prefs_content(self) -> bytes:
|
||||
self._step("get_prefs_content")
|
||||
return self.prefs
|
||||
|
||||
def get_trigger_content(self) -> bytes:
|
||||
self._step("get_trigger_content")
|
||||
return self.trigger
|
||||
|
||||
def get_active_setup_raw(self) -> str:
|
||||
self._step("get_active_setup_raw")
|
||||
return self.active_name
|
||||
|
||||
def read_schedule(self) -> bytes:
|
||||
self._step("read_schedule")
|
||||
if self.schedule_error is not None:
|
||||
raise self.schedule_error
|
||||
return self.schedule_body
|
||||
|
||||
def read_unsolicited(self) -> bytes:
|
||||
self._step("read_unsolicited")
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+548
@@ -0,0 +1,548 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18003</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T003LCYV.JD0H</FileName>
|
||||
<HistogramStartTime>18:04:25</HistogramStartTime>
|
||||
<HistogramStartDate>2025-12-05</HistogramStartDate>
|
||||
<HistogramStopTime>20:30:00</HistogramStopTime>
|
||||
<HistogramStopDate>2025-12-05</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>145.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>7.0 Volts</BatteryLevel>
|
||||
<Calibration>March 14, 2025 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>I-80-North Fork Bridges-I80 E. Abutment</Project>
|
||||
<Client>Fay Company</Client>
|
||||
<UserName>Terra-Mechanics, Inc - Harrison</UserName>
|
||||
<Seis.Loc>Area 2 - Loc 3 - I-80 - East Abutment</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.035</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>0.090</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.045</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>11</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>43</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>37</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>20:10:25</TranPeakTime>
|
||||
<TranPeakDate>2025-12-05</TranPeakDate>
|
||||
<VertPeakTime>19:09:25</VertPeakTime>
|
||||
<VertPeakDate>2025-12-05</VertPeakDate>
|
||||
<LongPeakTime>20:09:25</LongPeakTime>
|
||||
<LongPeakDate>2025-12-05</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>0.099</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>19:09:25</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2025-12-05</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>124.7</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>18:19:25</MicLTime>
|
||||
<MicLDate>2025-12-05</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>2.4</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.7 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.5</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.6 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.1</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.4 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.9</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>20.1 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>767 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Passed</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2025-12-05 18:04:24 - 2025-12-05 20:30:00 "Event Recorded Timer Stop"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2025-12-05 18:05:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>13</Cell><Cell>0.070</Cell><Cell>23</Cell><Cell>0.030</Cell><Cell>17</Cell><Cell>0.075</Cell><Cell>0.003</Cell><Cell>121.5</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 18:06:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>7.6</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>47</Cell><Cell>0.074</Cell><Cell>0.003</Cell><Cell>119.1</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:07:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>14</Cell><Cell>0.080</Cell><Cell>34</Cell><Cell>0.030</Cell><Cell>34</Cell><Cell>0.084</Cell><Cell>0.002</Cell><Cell>118.3</Cell><Cell>3.6</Cell></Row>
|
||||
<Time>2025-12-05 18:08:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>7.8</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>21</Cell><Cell>0.064</Cell><Cell>0.003</Cell><Cell>121.0</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 18:09:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.3</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.020</Cell><Cell>18</Cell><Cell>0.059</Cell><Cell>0.004</Cell><Cell>122.8</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 18:10:25</Time>
|
||||
<Row>
|
||||
<Cell>0.030</Cell><Cell>43</Cell><Cell>0.080</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>43</Cell><Cell>0.088</Cell><Cell>0.003</Cell><Cell>121.0</Cell><Cell>4.2</Cell></Row>
|
||||
<Time>2025-12-05 18:11:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.085</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>47</Cell><Cell>0.092</Cell><Cell>0.003</Cell><Cell>119.8</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 18:12:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.2</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>20</Cell><Cell>0.061</Cell><Cell>0.003</Cell><Cell>119.4</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:13:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.5</Cell><Cell>0.055</Cell><Cell>73</Cell><Cell>0.025</Cell><Cell>37</Cell><Cell>0.062</Cell><Cell>0.002</Cell><Cell>117.6</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:14:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>11</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>43</Cell><Cell>0.072</Cell><Cell>0.004</Cell><Cell>121.8</Cell><Cell>18</Cell></Row>
|
||||
<Time>2025-12-05 18:15:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.075</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.081</Cell><Cell>0.002</Cell><Cell>118.6</Cell><Cell>3.5</Cell></Row>
|
||||
<Time>2025-12-05 18:16:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.072</Cell><Cell>0.003</Cell><Cell>120.0</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:17:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>11</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.065</Cell><Cell>0.003</Cell><Cell>119.9</Cell><Cell>2.6</Cell></Row>
|
||||
<Time>2025-12-05 18:18:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>13</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.077</Cell><Cell>0.003</Cell><Cell>119.7</Cell><Cell>12</Cell></Row>
|
||||
<Time>2025-12-05 18:19:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>28</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>34</Cell><Cell>0.073</Cell><Cell>0.005</Cell><Cell>124.7</Cell><Cell>2.4</Cell></Row>
|
||||
<Time>2025-12-05 18:20:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.066</Cell><Cell>0.003</Cell><Cell>119.4</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 18:21:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>9.8</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>121.0</Cell><Cell>5.1</Cell></Row>
|
||||
<Time>2025-12-05 18:22:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.075</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.079</Cell><Cell>0.003</Cell><Cell>119.0</Cell><Cell>2.5</Cell></Row>
|
||||
<Time>2025-12-05 18:23:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>17</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.020</Cell><Cell>51</Cell><Cell>0.063</Cell><Cell>0.004</Cell><Cell>122.1</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 18:24:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>7.6</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.020</Cell><Cell>39</Cell><Cell>0.064</Cell><Cell>0.003</Cell><Cell>120.6</Cell><Cell>4.4</Cell></Row>
|
||||
<Time>2025-12-05 18:25:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>7.5</Cell><Cell>0.075</Cell><Cell>37</Cell><Cell>0.030</Cell><Cell>30</Cell><Cell>0.082</Cell><Cell>0.002</Cell><Cell>118.2</Cell><Cell>5.0</Cell></Row>
|
||||
<Time>2025-12-05 18:26:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>16</Cell><Cell>0.060</Cell><Cell>26</Cell><Cell>0.025</Cell><Cell>24</Cell><Cell>0.064</Cell><Cell>0.003</Cell><Cell>121.4</Cell><Cell>3.6</Cell></Row>
|
||||
<Time>2025-12-05 18:27:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>21</Cell><Cell>0.080</Cell><Cell>37</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.084</Cell><Cell>0.003</Cell><Cell>120.1</Cell><Cell>3.4</Cell></Row>
|
||||
<Time>2025-12-05 18:28:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.045</Cell><Cell>24</Cell><Cell>0.020</Cell><Cell>20</Cell><Cell>0.048</Cell><Cell>0.002</Cell><Cell>118.1</Cell><Cell>2.6</Cell></Row>
|
||||
<Time>2025-12-05 18:29:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.060</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>23</Cell><Cell>0.065</Cell><Cell>0.003</Cell><Cell>120.1</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 18:30:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.3</Cell><Cell>0.045</Cell><Cell>22</Cell><Cell>0.020</Cell><Cell>30</Cell><Cell>0.051</Cell><Cell>0.002</Cell><Cell>115.9</Cell><Cell>2.6</Cell></Row>
|
||||
<Time>2025-12-05 18:31:25</Time>
|
||||
<Row>
|
||||
<Cell>0.030</Cell><Cell>24</Cell><Cell>0.070</Cell><Cell>39</Cell><Cell>0.030</Cell><Cell>39</Cell><Cell>0.073</Cell><Cell>0.004</Cell><Cell>122.8</Cell><Cell>2.3</Cell></Row>
|
||||
<Time>2025-12-05 18:32:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.4</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>120.9</Cell><Cell>3.1</Cell></Row>
|
||||
<Time>2025-12-05 18:33:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>11</Cell><Cell>0.050</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>17</Cell><Cell>0.057</Cell><Cell>0.003</Cell><Cell>121.3</Cell><Cell>13</Cell></Row>
|
||||
<Time>2025-12-05 18:34:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>22</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>30</Cell><Cell>0.066</Cell><Cell>0.004</Cell><Cell>122.0</Cell><Cell>3.0</Cell></Row>
|
||||
<Time>2025-12-05 18:35:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.035</Cell><Cell>18</Cell><Cell>0.077</Cell><Cell>0.003</Cell><Cell>120.6</Cell><Cell>4.8</Cell></Row>
|
||||
<Time>2025-12-05 18:36:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.1</Cell><Cell>0.045</Cell><Cell>22</Cell><Cell>0.020</Cell><Cell>30</Cell><Cell>0.051</Cell><Cell>0.002</Cell><Cell>116.7</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:37:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>16</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>120.2</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:38:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>13</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>23</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>119.3</Cell><Cell>2.3</Cell></Row>
|
||||
<Time>2025-12-05 18:39:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.7</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.020</Cell><Cell>43</Cell><Cell>0.059</Cell><Cell>0.003</Cell><Cell>121.3</Cell><Cell>2.2</Cell></Row>
|
||||
<Time>2025-12-05 18:40:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>19</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>37</Cell><Cell>0.068</Cell><Cell>0.004</Cell><Cell>123.1</Cell><Cell>11</Cell></Row>
|
||||
<Time>2025-12-05 18:41:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>22</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.002</Cell><Cell>118.1</Cell><Cell>17</Cell></Row>
|
||||
<Time>2025-12-05 18:42:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>27</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.062</Cell><Cell>0.002</Cell><Cell>118.6</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:43:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.3</Cell><Cell>0.060</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.065</Cell><Cell>0.002</Cell><Cell>116.9</Cell><Cell>6.3</Cell></Row>
|
||||
<Time>2025-12-05 18:44:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.072</Cell><Cell>0.004</Cell><Cell>122.5</Cell><Cell>4.1</Cell></Row>
|
||||
<Time>2025-12-05 18:45:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>2.6</Cell><Cell>0.060</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.066</Cell><Cell>0.004</Cell><Cell>122.0</Cell><Cell>5.7</Cell></Row>
|
||||
<Time>2025-12-05 18:46:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.2</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>11</Cell><Cell>0.064</Cell><Cell>0.004</Cell><Cell>121.9</Cell><Cell>1.7</Cell></Row>
|
||||
<Time>2025-12-05 18:47:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>14</Cell><Cell>0.070</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.076</Cell><Cell>0.004</Cell><Cell>122.1</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 18:48:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>34</Cell><Cell>0.070</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>18</Cell><Cell>0.076</Cell><Cell>0.003</Cell><Cell>120.1</Cell><Cell>15</Cell></Row>
|
||||
<Time>2025-12-05 18:49:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.5</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>57</Cell><Cell>0.070</Cell><Cell>0.004</Cell><Cell>121.8</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 18:50:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>18</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>24</Cell><Cell>0.069</Cell><Cell>0.002</Cell><Cell>117.6</Cell><Cell>2.5</Cell></Row>
|
||||
<Time>2025-12-05 18:51:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>10</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>47</Cell><Cell>0.070</Cell><Cell>0.004</Cell><Cell>122.0</Cell><Cell>2.5</Cell></Row>
|
||||
<Time>2025-12-05 18:52:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>4.2</Cell><Cell>0.050</Cell><Cell>22</Cell><Cell>0.020</Cell><Cell>14</Cell><Cell>0.056</Cell><Cell>0.003</Cell><Cell>119.1</Cell><Cell>2.7</Cell></Row>
|
||||
<Time>2025-12-05 18:53:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>1.9</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.020</Cell><Cell>34</Cell><Cell>0.059</Cell><Cell>0.004</Cell><Cell>122.1</Cell><Cell>4.3</Cell></Row>
|
||||
<Time>2025-12-05 18:54:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell><1.0</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>47</Cell><Cell>0.070</Cell><Cell>0.002</Cell><Cell>117.2</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 18:55:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>17</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>121.1</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:56:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell><1.0</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>57</Cell><Cell>0.065</Cell><Cell>0.003</Cell><Cell>119.8</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 18:57:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>15</Cell><Cell>0.070</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.074</Cell><Cell>0.003</Cell><Cell>120.9</Cell><Cell>4.7</Cell></Row>
|
||||
<Time>2025-12-05 18:58:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.9</Cell><Cell>0.050</Cell><Cell>22</Cell><Cell>0.020</Cell><Cell>28</Cell><Cell>0.051</Cell><Cell>0.002</Cell><Cell>117.1</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 18:59:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.077</Cell><Cell>0.002</Cell><Cell>117.4</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 19:00:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>27</Cell><Cell>0.055</Cell><Cell>85</Cell><Cell>0.030</Cell><Cell>17</Cell><Cell>0.058</Cell><Cell>0.003</Cell><Cell>120.2</Cell><Cell>1.8</Cell></Row>
|
||||
<Time>2025-12-05 19:01:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>17</Cell><Cell>0.055</Cell><Cell>43</Cell><Cell>0.020</Cell><Cell>43</Cell><Cell>0.059</Cell><Cell>0.004</Cell><Cell>123.1</Cell><Cell>3.7</Cell></Row>
|
||||
<Time>2025-12-05 19:02:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell><1.0</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>120.4</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:03:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.6</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>119.6</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:04:25</Time>
|
||||
<Row>
|
||||
<Cell>0.030</Cell><Cell>17</Cell><Cell>0.085</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>57</Cell><Cell>0.092</Cell><Cell>0.004</Cell><Cell>122.8</Cell><Cell>2.2</Cell></Row>
|
||||
<Time>2025-12-05 19:05:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>24</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.062</Cell><Cell>0.002</Cell><Cell>117.8</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:06:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.050</Cell><Cell>23</Cell><Cell>0.025</Cell><Cell>26</Cell><Cell>0.058</Cell><Cell>0.002</Cell><Cell>116.4</Cell><Cell>51</Cell></Row>
|
||||
<Time>2025-12-05 19:07:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>14</Cell><Cell>0.055</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>26</Cell><Cell>0.059</Cell><Cell>0.003</Cell><Cell>119.0</Cell><Cell>2.2</Cell></Row>
|
||||
<Time>2025-12-05 19:08:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>11</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.035</Cell><Cell>30</Cell><Cell>0.078</Cell><Cell>0.002</Cell><Cell>117.2</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 19:09:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>15</Cell><Cell>0.090</Cell><Cell>43</Cell><Cell>0.040</Cell><Cell>47</Cell><Cell>0.099</Cell><Cell>0.003</Cell><Cell>120.2</Cell><Cell>4.7</Cell></Row>
|
||||
<Time>2025-12-05 19:10:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>17</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.072</Cell><Cell>0.003</Cell><Cell>119.6</Cell><Cell>3.6</Cell></Row>
|
||||
<Time>2025-12-05 19:11:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.6</Cell><Cell>0.060</Cell><Cell>57</Cell><Cell>0.030</Cell><Cell>28</Cell><Cell>0.062</Cell><Cell>0.003</Cell><Cell>119.8</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:12:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>32</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.035</Cell><Cell>27</Cell><Cell>0.074</Cell><Cell>0.003</Cell><Cell>120.2</Cell><Cell>4.0</Cell></Row>
|
||||
<Time>2025-12-05 19:13:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>16</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>24</Cell><Cell>0.069</Cell><Cell>0.003</Cell><Cell>119.6</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:14:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>16</Cell><Cell>0.040</Cell><Cell>24</Cell><Cell>0.020</Cell><Cell>22</Cell><Cell>0.047</Cell><Cell>0.002</Cell><Cell>117.4</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:15:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>19</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.070</Cell><Cell>0.002</Cell><Cell>116.7</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 19:16:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>16</Cell><Cell>0.070</Cell><Cell>39</Cell><Cell>0.035</Cell><Cell>51</Cell><Cell>0.080</Cell><Cell>0.004</Cell><Cell>121.9</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 19:17:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.080</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>27</Cell><Cell>0.087</Cell><Cell>0.003</Cell><Cell>119.7</Cell><Cell>2.7</Cell></Row>
|
||||
<Time>2025-12-05 19:18:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.076</Cell><Cell>0.003</Cell><Cell>119.4</Cell><Cell>6.7</Cell></Row>
|
||||
<Time>2025-12-05 19:19:25</Time>
|
||||
<Row>
|
||||
<Cell>0.030</Cell><Cell>20</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.072</Cell><Cell>0.003</Cell><Cell>121.6</Cell><Cell>4.7</Cell></Row>
|
||||
<Time>2025-12-05 19:20:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell><1.0</Cell><Cell>0.065</Cell><Cell>39</Cell><Cell>0.025</Cell><Cell>26</Cell><Cell>0.069</Cell><Cell>0.003</Cell><Cell>119.9</Cell><Cell>4.1</Cell></Row>
|
||||
<Time>2025-12-05 19:21:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>4.7</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>22</Cell><Cell>0.065</Cell><Cell>0.002</Cell><Cell>117.9</Cell><Cell>1.5</Cell></Row>
|
||||
<Time>2025-12-05 19:22:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>23</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>37</Cell><Cell>0.070</Cell><Cell>0.002</Cell><Cell>118.2</Cell><Cell>2.2</Cell></Row>
|
||||
<Time>2025-12-05 19:23:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>16</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.071</Cell><Cell>0.003</Cell><Cell>120.0</Cell><Cell>2.9</Cell></Row>
|
||||
<Time>2025-12-05 19:24:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>4.0</Cell><Cell>0.045</Cell><Cell>34</Cell><Cell>0.020</Cell><Cell>18</Cell><Cell>0.050</Cell><Cell>0.003</Cell><Cell>118.7</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:25:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>2.9</Cell><Cell>0.055</Cell><Cell>23</Cell><Cell>0.025</Cell><Cell>17</Cell><Cell>0.062</Cell><Cell>0.002</Cell><Cell>118.5</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:26:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>47</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>47</Cell><Cell>0.075</Cell><Cell>0.004</Cell><Cell>122.7</Cell><Cell>2.7</Cell></Row>
|
||||
<Time>2025-12-05 19:27:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>9.7</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>28</Cell><Cell>0.074</Cell><Cell>0.003</Cell><Cell>121.1</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 19:28:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>57</Cell><Cell>0.090</Cell><Cell>47</Cell><Cell>0.040</Cell><Cell>51</Cell><Cell>0.097</Cell><Cell>0.003</Cell><Cell>121.3</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 19:29:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>11</Cell><Cell>0.050</Cell><Cell>22</Cell><Cell>0.020</Cell><Cell>34</Cell><Cell>0.056</Cell><Cell>0.002</Cell><Cell>114.8</Cell><Cell>2.3</Cell></Row>
|
||||
<Time>2025-12-05 19:30:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>47</Cell><Cell>0.072</Cell><Cell>0.003</Cell><Cell>119.1</Cell><Cell>51</Cell></Row>
|
||||
<Time>2025-12-05 19:31:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.055</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.061</Cell><Cell>0.004</Cell><Cell>122.0</Cell><Cell>2.6</Cell></Row>
|
||||
<Time>2025-12-05 19:32:25</Time>
|
||||
<Row>
|
||||
<Cell>0.015</Cell><Cell><1.0</Cell><Cell>0.015</Cell><Cell>18</Cell><Cell>0.015</Cell><Cell>12</Cell><Cell>0.026</Cell><Cell>0.001</Cell><Cell>108.0</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:33:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>2.9</Cell><Cell>0.050</Cell><Cell>21</Cell><Cell>0.025</Cell><Cell>22</Cell><Cell>0.058</Cell><Cell>0.002</Cell><Cell>117.2</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:34:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>8.3</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>24</Cell><Cell>0.066</Cell><Cell>0.003</Cell><Cell>121.5</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 19:35:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.8</Cell><Cell>0.040</Cell><Cell>23</Cell><Cell>0.020</Cell><Cell>23</Cell><Cell>0.047</Cell><Cell>0.002</Cell><Cell>114.4</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:36:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>12</Cell><Cell>0.055</Cell><Cell>43</Cell><Cell>0.020</Cell><Cell>39</Cell><Cell>0.059</Cell><Cell>0.003</Cell><Cell>121.0</Cell><Cell>2.8</Cell></Row>
|
||||
<Time>2025-12-05 19:37:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.055</Cell><Cell>22</Cell><Cell>0.030</Cell><Cell>20</Cell><Cell>0.066</Cell><Cell>0.002</Cell><Cell>117.6</Cell><Cell>3.1</Cell></Row>
|
||||
<Time>2025-12-05 19:38:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>7.3</Cell><Cell>0.050</Cell><Cell>39</Cell><Cell>0.020</Cell><Cell>32</Cell><Cell>0.056</Cell><Cell>0.004</Cell><Cell>122.2</Cell><Cell>2.5</Cell></Row>
|
||||
<Time>2025-12-05 19:39:25</Time>
|
||||
<Row>
|
||||
<Cell>0.030</Cell><Cell>23</Cell><Cell>0.070</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>47</Cell><Cell>0.077</Cell><Cell>0.003</Cell><Cell>120.3</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:40:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>18</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>51</Cell><Cell>0.070</Cell><Cell>0.004</Cell><Cell>121.8</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 19:41:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>32</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>17</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>120.1</Cell><Cell>14</Cell></Row>
|
||||
<Time>2025-12-05 19:42:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>17</Cell><Cell>0.060</Cell><Cell>26</Cell><Cell>0.025</Cell><Cell>23</Cell><Cell>0.065</Cell><Cell>0.002</Cell><Cell>116.1</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:43:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.060</Cell><Cell>23</Cell><Cell>0.030</Cell><Cell>24</Cell><Cell>0.070</Cell><Cell>0.002</Cell><Cell>116.9</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:44:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.075</Cell><Cell>47</Cell><Cell>0.035</Cell><Cell>51</Cell><Cell>0.081</Cell><Cell>0.003</Cell><Cell>121.5</Cell><Cell>6.0</Cell></Row>
|
||||
<Time>2025-12-05 19:45:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>18</Cell><Cell>0.050</Cell><Cell>21</Cell><Cell>0.025</Cell><Cell>22</Cell><Cell>0.056</Cell><Cell>0.002</Cell><Cell>117.2</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:46:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>22</Cell><Cell>0.055</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>18</Cell><Cell>0.059</Cell><Cell>0.003</Cell><Cell>119.6</Cell><Cell>3.0</Cell></Row>
|
||||
<Time>2025-12-05 19:47:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell><1.0</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>47</Cell><Cell>0.077</Cell><Cell>0.002</Cell><Cell>118.3</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:48:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>8.1</Cell><Cell>0.030</Cell><Cell>39</Cell><Cell>0.020</Cell><Cell>23</Cell><Cell>0.037</Cell><Cell>0.002</Cell><Cell>116.6</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:49:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>17</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>24</Cell><Cell>0.074</Cell><Cell>0.002</Cell><Cell>118.6</Cell><Cell>3.3</Cell></Row>
|
||||
<Time>2025-12-05 19:50:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.2</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.072</Cell><Cell>0.003</Cell><Cell>118.8</Cell><Cell>2.6</Cell></Row>
|
||||
<Time>2025-12-05 19:51:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>13</Cell><Cell>0.035</Cell><Cell>21</Cell><Cell>0.020</Cell><Cell>20</Cell><Cell>0.041</Cell><Cell>0.001</Cell><Cell>112.8</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:52:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>14</Cell><Cell>0.075</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>47</Cell><Cell>0.081</Cell><Cell>0.004</Cell><Cell>121.7</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 19:53:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>37</Cell><Cell>0.072</Cell><Cell>0.004</Cell><Cell>121.9</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 19:54:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>16</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>47</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>120.6</Cell><Cell>15</Cell></Row>
|
||||
<Time>2025-12-05 19:55:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>22</Cell><Cell>0.060</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.065</Cell><Cell>0.003</Cell><Cell>120.7</Cell><Cell>2.0</Cell></Row>
|
||||
<Time>2025-12-05 19:56:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>21</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>37</Cell><Cell>0.066</Cell><Cell>0.003</Cell><Cell>121.1</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 19:57:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.6</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>47</Cell><Cell>0.072</Cell><Cell>0.004</Cell><Cell>121.9</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:58:25</Time>
|
||||
<Row>
|
||||
<Cell>0.030</Cell><Cell>18</Cell><Cell>0.075</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.079</Cell><Cell>0.003</Cell><Cell>121.5</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 19:59:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>12</Cell><Cell>0.075</Cell><Cell>43</Cell><Cell>0.035</Cell><Cell>30</Cell><Cell>0.081</Cell><Cell>0.003</Cell><Cell>119.4</Cell><Cell>1.8</Cell></Row>
|
||||
<Time>2025-12-05 20:00:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>20</Cell><Cell>0.050</Cell><Cell>22</Cell><Cell>0.025</Cell><Cell>23</Cell><Cell>0.057</Cell><Cell>0.002</Cell><Cell>115.0</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:01:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>11</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>18</Cell><Cell>0.066</Cell><Cell>0.003</Cell><Cell>119.1</Cell><Cell>2.4</Cell></Row>
|
||||
<Time>2025-12-05 20:02:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>22</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>39</Cell><Cell>0.073</Cell><Cell>0.003</Cell><Cell>119.0</Cell><Cell>2.4</Cell></Row>
|
||||
<Time>2025-12-05 20:03:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>15</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>43</Cell><Cell>0.076</Cell><Cell>0.003</Cell><Cell>119.7</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 20:04:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>16</Cell><Cell>0.050</Cell><Cell>34</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.055</Cell><Cell>0.002</Cell><Cell>115.9</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:05:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.2</Cell><Cell>0.045</Cell><Cell>34</Cell><Cell>0.020</Cell><Cell>30</Cell><Cell>0.049</Cell><Cell>0.002</Cell><Cell>117.6</Cell><Cell>2.3</Cell></Row>
|
||||
<Time>2025-12-05 20:06:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>27</Cell><Cell>0.055</Cell><Cell>24</Cell><Cell>0.025</Cell><Cell>16</Cell><Cell>0.061</Cell><Cell>0.002</Cell><Cell>115.4</Cell><Cell>4.9</Cell></Row>
|
||||
<Time>2025-12-05 20:07:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>3.5</Cell><Cell>0.090</Cell><Cell>47</Cell><Cell>0.040</Cell><Cell>57</Cell><Cell>0.097</Cell><Cell>0.004</Cell><Cell>123.1</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 20:08:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>17</Cell><Cell>0.060</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>51</Cell><Cell>0.066</Cell><Cell>0.003</Cell><Cell>119.9</Cell><Cell>2.3</Cell></Row>
|
||||
<Time>2025-12-05 20:09:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>32</Cell><Cell>0.090</Cell><Cell>43</Cell><Cell>0.045</Cell><Cell>37</Cell><Cell>0.098</Cell><Cell>0.002</Cell><Cell>118.6</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 20:10:25</Time>
|
||||
<Row>
|
||||
<Cell>0.035</Cell><Cell>11</Cell><Cell>0.070</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.077</Cell><Cell>0.003</Cell><Cell>120.3</Cell><Cell>3.7</Cell></Row>
|
||||
<Time>2025-12-05 20:11:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>20</Cell><Cell>0.070</Cell><Cell>0.002</Cell><Cell>117.4</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:12:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>5.3</Cell><Cell>0.050</Cell><Cell>24</Cell><Cell>0.025</Cell><Cell>26</Cell><Cell>0.059</Cell><Cell>0.002</Cell><Cell>118.2</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:13:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.055</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.061</Cell><Cell>0.002</Cell><Cell>117.1</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:14:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>13</Cell><Cell>0.060</Cell><Cell>47</Cell><Cell>0.025</Cell><Cell>51</Cell><Cell>0.064</Cell><Cell>0.002</Cell><Cell>118.3</Cell><Cell>4.0</Cell></Row>
|
||||
<Time>2025-12-05 20:15:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>12</Cell><Cell>0.035</Cell><Cell>24</Cell><Cell>0.020</Cell><Cell>19</Cell><Cell>0.043</Cell><Cell>0.002</Cell><Cell>115.7</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:16:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>10</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>51</Cell><Cell>0.072</Cell><Cell>0.002</Cell><Cell>117.8</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:17:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>32</Cell><Cell>0.065</Cell><Cell>43</Cell><Cell>0.025</Cell><Cell>43</Cell><Cell>0.069</Cell><Cell>0.004</Cell><Cell>123.3</Cell><Cell>2.1</Cell></Row>
|
||||
<Time>2025-12-05 20:18:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>13</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>37</Cell><Cell>0.070</Cell><Cell>0.003</Cell><Cell>119.6</Cell><Cell>4.1</Cell></Row>
|
||||
<Time>2025-12-05 20:19:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.8</Cell><Cell>0.055</Cell><Cell>23</Cell><Cell>0.025</Cell><Cell>24</Cell><Cell>0.062</Cell><Cell>0.003</Cell><Cell>120.0</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:20:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>7.2</Cell><Cell>0.050</Cell><Cell>39</Cell><Cell>0.025</Cell><Cell>39</Cell><Cell>0.057</Cell><Cell>0.002</Cell><Cell>117.8</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:21:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>3.2</Cell><Cell>0.050</Cell><Cell>23</Cell><Cell>0.025</Cell><Cell>26</Cell><Cell>0.059</Cell><Cell>0.002</Cell><Cell>116.6</Cell><Cell>2.5</Cell></Row>
|
||||
<Time>2025-12-05 20:22:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.2</Cell><Cell>0.055</Cell><Cell>23</Cell><Cell>0.025</Cell><Cell>37</Cell><Cell>0.062</Cell><Cell>0.002</Cell><Cell>118.3</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:23:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.065</Cell><Cell>47</Cell><Cell>0.030</Cell><Cell>24</Cell><Cell>0.072</Cell><Cell>0.003</Cell><Cell>120.2</Cell><Cell>1.8</Cell></Row>
|
||||
<Time>2025-12-05 20:24:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>18</Cell><Cell>0.050</Cell><Cell>32</Cell><Cell>0.025</Cell><Cell>34</Cell><Cell>0.057</Cell><Cell>0.002</Cell><Cell>116.9</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:25:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>13</Cell><Cell>0.080</Cell><Cell>47</Cell><Cell>0.035</Cell><Cell>51</Cell><Cell>0.087</Cell><Cell>0.002</Cell><Cell>118.5</Cell><Cell>1.9</Cell></Row>
|
||||
<Time>2025-12-05 20:26:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>6.6</Cell><Cell>0.040</Cell><Cell>23</Cell><Cell>0.020</Cell><Cell>30</Cell><Cell>0.046</Cell><Cell>0.002</Cell><Cell>117.6</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:27:25</Time>
|
||||
<Row>
|
||||
<Cell>0.020</Cell><Cell>17</Cell><Cell>0.040</Cell><Cell>21</Cell><Cell>0.020</Cell><Cell>23</Cell><Cell>0.047</Cell><Cell>0.002</Cell><Cell>115.2</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:28:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>18</Cell><Cell>0.090</Cell><Cell>73</Cell><Cell>0.040</Cell><Cell>51</Cell><Cell>0.093</Cell><Cell>0.003</Cell><Cell>119.3</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2025-12-05 20:29:25</Time>
|
||||
<Row>
|
||||
<Cell>0.025</Cell><Cell>28</Cell><Cell>0.075</Cell><Cell>43</Cell><Cell>0.030</Cell><Cell>57</Cell><Cell>0.081</Cell><Cell>0.004</Cell><Cell>122.2</Cell><Cell>2.2</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+137
@@ -0,0 +1,137 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE9440</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>K440HA3C.JM0H</FileName>
|
||||
<HistogramStartTime>11:42:58</HistogramStartTime>
|
||||
<HistogramStartDate>2018-02-10</HistogramStartDate>
|
||||
<HistogramStopTime>11:43:34</HistogramStopTime>
|
||||
<HistogramStopDate>2018-02-10</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>8.00</NumberofIntervals>
|
||||
<IntervalSize>5 seconds</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.8 Volts</BatteryLevel>
|
||||
<Calibration>January 11, 2018 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>Villanova Stadium Station - Seis. Loc #2</Project>
|
||||
<Client>D'Angleo Brothers, Inc</Client>
|
||||
<UserName>Terra-Mechanics, Inc - D Harrison</UserName>
|
||||
<Seis.Location>Loc # 2 - OutBound Track</Seis.Location>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.390</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>2.645</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.095</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>85</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>73</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>43</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>11:43:33</TranPeakTime>
|
||||
<TranPeakDate>2018-02-10</TranPeakDate>
|
||||
<VertPeakTime>11:43:33</VertPeakTime>
|
||||
<VertPeakDate>2018-02-10</VertPeakDate>
|
||||
<LongPeakTime>11:43:33</LongPeakTime>
|
||||
<LongPeakDate>2018-02-10</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>2.656</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>11:43:33</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2018-02-10</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>126.4</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>11:43:18</MicLTime>
|
||||
<MicLDate>2018-02-10</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.2 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.3</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.5 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.7</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.4 Hz.</LongTestFreq>
|
||||
<LongTestRatio>4.1</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>19.7 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>634 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Passed</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2018-02-10 11:42:57 - 2018-02-10 11:43:34 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2018-02-10 11:43:03</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>N/A</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>34</Cell></Row>
|
||||
<Time>2018-02-10 11:43:08</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>100.0</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2018-02-10 11:43:13</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>87.96</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2018-02-10 11:43:18</Time>
|
||||
<Row>
|
||||
<Cell>0.010</Cell><Cell>>100</Cell><Cell>0.015</Cell><Cell>>100</Cell><Cell>0.010</Cell><Cell>>100</Cell><Cell>0.016</Cell><Cell>0.006</Cell><Cell>126.4</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2018-02-10 11:43:23</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.004</Cell><Cell>122.0</Cell><Cell>43</Cell></Row>
|
||||
<Time>2018-02-10 11:43:28</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.010</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.011</Cell><Cell>0.000</Cell><Cell>87.96</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2018-02-10 11:43:33</Time>
|
||||
<Row>
|
||||
<Cell>0.390</Cell><Cell>85</Cell><Cell>2.645</Cell><Cell>73</Cell><Cell>0.095</Cell><Cell>43</Cell><Cell>2.656</Cell><Cell>0.000</Cell><Cell>93.98</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2018-02-10 11:43:34</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.007</Cell><Cell>0.000</Cell><Cell>87.96</Cell><Cell>>100</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+140
@@ -0,0 +1,140 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18193</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T193KR5M.X90H</FileName>
|
||||
<HistogramStartTime>17:22:21</HistogramStartTime>
|
||||
<HistogramStartDate>2024-10-07</HistogramStartDate>
|
||||
<HistogramStopTime>17:22:38</HistogramStopTime>
|
||||
<HistogramStopDate>2024-10-07</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>9.00</NumberofIntervals>
|
||||
<IntervalSize>2 seconds</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.3 Volts</BatteryLevel>
|
||||
<Calibration>July 10, 2024 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>I-80- North Fork Bridges-543 Plank Rd</Project>
|
||||
<Client>Fay Company</Client>
|
||||
<UserName>Terra-Mechanics Inc - Harrison</UserName>
|
||||
<Seis.Loc>Loc #1 -Main Line- Area 2 - 543 Plank Rd</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>2.290</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>5.515</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>1.520</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>11</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>34</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>18</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>17:22:37</TranPeakTime>
|
||||
<TranPeakDate>2024-10-07</TranPeakDate>
|
||||
<VertPeakTime>17:22:37</VertPeakTime>
|
||||
<VertPeakDate>2024-10-07</VertPeakDate>
|
||||
<LongPeakTime>17:22:37</LongPeakTime>
|
||||
<LongPeakDate>2024-10-07</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>5.818</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>17:22:37</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2024-10-07</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>108.0</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>17:22:37</MicLTime>
|
||||
<MicLDate>2024-10-07</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>57</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.6 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.7</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.7 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.5</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.5 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.6</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2024-10-07 17:22:20 - 2024-10-07 17:22:38 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2024-10-07 17:22:23</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.010</Cell><Cell>>100</Cell><Cell>0.011</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>64</Cell></Row>
|
||||
<Time>2024-10-07 17:22:25</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>64</Cell></Row>
|
||||
<Time>2024-10-07 17:22:27</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>64</Cell></Row>
|
||||
<Time>2024-10-07 17:22:29</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>64</Cell></Row>
|
||||
<Time>2024-10-07 17:22:31</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>64</Cell></Row>
|
||||
<Time>2024-10-07 17:22:33</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>73</Cell></Row>
|
||||
<Time>2024-10-07 17:22:35</Time>
|
||||
<Row>
|
||||
<Cell>0.005</Cell><Cell>>100</Cell><Cell>0.010</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.011</Cell><Cell>0.000</Cell><Cell>104.2</Cell><Cell>64</Cell></Row>
|
||||
<Time>2024-10-07 17:22:37</Time>
|
||||
<Row>
|
||||
<Cell>2.290</Cell><Cell>11</Cell><Cell>5.515</Cell><Cell>34</Cell><Cell>1.520</Cell><Cell>18</Cell><Cell>5.818</Cell><Cell>0.001</Cell><Cell>108.0</Cell><Cell>57</Cell></Row>
|
||||
<Time>2024-10-07 17:22:38</Time>
|
||||
<Row>
|
||||
<Cell>0.010</Cell><Cell>>100</Cell><Cell>0.020</Cell><Cell>2.9</Cell><Cell>0.005</Cell><Cell>>100</Cell><Cell>0.022</Cell><Cell>0.001</Cell><Cell>104.9</Cell><Cell>64</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18190</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T190LD42.T00H</FileName>
|
||||
<HistogramStartTime>13:29:24</HistogramStartTime>
|
||||
<HistogramStartDate>2025-12-08</HistogramStartDate>
|
||||
<HistogramStopTime>13:29:37</HistogramStopTime>
|
||||
<HistogramStopDate>2025-12-08</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>2048 sps</SampleRate>
|
||||
<BatteryLevel>6.7 Volts</BatteryLevel>
|
||||
<Calibration>June 13, 2025 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>I-80-North Fork-Area 3-462Richardsvilel</Project>
|
||||
<Client>Fay Company</Client>
|
||||
<UserName>Terra-Mechanics Inc.- Harrison</UserName>
|
||||
<SeisLoc>Loc #8 - Area 3- 462 Richardsville Road</SeisLoc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>1.280</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>2.615</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>1.120</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>15.5</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>64</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>17.7</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>13:29:37</TranPeakTime>
|
||||
<TranPeakDate>2025-12-08</TranPeakDate>
|
||||
<VertPeakTime>13:29:37</VertPeakTime>
|
||||
<VertPeakDate>2025-12-08</VertPeakDate>
|
||||
<LongPeakTime>13:29:37</LongPeakTime>
|
||||
<LongPeakDate>2025-12-08</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>2.644</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>13:29:37</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2025-12-08</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>107.0</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>13:29:37</MicLTime>
|
||||
<MicLDate>2025-12-08</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>51</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.4 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.2</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.6 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.4</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.3 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.7</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2025-12-08 13:29:23 - 2025-12-08 13:29:37 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2025-12-08 13:29:37</Time>
|
||||
<Row>
|
||||
<Cell>1.280</Cell><Cell>15.5</Cell><Cell>2.615</Cell><Cell>64</Cell><Cell>1.120</Cell><Cell>17.7</Cell><Cell>2.644</Cell><Cell>0.001</Cell><Cell>107.0</Cell><Cell>51</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18190</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T190LD5Q.LD0H</FileName>
|
||||
<HistogramStartTime>11:00:49</HistogramStartTime>
|
||||
<HistogramStartDate>2025-12-09</HistogramStartDate>
|
||||
<HistogramStopTime>11:00:59</HistogramStopTime>
|
||||
<HistogramStopDate>2025-12-09</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.9 Volts</BatteryLevel>
|
||||
<Calibration>June 13, 2025 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>I-80-North Fork-Area 3-462Richardsvilel</Project>
|
||||
<Client>Fay Company</Client>
|
||||
<UserName>Terra-Mechanics Inc.- Harrison</UserName>
|
||||
<SeisLoc>Loc #8 - Area 3- 462 Richardsville Road</SeisLoc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>2.140</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>OORANGE</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>2.830</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>85</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>34</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>11:00:59</TranPeakTime>
|
||||
<TranPeakDate>2025-12-09</TranPeakDate>
|
||||
<VertPeakTime>11:00:59</VertPeakTime>
|
||||
<VertPeakDate>2025-12-09</VertPeakDate>
|
||||
<LongPeakTime>11:00:59</LongPeakTime>
|
||||
<LongPeakDate>2025-12-09</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>OORANGE</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>11:00:59</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2025-12-09</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>106.0</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>11:00:59</MicLTime>
|
||||
<MicLDate>2025-12-09</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>85</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.4 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.4</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.6 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.5</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.3 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.9</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>20.5 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>691 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Passed</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2025-12-09 11:00:48 - 2025-12-09 11:00:59 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2025-12-09 11:00:59</Time>
|
||||
<Row>
|
||||
<Cell>2.140</Cell><Cell>>100</Cell><Cell>OORANGE</Cell><Cell>85</Cell><Cell>2.830</Cell><Cell>34</Cell><Cell>OORANGE</Cell><Cell>0.001</Cell><Cell>106.0</Cell><Cell>85</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE9557</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>K557I55Y.I20H</FileName>
|
||||
<HistogramStartTime>12:54:02</HistogramStartTime>
|
||||
<HistogramStartDate>2019-10-07</HistogramStartDate>
|
||||
<HistogramStopTime>12:54:28</HistogramStopTime>
|
||||
<HistogramStopDate>2019-10-07</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.4 Volts</BatteryLevel>
|
||||
<Calibration>January 18, 2019 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>Landmark - The Standard - Atherton Hotel</Project>
|
||||
<Client>Landmark Constructors</Client>
|
||||
<UserName>Terra-Mechanics, Inc. - D. Bartholomae</UserName>
|
||||
<SeisLocation>Loc 2- Atherton Hotel - 125 S. Atherton</SeisLocation>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.425</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>0.010</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.485</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>12:54:28</TranPeakTime>
|
||||
<TranPeakDate>2019-10-07</TranPeakDate>
|
||||
<VertPeakTime>12:54:28</VertPeakTime>
|
||||
<VertPeakDate>2019-10-07</VertPeakDate>
|
||||
<LongPeakTime>12:54:28</LongPeakTime>
|
||||
<LongPeakDate>2019-10-07</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>0.645</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>12:54:28</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2019-10-07</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>91.5</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>12:54:28</MicLTime>
|
||||
<MicLDate>2019-10-07</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.9 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.4</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.4 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.7</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.7 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.9</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>20.1 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>585 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Passed</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2019-10-07 12:54:01 - 2019-10-07 12:54:28 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2019-10-07 12:54:28</Time>
|
||||
<Row>
|
||||
<Cell>0.425</Cell><Cell>>100</Cell><Cell>0.010</Cell><Cell>>100</Cell><Cell>0.485</Cell><Cell>>100</Cell><Cell>0.645</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>>100</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+117
@@ -0,0 +1,117 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18438</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T438I4V5.DJ0H</FileName>
|
||||
<HistogramStartTime>16:48:55</HistogramStartTime>
|
||||
<HistogramStartDate>2019-10-01</HistogramStartDate>
|
||||
<HistogramStopTime>16:48:57</HistogramStopTime>
|
||||
<HistogramStopDate>2019-10-01</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.8 Volts</BatteryLevel>
|
||||
<Calibration>September 3, 2019 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<JobNumber>1</JobNumber>
|
||||
<Project>Univ of Pitt - Scaife Hall-UPMC - Loc 2</Project>
|
||||
<Client>P J Dick, Inc.</Client>
|
||||
<UserName>Terra-Mechanics, Inc. - D. Harrison</UserName>
|
||||
<Seis.Loc>Unit #2 - Station #2 - Loc 2</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.550</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>1.335</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.270</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>N/A</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>N/A</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>N/A</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>16:48:57</TranPeakTime>
|
||||
<TranPeakDate>2019-10-01</TranPeakDate>
|
||||
<VertPeakTime>16:48:57</VertPeakTime>
|
||||
<VertPeakDate>2019-10-01</VertPeakDate>
|
||||
<LongPeakTime>16:48:57</LongPeakTime>
|
||||
<LongPeakDate>2019-10-01</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>1.394</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>16:48:57</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2019-10-01</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>114.4</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>16:48:57</MicLTime>
|
||||
<MicLDate>2019-10-01</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>51</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.5 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.0</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.5 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.9</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.6 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.7</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2019-10-01 16:48:54 - 2019-10-01 16:48:57 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2019-10-01 16:48:57</Time>
|
||||
<Row>
|
||||
<Cell>0.550</Cell><Cell>N/A</Cell><Cell>1.335</Cell><Cell>N/A</Cell><Cell>0.270</Cell><Cell>N/A</Cell><Cell>1.394</Cell><Cell>0.002</Cell><Cell>114.4</Cell><Cell>51</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE9558</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>K558L4KY.440H</FileName>
|
||||
<HistogramStartTime>17:04:52</HistogramStartTime>
|
||||
<HistogramStartDate>2025-06-25</HistogramStartDate>
|
||||
<HistogramStopTime>17:05:39</HistogramStopTime>
|
||||
<HistogramStopDate>2025-06-25</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>5 minutes</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.3 Volts</BatteryLevel>
|
||||
<Calibration>June 13, 2025 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>Fay - Locks & Dam No3 -Loc 5 Synthomer</Project>
|
||||
<Client>Fay Company</Client>
|
||||
<UserName>Terra-Mechanics Inc - Harrison</UserName>
|
||||
<Seis.Loc>Location #5 Sythomer Plant</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>2.315</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>2.715</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>5.115</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>10</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>85</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>19</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>17:05:39</TranPeakTime>
|
||||
<TranPeakDate>2025-06-25</TranPeakDate>
|
||||
<VertPeakTime>17:05:39</VertPeakTime>
|
||||
<VertPeakDate>2025-06-25</VertPeakDate>
|
||||
<LongPeakTime>17:05:39</LongPeakTime>
|
||||
<LongPeakDate>2025-06-25</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>5.559</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>17:05:39</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2025-06-25</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>111.8</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>17:05:39</MicLTime>
|
||||
<MicLDate>2025-06-25</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>43</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.7 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.9</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.5 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.8</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.5 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.7</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2025-06-25 17:04:51 - 2025-06-25 17:05:39 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2025-06-25 17:05:39</Time>
|
||||
<Row>
|
||||
<Cell>2.315</Cell><Cell>10</Cell><Cell>2.715</Cell><Cell>85</Cell><Cell>5.115</Cell><Cell>19</Cell><Cell>5.559</Cell><Cell>0.001</Cell><Cell>111.8</Cell><Cell>43</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+3978
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+3975
File diff suppressed because it is too large.
Load diff
@@ -141,10 +141,12 @@ def test_a_report_fills_in_when_the_record_is_missing():
|
||||
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report")
|
||||
|
||||
|
||||
def test_a_histogram_keeps_its_footer_start_for_now():
|
||||
# Its record (marker fe f5) also holds Blastware's start -- that change is #51.
|
||||
def test_a_histogram_takes_its_event_records_start():
|
||||
# #51: its record (marker fe f5) holds Blastware's start; the footer's
|
||||
# 19:04:50 is a second early.
|
||||
ev = read_blastware_file(HISTOGRAM)
|
||||
assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 50), "footer")
|
||||
assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 51),
|
||||
"event_record")
|
||||
|
||||
|
||||
def test_the_sidecar_keeps_the_instruments_time_and_says_where_it_came_from():
|
||||
@@ -173,13 +175,16 @@ def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbou
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
|
||||
other = Event(index=0) # a different event at 14:23:43
|
||||
# A different waveform at 14:23:43. The key is unit + time + type (#51), so
|
||||
# "its neighbour" is an event of the same type at the same second.
|
||||
other = Event(index=0)
|
||||
other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
|
||||
hour=14, minute=23, second=43)
|
||||
other._waveform_key = bytes.fromhex("01110000")
|
||||
other.record_type = "Waveform"
|
||||
other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
|
||||
db.insert_events([other], serial="BE9441", device_family="series3",
|
||||
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
|
||||
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0W"}})
|
||||
|
||||
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
|
||||
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
|
||||
@@ -189,6 +194,31 @@ def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbou
|
||||
waveform_records={ev._waveform_key.hex(): rec}) == (0, 1)
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \
|
||||
[("K441LTOF.ZJ0H", 0.04)]
|
||||
[("K441LTOF.ZJ0W", 0.04)]
|
||||
assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept
|
||||
assert any("not merged" in r.message for r in caplog.records)
|
||||
|
||||
|
||||
def test_an_estimate_beside_a_histogram_at_its_second_is_stored_alongside(tmp_path):
|
||||
# A waveform and a histogram may share a second (#51): the estimate is its
|
||||
# own row, and the histogram is untouched.
|
||||
import sqlite3
|
||||
from minimateplus.models import Event, PeakValues, Timestamp
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
|
||||
hist = Event(index=0)
|
||||
hist.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
|
||||
hour=14, minute=23, second=43)
|
||||
hist._waveform_key = bytes.fromhex("01110000")
|
||||
hist.record_type = "Histogram"
|
||||
hist.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
|
||||
db.insert_events([hist], serial="BE9441", device_family="series3",
|
||||
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
|
||||
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
|
||||
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
|
||||
assert db.insert_events([ev], serial="BE9441", device_family="series3",
|
||||
waveform_records={ev._waveform_key.hex(): rec}) == (1, 0)
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
rows = c.execute("SELECT record_type, peak_vector_sum FROM events ORDER BY record_type").fetchall()
|
||||
assert rows[0] == ("Histogram", 0.04) and rows[1][0] == "Waveform"
|
||||
@@ -276,3 +276,249 @@ def test_an_imported_file_and_the_backfill_store_its_range(tmp_path):
|
||||
"--db-path", str(tmp_path / "seismo_relay.db"), "--force"]) == 0
|
||||
with h5py.File(h5, "r") as f:
|
||||
assert f.attrs["geo_range"] == "sensitive"
|
||||
|
||||
|
||||
# ── The job number ──────────────────────────────────────────────────────────
|
||||
# Series IV's 0x1A layout again: report flags at k - 9 (bit 0x02 = job number
|
||||
# shown) and the number, uint16 BE, at k - 8, kept while switched off. The flag
|
||||
# matches Blastware's JobNumber on 2,997 / 2,997 DL2 events that print one and
|
||||
# 66,986 / 66,986 that don't (measured 2026-11-02). Every printed value is 1;
|
||||
# hidden ones hold real numbers (802, 1012, 1013, 622).
|
||||
|
||||
@pytest.mark.parametrize("rel,enabled,number", [
|
||||
("decode-checker-10-29-26/T1905KDW.5F0W", True, 1), # XML JobNumber 1
|
||||
("job-number-11-02-26/T438I4V5.DJ0H", True, 1), # histogram, XML JobNumber 1
|
||||
("job-number-11-02-26/K557I55Y.I20H", False, 802), # no JobNumber in the XML
|
||||
("decode-checker-10-29-26/R352HFZ7.530H", False, 1),
|
||||
])
|
||||
def test_job_number_comes_from_the_file(rel, enabled, number):
|
||||
pi = read_blastware_file(_FIX / rel).project_info
|
||||
assert (pi.job_number_enabled, pi.job_number) == (enabled, number)
|
||||
|
||||
|
||||
def test_the_h5_carries_the_job_number(tmp_path):
|
||||
import h5py
|
||||
from sfm import event_hdf5
|
||||
ev = read_blastware_file(_FIX / "job-number-11-02-26/K557I55Y.I20H")
|
||||
event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE9557")
|
||||
with h5py.File(tmp_path / "e.h5", "r") as f:
|
||||
assert (bool(f.attrs["job_number_enabled"]), int(f.attrs["job_number"])) == (False, 802)
|
||||
|
||||
|
||||
# ── Histograms: the codec follows the record type, and loud short blocks ─────
|
||||
_HD = "histogram-decode-11-02-26"
|
||||
|
||||
|
||||
def test_a_histogram_body_goes_to_the_histogram_codec():
|
||||
# BE9440, 2018, 5 s intervals. The waveform codec accepted this body when
|
||||
# it was tried first, and returned ~5x too many "samples". Blastware's
|
||||
# report: 6,976 intervals, PPV 0.180 / 0.195 / 0.215, PVS 0.270, start
|
||||
# 2018-04-26 07:53:41.
|
||||
ev = read_blastware_file(_FIX / _HD / "K440HDXX.XH0H")
|
||||
assert ev.record_type == "Histogram"
|
||||
assert len(ev.raw_samples["Tran"]) == 6976
|
||||
pv = ev.peak_values
|
||||
for got, want in zip((pv.tran, pv.vert, pv.long, pv.peak_vector_sum),
|
||||
(0.180, 0.195, 0.215, 0.270)):
|
||||
assert abs(got - want) <= 0.0005 + 1e-9, (got, want)
|
||||
ts = ev.timestamp
|
||||
assert (ts.year, ts.month, ts.day) == (2018, 4, 26)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name,n", [
|
||||
("T193KR5M.X90H", 9), # 2 s; its 8th interval is 5.8 in/s of vector sum
|
||||
("K440HA3C.JM0H", 8), # 5 s
|
||||
])
|
||||
def test_a_loud_interval_does_not_hide_a_short_histogram(name, n):
|
||||
# A short (one-block) sub-minute histogram is found by its record layout.
|
||||
# An interval louder than 1.28 in/s has a vector sum squared above 65,535,
|
||||
# which the old "first word is 0000" test rejected.
|
||||
ev = read_blastware_file(_FIX / _HD / name)
|
||||
assert len(ev.raw_samples["Tran"]) == n
|
||||
|
||||
|
||||
# ── The footer is the file's last 26 bytes ──────────────────────────────────
|
||||
# Every DL2 file ends in a valid footer (70,041 / 70,041: 0e 08 and two valid
|
||||
# times). A few also hold an earlier "0e 08 + date" record, ~1.1 KB before
|
||||
# the end: the stop time followed by zeros. The first-match footer search took
|
||||
# it, so a histogram started at its own stop -- a day late on BE9558's daily
|
||||
# histograms -- and a waveform lost its stop and its trigger time.
|
||||
_FT = "footer-11-03-26"
|
||||
|
||||
|
||||
def test_a_histogram_starts_at_its_footer_not_at_an_earlier_stop_record():
|
||||
ts = read_blastware_file(_FIX / _FT / "K558L9XP.FK0H").timestamp
|
||||
# Blastware: 2025-10-07 19:14:08 (SFM read 2025-10-08 19:10:01)
|
||||
assert (ts.year, ts.month, ts.day, ts.hour, ts.minute) == (2025, 10, 7, 19, 14)
|
||||
|
||||
|
||||
def test_a_histogram_with_the_early_record_gets_its_time():
|
||||
ts = read_blastware_file(_FIX / _FT / "T003LCYV.JD0H").timestamp
|
||||
# Blastware: 2025-12-05 18:04:25 (SFM had no time at all)
|
||||
assert ts is not None
|
||||
assert (ts.year, ts.month, ts.day, ts.hour, ts.minute) == (2025, 12, 5, 18, 4)
|
||||
|
||||
|
||||
def test_a_waveform_with_the_early_record_is_timed_from_its_trigger():
|
||||
ev = read_blastware_file(_FIX / _FT / "K440I4LG.JK0W")
|
||||
ts = ev.timestamp
|
||||
# Blastware: 2019-09-26 11:14:08, record time 4 s (SFM read the stop, 11:14:12)
|
||||
assert (ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) == (2019, 9, 26, 11, 14, 8)
|
||||
assert ev.timestamp_source in ("event_record", "estimate")
|
||||
|
||||
|
||||
# ── Group A: identity, battery, trigger ─────────────────────────────────────
|
||||
# The identity block before the setup name is what the live read gets from
|
||||
# SUB FE (DeviceInfo): serial k-202, firmware k-147, DSP version k-138,
|
||||
# calibration date k-132 and "by" k-128, manufacturer k-94, model k-72; the
|
||||
# battery is a uint16 of hundredths of a volt at k-190. Measured against every
|
||||
# DL2 report 2026-11-03 (serial, version, calibration 69,983 / 69,983).
|
||||
import datetime as _dt # noqa: E402
|
||||
|
||||
_SF = "setup-fields-11-03-26"
|
||||
|
||||
|
||||
def test_the_identity_block_is_read():
|
||||
# Blastware: BE18189, "V 10.72-8.17 MiniMate Plus",
|
||||
# "February 20, 2019 by Instantel", "6.8 Volts"
|
||||
ev = read_blastware_file(_FIX / _SF / "T189HUD6.QE0W")
|
||||
di = ev.device_info
|
||||
assert (di.serial, di.firmware_version, di.dsp_version, di.manufacturer, di.model) == (
|
||||
"BE18189", "S338.17", "10.72", "Instantel", "MiniMate Plus")
|
||||
assert di.firmware_minor == 17
|
||||
assert (di.calibration_date, di.calibrated_by) == (_dt.date(2019, 2, 20), "Instantel")
|
||||
assert abs(ev.battery_volts - 6.8) <= 0.05 + 1e-9
|
||||
|
||||
|
||||
def test_the_battery_is_kept_exact():
|
||||
# Blastware prints "6.3 Volts" for a stored 6.25: it rounds half up.
|
||||
assert read_blastware_file(_FIX / _SF / "K558L4KY.440H").battery_volts == 6.25
|
||||
|
||||
|
||||
# (file, Blastware's Trigger as the event record's bitmask, geo level in/s,
|
||||
# mic level psi or None, mic a trigger source)
|
||||
@pytest.mark.parametrize("rel,by,geo,mic_psi,mic_src", [
|
||||
(f"{_SF}/T189HUD6.QE0W", 0x0008, 0.050, 0.0072, True), # MicL, 128.0 dB(L)
|
||||
(f"{_SF}/T438L713.RY0W", 0x0002, 0.500, 0.0100, True), # Vert, 130.8 dB(L)
|
||||
(f"{_SF}/M529I6LG.3Y0W", 0x0004, 0.050, 0.005, True), # Long, 0.005 psi(L)
|
||||
("bw-import-fields-10-29-26/R352HIUI.F40W", 0x0001, 0.400, None, False), # Tran
|
||||
("decode-checker-10-29-26/T1905KDW.5F0W", 0x0200, None, None, None), # Manual
|
||||
])
|
||||
def test_the_trigger_comes_from_the_file(rel, by, geo, mic_psi, mic_src):
|
||||
ev = read_blastware_file(_FIX / rel)
|
||||
assert ev.triggered_by == by
|
||||
if geo is not None:
|
||||
assert abs(ev.trigger_level_geo - geo) <= 0.0005 + 1e-9
|
||||
if mic_psi is not None:
|
||||
assert abs(ev.trigger_level_mic_psi - mic_psi) <= 0.0005 + 1e-9 # psi to 3 places, as printed
|
||||
if mic_src is not None:
|
||||
assert bool(ev.trigger_sources & 0x08) == mic_src
|
||||
assert (ev.record_stop_mode, ev.mic_type) == (0, 2) # Fixed, Linear Weighting
|
||||
|
||||
|
||||
def test_the_h5_carries_the_setup_fields(tmp_path):
|
||||
import h5py
|
||||
from sfm import event_hdf5
|
||||
ev = read_blastware_file(_FIX / _SF / "T189HUD6.QE0W")
|
||||
event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE18189")
|
||||
with h5py.File(tmp_path / "e.h5", "r") as f:
|
||||
a = f.attrs
|
||||
assert abs(float(a["battery_volts"]) - 6.8) <= 0.05 + 1e-9
|
||||
assert (int(a["triggered_by"]), int(a["trigger_sources"])) == (0x0008, ev.trigger_sources)
|
||||
assert abs(float(a["trigger_level_geo_ips"]) - 0.050) <= 0.0005 + 1e-9
|
||||
assert abs(float(a["trigger_level_mic_psi"]) - ev.trigger_level_mic_psi) < 1e-9
|
||||
assert (str(a["firmware_version"]), str(a["dsp_version"]), str(a["calibration_date"])) == (
|
||||
"S338.17", "10.72", "2019-02-20")
|
||||
|
||||
|
||||
# ── Group B: histogram interval detail ──────────────────────────────────────
|
||||
# Interval size is the setup's uint16 seconds at k - 40 (Series IV [8:10]); the
|
||||
# stop is the footer's. Each interval keeps its half-periods and its vector sum
|
||||
# (PVS^2). Frequency = (sample rate / 2) / half-period: 527,915 / 527,915 cells
|
||||
# at 1024 sps and 1,725 / 1,725 at 2048 (#50: the old fixed 512 halved every
|
||||
# 2048-sps frequency). Measured 2026-11-03.
|
||||
from minimateplus.histogram_codec import half_period_to_hz # noqa: E402
|
||||
|
||||
_HB = "histogram-intervals-11-03-26"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,sr,freqs,pvs,stop", [
|
||||
# Blastware: 1 minute; Tran 32, Vert 47, Long 14, MicL 47 Hz; PVS 1.358; stop 12:49:33
|
||||
("decode-checker-10-29-26/T004JTRF.ME0H", 1024,
|
||||
{"Tran": 32, "Vert": 47, "Long": 14, "MicL": 47}, 1.358, (2022, 12, 28, 12, 49, 33)),
|
||||
# Blastware: 1 minute at 2048 sps; Tran 15.5, Vert 64, Long 17.7, MicL 51 Hz; PVS 2.644
|
||||
(f"{_HB}/T190LD42.T00H", 2048,
|
||||
{"Tran": 15.5, "Vert": 64, "Long": 17.7, "MicL": 51}, 2.644, (2025, 12, 8, 13, 29, 37)),
|
||||
])
|
||||
def test_histogram_interval_detail_comes_from_the_file(rel, sr, freqs, pvs, stop):
|
||||
ev = read_blastware_file(_FIX / rel)
|
||||
assert (ev.sample_rate, ev.histogram_interval_sec) == (sr, 60)
|
||||
for ch, hz in freqs.items():
|
||||
got = half_period_to_hz(ev.interval_half_periods[ch][0], ev.sample_rate)
|
||||
d = 1 if isinstance(hz, float) else 0
|
||||
assert abs(got - hz) <= 0.5 * 10 ** -d + 1e-9, (ch, got, hz)
|
||||
assert abs(ev.interval_pvs[0] - pvs) <= 0.0005 + 1e-9
|
||||
t = ev.stop_time
|
||||
assert (t.year, t.month, t.day, t.hour, t.minute, t.second) == stop
|
||||
|
||||
|
||||
def test_the_h5_carries_the_interval_detail(tmp_path):
|
||||
import h5py
|
||||
from sfm import event_hdf5
|
||||
ev = read_blastware_file(_FIX / _HB / "T190LD42.T00H")
|
||||
event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE18190")
|
||||
with h5py.File(tmp_path / "e.h5", "r") as f:
|
||||
assert int(f.attrs["histogram_interval_sec"]) == 60
|
||||
assert list(f["intervals/half_period/Vert"][:]) == ev.interval_half_periods["Vert"]
|
||||
assert abs(float(f["intervals/pvs_ips"][0]) - 2.644) <= 0.0005 + 1e-9
|
||||
|
||||
|
||||
# ── #51: a histogram's start and stop from its own event record ─────────────
|
||||
# The footer's start runs a second early on 97%. The histogram's event record
|
||||
# (lead 00 28 05 00, source 04 00, marker fe f5) holds Blastware's start and
|
||||
# stop: 63,490 / 63,490 DL2 histograms each (2026-11-03).
|
||||
|
||||
def test_a_histogram_starts_at_its_event_records_start():
|
||||
ev = read_blastware_file(_FIX / "decode-checker-10-29-26/T004JTRF.ME0H")
|
||||
t, s = ev.timestamp, ev.stop_time
|
||||
# Blastware: start 2022-12-28 12:49:26, stop 12:49:33
|
||||
assert (t.year, t.month, t.day, t.hour, t.minute, t.second) == (2022, 12, 28, 12, 49, 26)
|
||||
assert (s.hour, s.minute, s.second) == (12, 49, 33)
|
||||
assert ev.timestamp_source == "event_record"
|
||||
|
||||
|
||||
def test_a_histogram_without_its_record_falls_back_to_the_footer_and_says_so():
|
||||
raw = bytearray((_FIX / "decode-checker-10-29-26/T004JTRF.ME0H").read_bytes())
|
||||
i = raw.find(b"\xfe\xf5")
|
||||
raw[i] = 0x00 # break the record's marker
|
||||
ev = decode_blastware_bytes(bytes(raw), name=None)
|
||||
assert ev.timestamp_source == "footer"
|
||||
assert ev.timestamp.second == 25 # the footer's start, a second early
|
||||
assert any("histogram event record" in p for p in ev.decode_problems)
|
||||
|
||||
|
||||
# ── Group D, part 1: time of peak, vector-sum time, peak acceleration ───────
|
||||
# Measured on 400 DL2 waveforms (2026-11-04):
|
||||
# time of peak = (peak sample - pre-trigger samples) / sample rate: 1,197 / 1,197
|
||||
# vector-sum time, the same on sqrt(T^2 + V^2 + L^2): 398 / 399
|
||||
# peak acceleration = largest |v[i+1] - v[i]| x rate / g, with Blastware's g
|
||||
# fitted to [386.2236, 386.2240] in/s^2 by every DL2 value: 19,475 / 19,479
|
||||
|
||||
@pytest.mark.parametrize("rel,times,pvs_time,accel", [
|
||||
(f"{_SF}/T189HUD6.QE0W",
|
||||
{"tran": 0.004, "vert": 0.001, "long": 0.024, "micl": 0.003}, 0.016, (0.027, 0.013, 0.027)),
|
||||
("decode-checker-10-29-26/R352HIUI.F40W",
|
||||
{"tran": 0.000, "vert": 0.000, "long": 0.000, "micl": 0.005}, 0.000, (1.617, 0.278, 0.318)),
|
||||
])
|
||||
def test_waveform_peak_detail_comes_from_the_samples(rel, times, pvs_time, accel):
|
||||
pv = read_blastware_file(_FIX / rel).peak_values
|
||||
for ch, t in times.items():
|
||||
assert abs(getattr(pv, f"{ch}_time_of_peak") - t) <= 0.0005 + 1e-9, (ch, getattr(pv, f"{ch}_time_of_peak"))
|
||||
assert abs(pv.pvs_time - pvs_time) <= 0.0005 + 1e-9
|
||||
for got, want in zip((pv.tran_peak_accel_g, pv.vert_peak_accel_g, pv.long_peak_accel_g), accel):
|
||||
assert abs(got - want) <= 0.0005 + 1e-9, (got, want)
|
||||
|
||||
|
||||
def test_a_histogram_has_no_waveform_peak_detail():
|
||||
pv = read_blastware_file(_FIX / "decode-checker-10-29-26/T004JTRF.ME0H").peak_values
|
||||
assert (pv.tran_time_of_peak, pv.pvs_time, pv.tran_peak_accel_g) == (None, None, None)
|
||||
@@ -83,9 +83,12 @@ def test_a_waveform_read_under_another_name_keeps_its_time(tmp_path):
|
||||
datetime.datetime(2026, 10, 26, 14, 23, 42)
|
||||
|
||||
|
||||
def test_a_histogram_keeps_the_binarys_window_start():
|
||||
assert blastware_filename_time(HISTOGRAM.name) != datetime.datetime(2026, 5, 10, 19, 4, 50)
|
||||
assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 50)
|
||||
def test_a_histogram_now_agrees_with_its_filename():
|
||||
# #51: the start comes from the histogram's own event record, which is
|
||||
# Blastware's -- and so the filename's. The footer's window start (19:04:50)
|
||||
# was a second early.
|
||||
assert blastware_filename_time(HISTOGRAM.name) == datetime.datetime(2026, 5, 10, 19, 4, 51)
|
||||
assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 51)
|
||||
|
||||
|
||||
def test_an_import_no_longer_lands_a_waveform_on_its_histogram_twins_row(tmp_path):
|
||||
|
||||
+189
-6
@@ -39,7 +39,9 @@ def test_event_type_comes_from_the_bytes():
|
||||
|
||||
def test_report_fields_stay_blank():
|
||||
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
|
||||
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
|
||||
# (BatteryLevel and Calibration are read since 2026-11-03, peak acceleration
|
||||
# since 2026-11-04: test_the_setup_fields_match_blastware, test_waveform_peak_detail_*)
|
||||
for tag in ("TranZCFreq", "TranPeakDisplacement", "TranTestResults"):
|
||||
assert s.values.get(tag) is None
|
||||
|
||||
|
||||
@@ -66,7 +68,7 @@ def test_full_waveform_row_verdicts():
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["BatteryLevel"].verdict == "sfm_blank"
|
||||
assert res["BatteryLevel"].verdict == "match" # 6.72 V, printed "6.7 Volts"
|
||||
assert "FileName" not in res
|
||||
|
||||
|
||||
@@ -86,9 +88,8 @@ def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
assert "row_length_disagreements=1" in res["samples.Tran"].detail
|
||||
|
||||
|
||||
def test_job_number_na_and_above_range():
|
||||
res = _results("T1905KDW.5F0W")
|
||||
assert res["JobNumber"].verdict == "sfm_blank"
|
||||
def test_zc_frequency_na_and_above_range():
|
||||
res = _results("T1905KDW.5F0W") # its JobNumber: test_the_job_number_matches_blastware
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
|
||||
@@ -96,7 +97,7 @@ def test_job_number_na_and_above_range():
|
||||
def test_mic_units_pick_the_conversion():
|
||||
res = _results("T004JTRF.ME0H") # psi(L)
|
||||
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
|
||||
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
|
||||
assert res["intervals.Tran Freq Hz"].verdict == "match" # read since 2026-11-03
|
||||
fields = set(_results("R352HFZ7.530H")) # no mic
|
||||
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
|
||||
|
||||
@@ -172,3 +173,185 @@ def test_a_sensitive_range_event_now_matches():
|
||||
for f in ("GeoRange", "TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
|
||||
"samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
|
||||
|
||||
def test_the_job_number_matches_blastware():
|
||||
assert _results("T1905KDW.5F0W", CARVEOUTS)["JobNumber"].verdict == "match"
|
||||
|
||||
|
||||
def test_a_hidden_job_number_is_not_reported():
|
||||
# Flag off: Blastware prints no JobNumber, and SFM's side reports none either.
|
||||
assert sfm_side((FIX / "R352HFZ7.530H").read_bytes()).job_number is None
|
||||
|
||||
|
||||
def test_a_job_number_only_sfm_shows_is_a_mismatch():
|
||||
side = sfm_side((FIX / "R352HFZ7.530H").read_bytes())
|
||||
side.job_number = "1"
|
||||
res = {r.field: r for r in compare(side, parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML"))}
|
||||
assert res["JobNumber"].verdict == "mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stem", ["T193KR5M.X90H", "K440HA3C.JM0H"])
|
||||
def test_a_loud_short_histogram_matches_blastware(stem):
|
||||
hd = FIX.parent / "histogram-decode-11-02-26"
|
||||
res = {r.field: r for r in compare(sfm_side((hd / stem).read_bytes()),
|
||||
parse_xml_report_file(hd / (stem.replace(".", "_", 1) + "_XML.XML")),
|
||||
CARVEOUTS)}
|
||||
for f in ("NumberofIntervals", "intervals.Tran Peak in/s", "intervals.Vert Peak in/s",
|
||||
"intervals.Long Peak in/s"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
|
||||
|
||||
def _count_case(extra, drop_rows=0):
|
||||
jf = FIX.parent / "job-number-11-02-26"
|
||||
ref = parse_xml_report_file(jf / "T438I4V5_DJ0H_XML.XML")
|
||||
rows = len(ref.intervals)
|
||||
ref.scalars["NumberofIntervals"] = f"{rows + extra}.00"
|
||||
if drop_rows:
|
||||
ref.intervals = ref.intervals[:-drop_rows]
|
||||
side = sfm_side((jf / "T438I4V5.DJ0H").read_bytes())
|
||||
return {r.field: r for r in compare(side, ref, CARVEOUTS)}["NumberofIntervals"]
|
||||
|
||||
|
||||
def test_blastware_counting_the_monitoring_time_is_accepted():
|
||||
# Blastware's Number of Intervals is (stop - start) / interval. When the
|
||||
# unit never wrote the last minute, Blastware's own table lists one block
|
||||
# fewer, and SFM matches the table (T193KSWP.FF0H: 2,880 against 2,850 rows).
|
||||
r = _count_case(30)
|
||||
assert (r.verdict, r.carveout) == ("accepted", "interval-count-is-duration")
|
||||
|
||||
|
||||
def test_the_count_carveout_needs_blastwares_own_table_to_agree_with_sfm():
|
||||
assert _count_case(30, drop_rows=1).verdict == "mismatch"
|
||||
|
||||
|
||||
_GROUP_A = ("SerialNumber", "Version", "Calibration", "BatteryLevel", "Trigger",
|
||||
"GeoTriggerLevel", "MicTriggerLevel", "RecordStopMode", "Microphone", "Units")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stem,printed", [
|
||||
("T189HUD6.QE0W", set(_GROUP_A)),
|
||||
("T438L713.RY0W", set(_GROUP_A)), # 130.8 dB(L): 0.01 psi at 6895 Pa/psi
|
||||
("K558L4KY.440H", {"SerialNumber", "Version", "Calibration", "BatteryLevel",
|
||||
"Microphone", "Units"}), # histogram; battery 6.25 -> "6.3"
|
||||
])
|
||||
def test_the_setup_fields_match_blastware(stem, printed):
|
||||
sf = FIX.parent / "setup-fields-11-03-26"
|
||||
res = {r.field: r for r in compare(sfm_side((sf / stem).read_bytes()),
|
||||
parse_xml_report_file(sf / (stem.replace(".", "_", 1) + "_XML.XML")),
|
||||
CARVEOUTS)}
|
||||
assert printed <= set(res)
|
||||
for f in printed:
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
|
||||
|
||||
def test_a_manual_trigger_matches():
|
||||
res = _results("T1905KDW.5F0W", CARVEOUTS)
|
||||
assert res["Trigger"].verdict == "match"
|
||||
|
||||
|
||||
def _units_case(sfm_units):
|
||||
sf = FIX.parent / "setup-fields-11-03-26"
|
||||
ref = parse_xml_report_file(sf / "T189HUD6_QE0W_XML.XML")
|
||||
ref.scalars["Units"] = "in/s and psi(L)"
|
||||
side = sfm_side((sf / "T189HUD6.QE0W").read_bytes())
|
||||
if sfm_units is not None:
|
||||
side.values["Units"] = sfm_units
|
||||
return {r.field: r for r in compare(side, ref, CARVEOUTS)}["Units"]
|
||||
|
||||
|
||||
def test_dB_or_psi_is_blastwares_display_preference():
|
||||
# Blastware writes its report in its PC's current preference; DL2's reports
|
||||
# switch fleet-wide in 61 clean runs by write time, and no byte in the file
|
||||
# tells them apart.
|
||||
r = _units_case(None)
|
||||
assert (r.verdict, r.carveout) == ("accepted", "units-is-a-display-preference")
|
||||
|
||||
|
||||
def test_the_units_carveout_still_needs_the_mic():
|
||||
assert _units_case("in/s").verdict == "mismatch"
|
||||
|
||||
|
||||
def test_a_mic_trigger_level_is_read_in_the_unit_it_is_printed_in():
|
||||
# K441LA17.IN0W: Units "in/s and psi(L)", yet MicTriggerLevel "125.0 dB(L)".
|
||||
# The printed value states its own unit; that is the one to compare in.
|
||||
sf = FIX.parent / "setup-fields-11-03-26"
|
||||
ref = parse_xml_report_file(sf / "T189HUD6_QE0W_XML.XML") # 128.0 dB(L)
|
||||
ref.event_units = "in/s and psi(L)"
|
||||
res = {r.field: r for r in compare(sfm_side((sf / "T189HUD6.QE0W").read_bytes()), ref, CARVEOUTS)}
|
||||
assert res["MicTriggerLevel"].verdict == "match", res["MicTriggerLevel"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [FIX / "T004JTRF.ME0H",
|
||||
FIX.parent / "histogram-intervals-11-03-26" / "T190LD42.T00H"])
|
||||
def test_histogram_interval_detail_matches_blastware(path):
|
||||
ref = parse_xml_report_file(path.with_name(path.name.replace(".", "_", 1) + "_XML.XML"))
|
||||
res = {r.field: r for r in compare(sfm_side(path.read_bytes()), ref, CARVEOUTS)}
|
||||
for f in ("IntervalSize", "HistogramStopDate", "HistogramStopTime", "intervals.Tran Freq Hz",
|
||||
"intervals.Vert Freq Hz", "intervals.Long Freq Hz", "intervals.MicL Freq Hz",
|
||||
"intervals.Geo PVS in/s"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("halfp,sr,want", [
|
||||
(0, 1024, "N/A"), (5, 1024, ">100"), (5, 2048, ">200"), (1024, 1024, "<1.0"),
|
||||
])
|
||||
def test_blastwares_interval_frequency_words(halfp, sr, want):
|
||||
# N/A for a half-period of 0, ">100" / ">200" at 5 samples or fewer, "<1.0"
|
||||
# below 1 Hz -- on ~3.1 M DL2 cells, 2026-11-03.
|
||||
from minimateplus.decode_check import interval_frequency
|
||||
assert interval_frequency(halfp, sr) == want
|
||||
|
||||
|
||||
def _pvs_oorange(unclamp=False):
|
||||
hb = FIX.parent / "histogram-intervals-11-03-26"
|
||||
ref = parse_xml_report_file(hb / "T190LD5Q_LD0H_XML.XML") # Geo PVS OORANGE, Vert OORANGE
|
||||
if unclamp:
|
||||
cols = ref.interval_columns
|
||||
t, row = ref.intervals[0]
|
||||
row = list(row)
|
||||
row[cols.index("Vert Peak in/s")] = "0.500"
|
||||
ref.intervals[0] = (t, row)
|
||||
res = {r.field: r for r in compare(sfm_side((hb / "T190LD5Q.LD0H").read_bytes()), ref, CARVEOUTS)}
|
||||
return res["intervals.Geo PVS in/s"]
|
||||
|
||||
|
||||
def test_an_oorange_interval_vector_sum_is_saturation():
|
||||
# Blastware prints OORANGE for an interval's vector sum above the range when
|
||||
# it clamped a channel in that interval: 17 / 17 DL2 cells, SFM's sum
|
||||
# 10.01 .. 17.33 (= sqrt 3 x 10.005).
|
||||
r = _pvs_oorange()
|
||||
assert (r.verdict, r.carveout) == ("accepted", "saturation")
|
||||
|
||||
|
||||
def test_an_oorange_vector_sum_needs_a_clamped_channel_in_that_interval():
|
||||
assert _pvs_oorange(unclamp=True).verdict == "mismatch"
|
||||
|
||||
|
||||
_PEAK_TIMES = ("TranPeakDate", "TranPeakTime", "VertPeakDate", "VertPeakTime", "LongPeakDate",
|
||||
"LongPeakTime", "PeakVectorSumDate", "PeakVectorSumTime", "MicLDate", "MicLTime")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [FIX / "T004JTRF.ME0H", # 1 interval
|
||||
FIX.parent / "footer-11-03-26" / "T003LCYV.JD0H", # 145
|
||||
FIX.parent / "histogram-decode-11-02-26" / "K440HA3C.JM0H"]) # 8 x 5 s
|
||||
def test_histogram_times_match_blastware(path):
|
||||
# #51: an interval's printed time is its end -- start + (n + 1) x interval,
|
||||
# capped at the stop -- and each peak's date and time are its interval's:
|
||||
# 2,308,524 / 2,308,524 rows and 2,000 / 2,000 peaks each on a DL2 sample.
|
||||
ref = parse_xml_report_file(path.with_name(path.name.replace(".", "_", 1) + "_XML.XML"))
|
||||
res = {r.field: r for r in compare(sfm_side(path.read_bytes()), ref, CARVEOUTS)}
|
||||
for f in (("HistogramStartDate", "HistogramStartTime", "HistogramStopTime", "intervals.Time")
|
||||
+ tuple(t for t in _PEAK_TIMES if t in ref.scalars)):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [FIX / "R352HIUI.F40W",
|
||||
FIX.parent / "setup-fields-11-03-26" / "T189HUD6.QE0W"])
|
||||
def test_waveform_peak_detail_matches_blastware(path):
|
||||
ref = parse_xml_report_file(path.with_name(path.name.replace(".", "_", 1) + "_XML.XML"))
|
||||
res = {r.field: r for r in compare(sfm_side(path.read_bytes()), ref, CARVEOUTS)}
|
||||
for f in ("TranTimeofPeak", "VertTimeofPeak", "LongTimeofPeak", "MicLTimeofPeak",
|
||||
"PeakVectorSumTimeSum", "TranPeakAcceleration", "VertPeakAcceleration",
|
||||
"LongPeakAcceleration"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
@@ -0,0 +1,80 @@
|
||||
"""DeviceAccess routes call-home by series (phase 4): a read, and an audited
|
||||
change that is never retried, verified over a short config window (3 reads,
|
||||
1 s apart), not the monitoring one."""
|
||||
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 FakeMiniMateClient, FakeMicromateClient, um12947_call_home # noqa: E402
|
||||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||||
from sfm.device_access.errors import DeviceError # noqa: E402
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
|
||||
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
|
||||
TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, 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(*, s4=None, s3=None, sleeps=None):
|
||||
return DeviceAccess(s4_client_factory=lambda a, **kw: s4, s3_client_factory=lambda a, **kw: s3,
|
||||
start_reaper=False, audit=Audit(),
|
||||
sleep=(sleeps.append if sleeps is not None else (lambda s: None)),
|
||||
verify_timeout_s=60.0, verify_interval_s=5.0)
|
||||
|
||||
|
||||
def test_call_home_state_dispatches_by_series():
|
||||
assert access(s4=FakeMicromateClient()).call_home_state(ADDR, "UM20147").series == 4
|
||||
assert access(s3=FakeMiniMateClient()).call_home_state(TCP3, "BE18193").series == 3
|
||||
|
||||
|
||||
def test_set_call_home_dispatches_by_series():
|
||||
s4 = FakeMicromateClient()
|
||||
r = access(s4=s4).set_call_home(ADDR, "UM20147", enabled=False)
|
||||
assert (r.series, r.outcome, r.verified) == (4, "sent", "ok") and len(s4.executed) == 1
|
||||
s3 = FakeMiniMateClient()
|
||||
r = access(s3=s3).set_call_home(TCP3, "BE18193", enabled=False)
|
||||
assert (r.series, r.outcome, r.verified) == (3, "sent", "ok") and s3.writes == ["call_home"]
|
||||
|
||||
|
||||
def test_the_verify_window_is_the_config_one_not_the_monitoring_one():
|
||||
sleeps = []
|
||||
s4 = FakeMicromateClient()
|
||||
s4.protocol.execute = lambda plan: [type("Ack", (), {"sub": st.ack_sub, "data": bytes(11)})()
|
||||
for st in plan.steps] # acked, but nothing changes
|
||||
r = access(s4=s4, sleeps=sleeps).set_call_home(ADDR, "UM20147", enabled=False)
|
||||
assert (r.outcome, r.verified) == ("failed", "mismatch")
|
||||
assert sleeps == [1.0, 1.0, 1.0]
|
||||
|
||||
|
||||
def test_set_call_home_on_a_dropped_held_line_is_not_retried():
|
||||
fake = FakeMicromateClient(call_home=um12947_call_home(True))
|
||||
da = access(s4=fake)
|
||||
da.status(ADDR, "UM20147") # hold the line
|
||||
fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails
|
||||
with pytest.raises(DeviceError): # the failure, not a retry
|
||||
da.set_call_home(ADDR, "UM20147", enabled=False)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_a_dry_run_needs_no_audit():
|
||||
da = DeviceAccess(s4_client_factory=lambda a, **kw: FakeMicromateClient(), start_reaper=False,
|
||||
audit=None, sleep=lambda s: None)
|
||||
assert da.set_call_home(ADDR, "UM20147", enabled=False, dry_run=True).outcome == "dry_run"
|
||||
@@ -0,0 +1,88 @@
|
||||
"""run_change is kind-agnostic (phase 4): a ChangeKind names the change and the
|
||||
state that means it took, so call-home rides the audited path start/stop uses.
|
||||
Fake callables only -- no device."""
|
||||
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 sfm.device_access.change import ( # noqa: E402
|
||||
ChangeKind, call_home_change, monitoring_change, run_change,
|
||||
)
|
||||
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 change(kind, states, *, verify=(6.0, 2.0), snapshot=None, audit=None):
|
||||
states = list(states)
|
||||
audit = audit or Audit()
|
||||
result = run_change(
|
||||
kind=kind, serial="UM20147", series=4, dry_run=False, even_if_already=False,
|
||||
audit=audit, address=ADDR, caller="test", sleep=lambda s: None,
|
||||
verify_timeout_s=verify[0], verify_interval_s=verify[1],
|
||||
read_serial=lambda: "UM20147",
|
||||
read_state=lambda: states.pop(0) if len(states) > 1 else states[0],
|
||||
describe_plan=lambda: {"steps": []}, send=lambda: {"subs": ["0x81"]},
|
||||
snapshot=snapshot)
|
||||
return result, audit
|
||||
|
||||
|
||||
def test_monitoring_kinds_are_todays_names():
|
||||
assert monitoring_change(True) == ChangeKind("start monitoring", "monitoring", "started")
|
||||
assert monitoring_change(False) == ChangeKind("stop monitoring", "idle", "stopped")
|
||||
|
||||
|
||||
def test_call_home_kinds():
|
||||
assert call_home_change(True) == ChangeKind("enable call-home", "enabled", "enabled")
|
||||
assert call_home_change(False) == ChangeKind("disable call-home", "disabled", "disabled")
|
||||
|
||||
|
||||
def test_a_call_home_change_is_verified_by_its_own_state():
|
||||
r, _ = change(call_home_change(False), ["enabled", "disabled"])
|
||||
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "disabled")
|
||||
assert r.action == "disable call-home"
|
||||
|
||||
|
||||
def test_a_call_home_read_back_that_did_not_change_is_a_mismatch():
|
||||
r, _ = change(call_home_change(False), ["enabled"] * 4, verify=(3.0, 1.0))
|
||||
assert (r.outcome, r.verified) == ("failed", "mismatch")
|
||||
|
||||
|
||||
def test_the_snapshot_is_kept_in_the_result_and_the_audit():
|
||||
r, audit = change(call_home_change(False), ["enabled", "disabled"], snapshot=lambda: {"after": "ab"})
|
||||
assert r.detail["snapshot"] == {"after": "ab"}
|
||||
((_, row),) = audit.rows.items()
|
||||
assert row["states"]["snapshot"] == {"after": "ab"}
|
||||
|
||||
|
||||
def test_a_failing_snapshot_does_not_change_the_outcome():
|
||||
def broken():
|
||||
raise RuntimeError("x")
|
||||
r, _ = change(call_home_change(False), ["enabled", "disabled"], snapshot=broken)
|
||||
assert (r.outcome, r.verified) == ("sent", "ok")
|
||||
assert r.detail["snapshot"] == {"error": "x"}
|
||||
|
||||
|
||||
def test_no_snapshot_leaves_the_result_as_before():
|
||||
r, audit = change(monitoring_change(True), ["idle", "monitoring"])
|
||||
assert "snapshot" not in r.detail
|
||||
((_, row),) = audit.rows.items()
|
||||
assert "snapshot" not in row["states"]
|
||||
@@ -11,7 +11,7 @@ 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,
|
||||
ConnectFailed, MalformedReply, NoAnswer, UnitStateUnknown, WrongUnit,
|
||||
)
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s3 import Series3Adapter # noqa: E402
|
||||
@@ -51,20 +51,20 @@ def test_status_maps_monitor_status():
|
||||
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_reads_the_logical_block():
|
||||
# Phase 5: the settings come from the 1A read assembled into its 2,090 bytes and
|
||||
# decoded by micromate.setup_fields (tests/test_device_access_s3_settings.py has
|
||||
# the rest); the fake's block is BE9441's of 2026-10-26.
|
||||
fake = FakeMiniMateClient()
|
||||
s = adapter(fake).settings(TCP, "BE18193")
|
||||
assert (s.record_mode, s.sample_rate, s.setup_name) == ("Histogram", 4096, "Standard Recording Setup.set")
|
||||
assert fake.calls.index("connect") < fake.calls.index("read_compliance_content")
|
||||
|
||||
|
||||
def test_settings_without_a_compliance_read_is_a_malformed_reply_and_not_retried():
|
||||
def test_settings_of_a_monitoring_unit_is_refused_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")
|
||||
with pytest.raises(UnitStateUnknown, match="settings"):
|
||||
adapter(FakeMiniMateClient(monitoring_settings=True)).settings(TCP, "BE18193")
|
||||
|
||||
|
||||
def test_a_cold_unit_over_tcp_gets_one_retry():
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Changing a MiniMate's settings by serial (phase 5): preview, one audited send,
|
||||
read back. The settings block is the 1A read assembled into its 2,090 logical
|
||||
bytes; the write is push_config_raw's Blastware sequence (68 73 | 71 x n 72 |
|
||||
82 83 | 69 74 72) with the event index, trigger and waveform blocks sent back as
|
||||
read. Fixture blocks: BE9441, 2026-10-26."""
|
||||
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 mp # noqa: E402
|
||||
from device_access_fakes import FakeMiniMateClient, s3_settings_blocks # noqa: E402
|
||||
from micromate.setup_fields import encode_setup, field_values # noqa: E402
|
||||
from minimateplus.client import MiniMateClient # noqa: E402
|
||||
from minimateplus.protocol import ImageRefused # noqa: E402
|
||||
from sfm.device_access.errors import ( # noqa: E402
|
||||
BadRequest, DeviceError, SettingsChanged, UnitStateUnknown,
|
||||
)
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s3 import Series3Adapter # noqa: E402
|
||||
|
||||
TCP = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
|
||||
BW_ORDER = ["0x68", "0x73", "0x71", "0x72", "0x82", "0x83", "0x69", "0x74", "0x72"]
|
||||
|
||||
|
||||
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 adapter(fake):
|
||||
return Series3Adapter(client_factory=lambda address, **kw: fake)
|
||||
|
||||
|
||||
def change(fake, changes, *, revision=None, dry_run=False, audit=None):
|
||||
return adapter(fake).change_settings(
|
||||
TCP, "BE18193", changes=changes, revision=revision, dry_run=dry_run,
|
||||
audit=audit if audit is not None else Audit(), caller="test", sleep=lambda s: None,
|
||||
verify_timeout_s=2.0, verify_interval_s=1.0)
|
||||
|
||||
|
||||
def live(fake, changes, audit=None):
|
||||
rev = change(fake, changes, dry_run=True).plan["revision"]
|
||||
return change(fake, changes, revision=rev, audit=audit)
|
||||
|
||||
|
||||
def test_s3_settings_read_uses_the_codec():
|
||||
s = adapter(FakeMiniMateClient()).settings(TCP, "BE18193")
|
||||
assert (s.record_mode, s.sample_rate, s.histogram_interval_s) == ("Histogram", 4096, 2)
|
||||
assert (s.record_time_s, s.geo_trigger_ips) == (20.0, 0.04)
|
||||
assert s.notes["Project"] == "TestUnit-Minimate" and s.notes["Client"] == "Terra-Mechanics"
|
||||
assert s.detail["record_mode_code"] == 0x03 and s.detail["geo_range"] == "normal"
|
||||
fields = {d["field"]: d for d in s.detail["editable"]}
|
||||
assert fields["geo_range"]["value"] == "normal" and fields["note_1"]["label"] == "Project"
|
||||
|
||||
|
||||
def test_s3_settings_read_of_a_monitoring_unit_says_why():
|
||||
with pytest.raises(UnitStateUnknown, match="stop monitoring first"):
|
||||
adapter(FakeMiniMateClient(monitoring_settings=True)).settings(TCP, "BE18193")
|
||||
|
||||
|
||||
def test_s3_dry_run_previews_and_sends_nothing():
|
||||
fake = FakeMiniMateClient()
|
||||
r = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True)
|
||||
assert r.outcome == "dry_run" and fake.writes == []
|
||||
assert r.plan["fields"] == {"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.04, "new": 0.05}}
|
||||
assert [s["sub"] for s in r.plan["steps"]] == BW_ORDER
|
||||
assert any("00 00" in w for w in r.plan["warnings"]) and r.plan["blocked"] == []
|
||||
assert len(r.plan["revision"]) == 16
|
||||
|
||||
|
||||
def test_s3_trigger_change_sends_the_units_own_blocks():
|
||||
fake = FakeMiniMateClient()
|
||||
blocks = s3_settings_blocks()
|
||||
live(fake, {"geo_trigger_ips": 0.05})
|
||||
event_index, compliance, trigger, waveform = fake.pushed
|
||||
assert (event_index, trigger, waveform) == (blocks["event_index"], blocks["trigger"], blocks["waveform"])
|
||||
assert compliance == encode_setup(blocks["compliance"], 3, {"geo_trigger_ips": 0.05})
|
||||
|
||||
|
||||
def test_s3_change_verifies_by_read_back():
|
||||
fake = FakeMiniMateClient()
|
||||
r = live(fake, {"geo_trigger_ips": 0.05, "note_4": "Loc 2 - north wall"})
|
||||
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "as asked")
|
||||
rows = r.detail["snapshot"]["fields"]
|
||||
assert rows["geo_trigger_ips"] == {"label": "Geophone trigger", "old": 0.04, "new": 0.05, "now": 0.05}
|
||||
assert rows["note_4"]["now"] == "Loc 2 - north wall"
|
||||
assert field_values(fake.settings_blocks["compliance"], 3)["geo_trigger_ips"] == 0.05
|
||||
|
||||
|
||||
def test_s3_stale_revision_sends_nothing():
|
||||
fake = FakeMiniMateClient()
|
||||
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
|
||||
fake.settings_blocks["compliance"] = encode_setup(fake.settings_blocks["compliance"], 3, {"job_number": 9})
|
||||
audit = Audit()
|
||||
with pytest.raises(SettingsChanged):
|
||||
change(fake, {"geo_trigger_ips": 0.05}, revision=rev, audit=audit)
|
||||
assert fake.writes == [] and audit.rows == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dry_run", [True, False])
|
||||
def test_s3_monitoring_is_refused(dry_run):
|
||||
fake = FakeMiniMateClient(monitoring_settings=True)
|
||||
with pytest.raises(UnitStateUnknown) as e:
|
||||
change(fake, {"geo_trigger_ips": 0.05}, revision="x", dry_run=dry_run)
|
||||
assert "stop monitoring first" in str(e.value) and "nothing sent" in str(e.value)
|
||||
assert fake.writes == []
|
||||
|
||||
|
||||
def test_s3_a_value_the_unit_does_not_allow_is_a_bad_request():
|
||||
with pytest.raises(BadRequest):
|
||||
change(FakeMiniMateClient(), {"record_time_s": 30.0}, dry_run=True) # 4096 sps: 26 s at most
|
||||
|
||||
|
||||
def test_s3_a_refused_image_is_audited_as_nothing_sent():
|
||||
audit = Audit()
|
||||
fake = FakeMiniMateClient(write_error=ImageRefused("write SUB 0x71: not a whole block"))
|
||||
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
|
||||
with pytest.raises(DeviceError):
|
||||
change(fake, {"geo_trigger_ips": 0.05}, revision=rev, audit=audit)
|
||||
((_, row),) = audit.rows.items()
|
||||
assert (row["outcome"], row["sent"]) == ("failed", 0)
|
||||
assert row["error"].startswith("refused before sending")
|
||||
|
||||
|
||||
class _Recorder:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def write(self, data):
|
||||
self.sent.append(bytes(data))
|
||||
|
||||
def read(self, n):
|
||||
return b""
|
||||
|
||||
|
||||
def test_push_config_raw_precheck_raises_image_refused():
|
||||
t = _Recorder()
|
||||
c = MiniMateClient("unused")
|
||||
c._proto = mp.MiniMateProtocol(t, recv_timeout=0.2)
|
||||
b = s3_settings_blocks()
|
||||
with pytest.raises(ImageRefused):
|
||||
c.push_config_raw(b["event_index"], b["compliance"][:2089], b["trigger"], b["waveform"])
|
||||
assert t.sent == []
|
||||
|
||||
|
||||
# Final review #1: the revision covers the changes previewed, not only the unit.
|
||||
def test_s3_a_revision_covers_the_changes_previewed():
|
||||
fake = FakeMiniMateClient()
|
||||
rev = change(fake, {"job_number": 7}, dry_run=True).plan["revision"]
|
||||
with pytest.raises(SettingsChanged):
|
||||
change(fake, {"geo_trigger_ips": 0.05}, revision=rev)
|
||||
assert fake.writes == []
|
||||
|
||||
|
||||
# Ruling: the trigger block's byte 5 "differs by unit and session" (#46); the three
|
||||
# echoed blocks are re-read at send and sent as read, so they are not in the revision.
|
||||
def test_s3_an_echoed_block_moving_does_not_stale_the_preview():
|
||||
fake = FakeMiniMateClient()
|
||||
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
|
||||
trig = bytearray(fake.settings_blocks["trigger"])
|
||||
trig[5] = 0x03
|
||||
fake.settings_blocks["trigger"] = bytes(trig)
|
||||
assert change(fake, {"geo_trigger_ips": 0.05}, revision=rev).verified == "ok"
|
||||
assert fake.pushed[2] == bytes(trig) # sent as read at send time
|
||||
|
||||
|
||||
# Final review #4 (spec): the refusal says a stop makes the unit call in.
|
||||
def test_s3_monitoring_refusal_says_a_stop_calls_in():
|
||||
with pytest.raises(UnitStateUnknown) as e:
|
||||
change(FakeMiniMateClient(monitoring_settings=True), {"geo_trigger_ips": 0.05}, dry_run=True)
|
||||
assert "call in" in str(e.value) and "call-home" in str(e.value)
|
||||
|
||||
|
||||
# Final review #3: the blocks are logical bytes; a block holding a literal
|
||||
# 10 02 / 10 03 / 10 04 (job number 4098 = 0x1002) must be written intact, and a
|
||||
# block the write would refuse must show in the preview, not only at Send.
|
||||
def test_s3_a_bad_echoed_block_is_blocked_in_the_preview():
|
||||
fake = FakeMiniMateClient()
|
||||
fake.settings_blocks["event_index"] = fake.settings_blocks["event_index"][:-1]
|
||||
r = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True)
|
||||
assert r.plan["blocked"] and r.plan["steps"] == []
|
||||
from sfm.device_access.errors import ChangeRefused
|
||||
with pytest.raises(ChangeRefused):
|
||||
change(fake, {"geo_trigger_ips": 0.05}, revision=r.plan["revision"])
|
||||
assert fake.writes == []
|
||||
|
||||
|
||||
def _acking():
|
||||
from minimateplus.framing import build_bw_write_frame # noqa: F401 (frames are parsed below)
|
||||
from test_minimate_write_frames import _payload
|
||||
|
||||
class Acks:
|
||||
def __init__(self):
|
||||
self.sent, self._buf = [], b""
|
||||
|
||||
def write(self, data):
|
||||
data = bytes(data)
|
||||
self.sent.append(data)
|
||||
sub = _payload(data)[2]
|
||||
body = bytes([0x00, 0x10, 0xFF - sub, 0x00, 0x00]) + bytes(11)
|
||||
body += bytes([sum(body) & 0xFF])
|
||||
self._buf += b"\x10\x02" + body.replace(b"\x10", b"\x10\x10") + b"\x03"
|
||||
|
||||
def read(self, n):
|
||||
out, self._buf = self._buf[:n], self._buf[n:]
|
||||
return out
|
||||
return Acks()
|
||||
|
||||
|
||||
def test_push_config_raw_writes_a_logical_block_with_a_literal_escape_byte_intact():
|
||||
from test_minimate_write_frames import _payload
|
||||
t = _acking()
|
||||
c = MiniMateClient("unused")
|
||||
c._proto = mp.MiniMateProtocol(t, recv_timeout=0.5)
|
||||
b = s3_settings_blocks()
|
||||
block = encode_setup(b["compliance"], 3, {"job_number": 4098}) # [40:42] = 10 02
|
||||
assert block[40:42] == b"\x10\x02"
|
||||
c.push_config_raw(b["event_index"], block, b["trigger"], b["waveform"])
|
||||
sent = b"".join(_payload(f)[16:] for f in t.sent if _payload(f)[2] == 0x71)
|
||||
assert sent == block + b"\x00\x00"
|
||||
|
||||
|
||||
# Bench 2026-11-04 (BE9441): a write sent while the unit's setup menu was open was
|
||||
# acknowledged and read back -- and then lost when the operator pressed Cancel or
|
||||
# Save: the menu writes its own copy of the WHOLE block back. The preview says so.
|
||||
def test_the_preview_warns_that_an_open_setup_menu_loses_the_change():
|
||||
r = change(FakeMiniMateClient(), {"geo_trigger_ips": 0.05}, dry_run=True)
|
||||
assert any("setup menu" in w and "lost" in w for w in r.plan["warnings"])
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Series 4 call-home: read the enable bit and dial string, and change it through
|
||||
the audited path (phase 4). The frames are micromate.writes' (equal to THOR's
|
||||
for UM12947); [118:120] is unit-maintained and moves after any config write."""
|
||||
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 FakeMicromateClient, um12947_call_home # noqa: E402
|
||||
from micromate.opcodes import ENABLEABLE_WRITES # noqa: E402
|
||||
from micromate.writes import plan_call_home_enabled # noqa: E402
|
||||
from sfm.device_access.errors import CallHomeInProgress # noqa: E402
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s4 import s4_call_home_state, s4_change_call_home # 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 change(fake, *, enabled, dry_run=False, even_if_already=False):
|
||||
return s4_change_call_home(fake, "UM20147", enabled=enabled, dry_run=dry_run,
|
||||
even_if_already=even_if_already, audit=Audit(), address=ADDR,
|
||||
caller="test", sleep=lambda s: None,
|
||||
verify_timeout_s=3.0, verify_interval_s=1.0)
|
||||
|
||||
|
||||
def test_call_home_writes_are_now_enableable():
|
||||
assert {0x7E, 0x7F} <= ENABLEABLE_WRITES
|
||||
|
||||
|
||||
def test_s4_call_home_state_reads_the_enable_bit_and_dial_string():
|
||||
st = s4_call_home_state(FakeMicromateClient(), "UM20147")
|
||||
assert (st.serial, st.series, st.enabled, st.dial_string) == ("UM20147", 4, True, "RADIO RING")
|
||||
assert st.detail["byte5"] == "0x05"
|
||||
assert st.detail["block"] == um12947_call_home().hex()
|
||||
assert s4_call_home_state(FakeMicromateClient(call_home=um12947_call_home(False)), "UM20147").enabled is False
|
||||
|
||||
|
||||
def test_s4_dry_run_shows_thors_frames():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=False, dry_run=True)
|
||||
assert r.outcome == "dry_run"
|
||||
assert r.plan["steps"] == plan_call_home_enabled(um12947_call_home(), False).describe()["steps"]
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_disable_sends_7e_7f_and_verifies():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=False)
|
||||
assert (r.outcome, r.verified, r.state_after, r.action) == ("sent", "ok", "disabled", "disable call-home")
|
||||
assert [st.sub for st in fake.executed[0].steps] == [0x7E, 0x7F]
|
||||
assert fake.call_home[5] == 0x04
|
||||
|
||||
|
||||
def test_s4_unit_maintained_bytes_do_not_make_a_mismatch():
|
||||
r = change(FakeMicromateClient(), enabled=False)
|
||||
assert r.verified == "ok"
|
||||
snap = r.detail["snapshot"]
|
||||
assert snap["changed_offsets"] == [5, 118, 119]
|
||||
assert snap["before"] == um12947_call_home().hex() and snap["after"] != snap["before"]
|
||||
|
||||
|
||||
def test_s4_no_change_while_calling_home():
|
||||
fake = FakeMicromateClient(run_states=[0x03])
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
change(fake, enabled=False)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_already_enabled_is_skipped():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=True)
|
||||
assert r.outcome == "skipped" and fake.executed == []
|
||||
|
||||
|
||||
def test_s4_even_if_already_sends_the_no_op_write():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=True, even_if_already=True)
|
||||
assert len(fake.executed) == 1
|
||||
assert any("changes nothing" in w for w in r.plan["warnings"])
|
||||
|
||||
|
||||
|
||||
def test_s4_unknown_run_state_sends_nothing():
|
||||
# Final review #3: a run state never measured is refused, as start/stop does.
|
||||
from sfm.device_access.errors import UnitStateUnknown
|
||||
fake = FakeMicromateClient(run_states=[0x07])
|
||||
with pytest.raises(UnitStateUnknown):
|
||||
change(fake, enabled=False)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_a_lost_ack_still_records_what_the_unit_holds():
|
||||
# Final review #4: the lost-ack path is where the operator most needs it.
|
||||
import micromate.protocol as mm_proto
|
||||
fake = FakeMicromateClient(execute_error=mm_proto.TimeoutError("lost"))
|
||||
r = change(fake, enabled=False)
|
||||
assert (r.outcome, r.sent) == ("failed", True)
|
||||
snap = r.detail["snapshot"]
|
||||
assert snap["changed_offsets"] == [] and snap["before"] == snap["after"] # the write did not land
|
||||
|
||||
|
||||
|
||||
# Measured at the bench 2026-11-03 (UM20147): a MONITORING Micromate returns its
|
||||
# real call-home block and ACKS a write, but does not apply it -- its own menu says
|
||||
# "Feature disabled while monitoring". SFM refuses up front and says why, rather
|
||||
# than send a write the unit will ignore.
|
||||
|
||||
@pytest.mark.parametrize("dry_run", [True, False])
|
||||
def test_s4_call_home_is_refused_while_monitoring(dry_run):
|
||||
from sfm.device_access.errors import UnitStateUnknown
|
||||
fake = FakeMicromateClient(run_states=[0x02])
|
||||
with pytest.raises(UnitStateUnknown) as e:
|
||||
change(fake, enabled=False, dry_run=dry_run)
|
||||
msg = str(e.value)
|
||||
assert "monitoring" in msg and "stop" in msg and "nothing sent" in msg
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
# The block's header is its own length (00 7C, N = 124); SFM flips a bit only in a
|
||||
# block that carries it, never in whatever 126 bytes came back.
|
||||
|
||||
def test_s4_a_block_that_is_not_the_call_home_block_sends_nothing():
|
||||
from sfm.device_access.errors import UnitStateUnknown
|
||||
fake = FakeMicromateClient(call_home=bytes(126))
|
||||
with pytest.raises(UnitStateUnknown) as e:
|
||||
change(fake, enabled=False)
|
||||
assert "not its call-home block" in str(e.value)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_state_of_a_block_that_is_not_the_call_home_block_says_why():
|
||||
st = s4_call_home_state(FakeMicromateClient(call_home=bytes(126)), "UM20147")
|
||||
assert st.enabled is None and "not its call-home block" in st.detail["reason"]
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Changing a Micromate's settings by serial (phase 5): preview, one audited send,
|
||||
read back. The push is micromate.writes.plan_setup_push (THOR's frames) under
|
||||
the active setup's own name; the unit's schedule is read first, because a
|
||||
scheduled start loads the setup it names and would undo a change to another."""
|
||||
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, schedule_record # noqa: E402
|
||||
from micromate.opcodes import ENABLEABLE_WRITES # noqa: E402
|
||||
from micromate.setup_fields import field_values # noqa: E402
|
||||
from sfm.device_access.errors import ( # noqa: E402
|
||||
BadRequest, ChangeRefused, SettingsChanged, UnitStateUnknown,
|
||||
)
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s4 import s4_change_settings, s4_settings # noqa: E402
|
||||
|
||||
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
|
||||
PUSH_SUBS = [0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72]
|
||||
|
||||
|
||||
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 change(fake, changes, *, revision=None, dry_run=False, audit=None):
|
||||
return s4_change_settings(fake, "UM20147", changes=changes, revision=revision, dry_run=dry_run,
|
||||
audit=audit if audit is not None else Audit(), address=ADDR,
|
||||
caller="test", sleep=lambda s: None,
|
||||
verify_timeout_s=2.0, verify_interval_s=1.0)
|
||||
|
||||
|
||||
def live(fake, changes, audit=None):
|
||||
rev = change(fake, changes, dry_run=True).plan["revision"]
|
||||
return change(fake, changes, revision=rev, audit=audit)
|
||||
|
||||
|
||||
def test_setup_push_subs_are_now_enableable():
|
||||
assert set(PUSH_SUBS) <= ENABLEABLE_WRITES
|
||||
|
||||
|
||||
def test_s4_settings_read_describes_the_editable_fields():
|
||||
st = s4_settings(FakeMicromateClient(), "UM20147")
|
||||
fields = {d["field"]: d for d in st.detail["editable"]}
|
||||
assert fields["geo_trigger_ips"]["value"] == 0.5 and "geo_range" not in fields
|
||||
|
||||
|
||||
def test_s4_dry_run_previews_old_to_new_and_sends_nothing():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
assert r.outcome == "dry_run"
|
||||
assert r.plan["fields"] == {"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.5, "new": 0.3}}
|
||||
assert len(r.plan["revision"]) == 16 and r.plan["blocked"] == []
|
||||
assert [s["sub"] for s in r.plan["steps"]] == [f"0x{s:02X}" for s in PUSH_SUBS]
|
||||
assert any("edit buffer" in w for w in r.plan["warnings"])
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_trigger_change_sends_the_push_and_verifies():
|
||||
fake = FakeMicromateClient()
|
||||
r = live(fake, {"geo_trigger_ips": 0.3})
|
||||
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "as asked")
|
||||
assert [st.sub for st in fake.executed[0].steps] == PUSH_SUBS
|
||||
assert field_values(fake.setup, 4)["geo_trigger_ips"] == 0.3
|
||||
assert r.detail["snapshot"]["fields"]["geo_trigger_ips"] == {
|
||||
"label": "Geophone trigger", "old": 0.5, "new": 0.3, "now": 0.3}
|
||||
name_step = fake.executed[0].steps[0]
|
||||
assert name_step.data.rstrip(b"\x00") == b"TEST1.mmb" # the active setup's own name
|
||||
|
||||
|
||||
def test_s4_stale_revision_sends_nothing():
|
||||
fake = FakeMicromateClient()
|
||||
rev = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True).plan["revision"]
|
||||
fake.setup = FakeMicromateClient(setup=None).setup[:40] + b"\x00\x07" + fake.setup[42:] # job number moved
|
||||
audit = Audit()
|
||||
with pytest.raises(SettingsChanged):
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision=rev, audit=audit)
|
||||
assert fake.executed == [] and audit.rows == {}
|
||||
|
||||
|
||||
def test_s4_already_as_asked_is_skipped():
|
||||
fake = FakeMicromateClient()
|
||||
r = live(fake, {"geo_trigger_ips": 0.5})
|
||||
assert r.outcome == "skipped" and fake.executed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dry_run", [True, False])
|
||||
def test_s4_monitoring_is_refused(dry_run):
|
||||
fake = FakeMicromateClient(run_states=[0x02])
|
||||
with pytest.raises(UnitStateUnknown) as e:
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision="x", dry_run=dry_run)
|
||||
assert "stop it first" in str(e.value) and "nothing sent" in str(e.value)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_a_value_the_unit_does_not_allow_is_a_bad_request():
|
||||
with pytest.raises(BadRequest):
|
||||
change(FakeMicromateClient(), {"geo_trigger_ips": 12.0}, dry_run=True)
|
||||
|
||||
|
||||
def test_s4_factory_setup_is_refused_live_and_shown_in_preview():
|
||||
fake = FakeMicromateClient(active_name="factory.MMB")
|
||||
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
assert any("factory setup" in b for b in r.plan["blocked"]) and r.plan["steps"] == []
|
||||
with pytest.raises(ChangeRefused):
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_schedule_conflict_blocks():
|
||||
fake = FakeMicromateClient(schedule_body=schedule_record(14, 0x02, "other.mmb") + bytes(264))
|
||||
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
assert any("other.mmb" in b and "07:00" in b for b in r.plan["blocked"])
|
||||
with pytest.raises(ChangeRefused) as e:
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
|
||||
assert "nothing sent" in str(e.value) and fake.executed == []
|
||||
|
||||
|
||||
def test_s4_schedule_on_the_active_setup_warns_only():
|
||||
fake = FakeMicromateClient(schedule_body=schedule_record(14, 0x02, "test1.MMB")
|
||||
+ schedule_record(37, 0x04) + bytes(4))
|
||||
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
assert r.plan["blocked"] == [] and any("survives" in w and "07:00" in w for w in r.plan["warnings"])
|
||||
assert live(fake, {"geo_trigger_ips": 0.3}).verified == "ok"
|
||||
|
||||
|
||||
def test_an_unreadable_schedule_refuses():
|
||||
fake = FakeMicromateClient(schedule_error=mm_proto.ProtocolError("no reply to 0x94"))
|
||||
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
assert any("could not read this unit's schedule" in b for b in r.plan["blocked"])
|
||||
with pytest.raises(ChangeRefused):
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_no_schedule_records_is_no_conflict():
|
||||
r = live(FakeMicromateClient(), {"geo_trigger_ips": 0.3})
|
||||
assert r.verified == "ok"
|
||||
|
||||
|
||||
def test_s4_a_lost_ack_records_what_the_unit_holds():
|
||||
fake = FakeMicromateClient(execute_error=mm_proto.TimeoutError("lost"))
|
||||
r = live(fake, {"geo_trigger_ips": 0.3})
|
||||
assert (r.outcome, r.sent) == ("failed", True)
|
||||
snap = r.detail["snapshot"]
|
||||
assert snap["fields"]["geo_trigger_ips"]["now"] == 0.5 and snap["changed_offsets"] == []
|
||||
|
||||
|
||||
def test_s4_unseen_block_size_is_blocked():
|
||||
fake = FakeMicromateClient()
|
||||
fake.prefs = fake.prefs + b"\x00"
|
||||
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
assert any("has not seen a block like it" in b for b in r.plan["blocked"])
|
||||
with pytest.raises(ChangeRefused):
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
# Final review #1: the revision covers the changes previewed, not only the unit.
|
||||
def test_s4_a_revision_covers_the_changes_previewed():
|
||||
fake = FakeMicromateClient()
|
||||
rev = change(fake, {"job_number": 7}, dry_run=True).plan["revision"]
|
||||
with pytest.raises(SettingsChanged):
|
||||
change(fake, {"geo_trigger_ips": 0.3}, revision=rev)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
# Ruling (final review, declined-to-judge): the blocks a push only echoes are
|
||||
# re-read at send and sent as read, so they are not part of the revision.
|
||||
def test_s4_an_echoed_block_moving_does_not_stale_the_preview():
|
||||
fake = FakeMicromateClient()
|
||||
rev = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True).plan["revision"]
|
||||
from micromate.setup_block import with_crc
|
||||
prefs = bytearray(fake.prefs)
|
||||
prefs[31] ^= 0x01
|
||||
fake.prefs = with_crc(bytes(prefs))
|
||||
assert change(fake, {"geo_trigger_ips": 0.3}, revision=rev).verified == "ok"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""DeviceAccess.change_settings (phase 5): the series-independent entry point --
|
||||
what it refuses before any I/O, and that it dispatches a change (never retried)."""
|
||||
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 FakeMiniMateClient, FakeMicromateClient # noqa: E402
|
||||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||||
from sfm.device_access.errors import BadRequest, NotSupported # noqa: E402
|
||||
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 _never(*a, **kw):
|
||||
raise AssertionError("no connection may be opened")
|
||||
|
||||
|
||||
def _access(s3=_never, s4=_never, audit="default"):
|
||||
return DeviceAccess(s3_client_factory=s3, s4_client_factory=s4, start_reaper=False,
|
||||
audit=Audit() if audit == "default" else audit, sleep=lambda s: None)
|
||||
|
||||
|
||||
def test_live_change_without_revision_is_refused_before_io():
|
||||
with pytest.raises(BadRequest, match="preview first"):
|
||||
_access().change_settings(ADDR, "UM20147", changes={"job_number": 7}, revision=None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [{}, None, "job_number=7"])
|
||||
def test_empty_changes_is_a_bad_request(changes):
|
||||
with pytest.raises(BadRequest):
|
||||
_access().change_settings(ADDR, "BE18193", changes=changes, revision="r", dry_run=True)
|
||||
|
||||
|
||||
def test_a_live_change_without_an_audit_log_is_refused():
|
||||
with pytest.raises(NotSupported, match="audit"):
|
||||
_access(audit=None).change_settings(ADDR, "BE18193", changes={"job_number": 7}, revision="r")
|
||||
|
||||
|
||||
def test_change_settings_dispatches_by_series_with_change_true(monkeypatch):
|
||||
access = _access(s3=lambda a, **kw: FakeMiniMateClient(), s4=lambda a, **kw: FakeMicromateClient())
|
||||
seen = []
|
||||
real = access._dispatch
|
||||
|
||||
def spy(address, serial, s3_op, s4_op, *, change=False):
|
||||
seen.append((serial, change))
|
||||
return real(address, serial, s3_op, s4_op, change=change)
|
||||
monkeypatch.setattr(access, "_dispatch", spy)
|
||||
r3 = access.change_settings(ADDR, "be18193", changes={"job_number": 7}, revision=None, dry_run=True)
|
||||
r4 = access.change_settings(ADDR, "UM20147", changes={"job_number": 7}, revision=None, dry_run=True)
|
||||
assert (r3.series, r4.series) == (3, 4) and r3.outcome == r4.outcome == "dry_run"
|
||||
assert seen == [("BE18193", True), ("UM20147", True)]
|
||||
+136
-34
@@ -296,9 +296,11 @@ def test_backfill_without_settings_changes_nothing():
|
||||
assert ev.sample_rate is None
|
||||
|
||||
|
||||
# The file path does not yet read a histogram's vector sum the way Blastware does
|
||||
# (the checker's open finding), the mic peak, or a sensitive range, so a live
|
||||
# download keeps the unit's own 0C values for those -- the Series-4 pattern.
|
||||
# Since 2026-11-02 a live download stores what its own file says -- peaks, vector
|
||||
# sum, mic, and the geophone range the event was recorded at -- and the unit's 0C
|
||||
# summary is only the download check. The file's range is the setting when it
|
||||
# recorded; the live 1A is the unit's setting now, which may have changed since.
|
||||
# Only when the file's range does not read (never seen in DL2) does the 1A decide.
|
||||
|
||||
def _with_unit_peaks(dl, *, tran, vert, long, micl, pvs):
|
||||
from minimateplus.models import PeakValues
|
||||
@@ -313,24 +315,99 @@ def _range(geo_range):
|
||||
return cc
|
||||
|
||||
|
||||
def test_a_series3_download_takes_its_peaks_from_the_file_and_its_mic_from_the_unit(sdm):
|
||||
# 2026-10-31: the file now reads a histogram's vector sum as the unit stored it
|
||||
# (0.385 here, as Blastware's report), so the row takes the file's peaks and
|
||||
# vector sum. The unit's 0C summary is read at fixed offsets and can shift
|
||||
# (bench #4 read 0 / -0.0); these believable-but-wrong values must not win.
|
||||
# The mic still comes from the unit: the file reads it as 0.
|
||||
GEO_FIX = Path(__file__).parent / "fixtures" / "geo-range-11-01-26"
|
||||
WRONG = dict(tran=0.21, vert=0.36, long=0.27, micl=0.0009, pvs=0.40) # believable, wrong; clears the old guard
|
||||
|
||||
|
||||
def _download_from(path, serial):
|
||||
from minimateplus.blastware_file import blastware_filename_time
|
||||
when = blastware_filename_time(path.name)
|
||||
return DownloadedEvent(event_id=f"{serial}:01110000:{when:%Y%m%d%H%M%S}", serial=serial, series=3,
|
||||
filename=path.name, verified=None, bw_bytes=path.read_bytes(), timestamp=when)
|
||||
|
||||
|
||||
def _h5_peaks(store, serial, name):
|
||||
from sfm import event_hdf5
|
||||
plot = event_hdf5.plot_json_from_hdf5(store.hdf5_path_for(serial, name))
|
||||
return tuple(max(abs(v) for v in plot["channels"][c]["values"]) for c in ("Tran", "Vert", "Long"))
|
||||
|
||||
|
||||
def _file_range_unread(monkeypatch):
|
||||
# A file whose range does not read: the decoder then assumes Normal.
|
||||
# K441LTON.900 is a Normal file, so its peaks are what such a decode gives.
|
||||
import minimateplus.event_file_io as efi
|
||||
real = efi.decode_blastware_bytes
|
||||
|
||||
def unread(raw, **kw):
|
||||
ev = real(raw, **kw)
|
||||
ev.geo_range = None
|
||||
return ev
|
||||
monkeypatch.setattr(efi, "decode_blastware_bytes", unread)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("compliance", [_range(0), _range(1), None],
|
||||
ids=["unit-says-normal", "unit-says-sensitive", "settings-unread"])
|
||||
def test_a_series3_download_stores_what_its_file_says(sdm, compliance):
|
||||
# K441LTON.900 was recorded in Normal range, whatever the unit is set to now.
|
||||
store, db = sdm
|
||||
dl = _with_unit_peaks(_hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)),
|
||||
tran=0.21, vert=0.36, long=0.27, micl=0.00058, pvs=0.40) # clears the old guard
|
||||
dl.compliance = _range(0) # Normal, confirmed by the unit
|
||||
**WRONG)
|
||||
dl.compliance = compliance
|
||||
row = db.get_event(persist_download(dl, store=store, db=db).db_event_id)
|
||||
assert row["peak_vector_sum"] == pytest.approx(0.3852, abs=1e-4) # Blastware: 0.385
|
||||
assert (row["tran_ppv"], row["vert_ppv"], row["long_ppv"]) == pytest.approx((0.2, 0.385, 0.255), abs=1e-4)
|
||||
assert row["mic_ppv"] == pytest.approx(0.00058, abs=1e-6)
|
||||
assert row["peak_vector_sum"] == pytest.approx(0.3852, abs=1e-4) # Blastware: 0.385
|
||||
assert row["mic_ppv"] == pytest.approx(5.80e-4, abs=2e-6) # Blastware: 106.0 dB(L)
|
||||
assert _h5_peaks(store, "BE9441", "K441LTON.900")[1] == pytest.approx(0.385, abs=0.006)
|
||||
|
||||
|
||||
def test_an_impossible_unit_vector_sum_is_not_kept(sdm):
|
||||
# Bench finding #4: BE9441's 0C read -0.0 for a vector sum whose channels reach 1.08.
|
||||
def test_a_sensitive_waveform_downloaded_with_its_settings_unread_is_blastwares(sdm):
|
||||
# e.g. downloaded while monitoring (the 1A carries no settings). The samples
|
||||
# were scaled as Normal before -- 8x: Vert read 0.44 in the .h5.
|
||||
store, db = sdm
|
||||
dl = _download_from(GEO_FIX / "K557J1KB.RQ0W", "BE9557")
|
||||
row = db.get_event(persist_download(dl, store=store, db=db).db_event_id)
|
||||
assert (row["tran_ppv"], row["vert_ppv"], row["long_ppv"]) == pytest.approx((0.019, 0.055, 0.019), abs=6e-4)
|
||||
assert row["peak_vector_sum"] == pytest.approx(0.061, abs=6e-4) # Blastware's report
|
||||
assert _h5_peaks(store, "BE9557", "K557J1KB.RQ0W") == pytest.approx((0.019, 0.055, 0.019), abs=7e-4)
|
||||
|
||||
|
||||
def test_a_sensitive_histogram_downloaded_with_its_settings_unread_keeps_its_scale(sdm):
|
||||
from minimateplus.event_file_io import decode_blastware_bytes
|
||||
store, db = sdm
|
||||
path = GEO_FIX / "M010HR6K.OA0H"
|
||||
pv = decode_blastware_bytes(path.read_bytes()).peak_values
|
||||
persist_download(_download_from(path, "BE11010"), store=store, db=db)
|
||||
assert _h5_peaks(store, "BE11010", path.name) == pytest.approx((pv.tran, pv.vert, pv.long), abs=7e-4)
|
||||
assert max(_h5_peaks(store, "BE11010", path.name)) < 0.02 # not 8x (Vert would read ~0.07)
|
||||
|
||||
|
||||
def test_when_the_files_range_does_not_read_a_sensitive_units_own_peaks_stand(sdm, monkeypatch):
|
||||
_file_range_unread(monkeypatch)
|
||||
store, db = sdm
|
||||
dl = _with_unit_peaks(_hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)),
|
||||
tran=0.025, vert=0.048, long=0.032, micl=0.0009, pvs=0.0481)
|
||||
dl.compliance = _range(1)
|
||||
row = db.get_event(persist_download(dl, store=store, db=db).db_event_id)
|
||||
assert (row["tran_ppv"], row["vert_ppv"], row["long_ppv"]) == pytest.approx((0.025, 0.048, 0.032), abs=1e-6)
|
||||
assert row["peak_vector_sum"] == pytest.approx(0.0481, abs=1e-6)
|
||||
assert row["mic_ppv"] == pytest.approx(5.80e-4, abs=2e-6) # the mic's scale is not the geophones'
|
||||
assert _h5_peaks(store, "BE9441", "K441LTON.900")[1] == pytest.approx(0.385 / 8, abs=7e-4)
|
||||
|
||||
|
||||
def test_when_the_files_range_does_not_read_and_the_unit_says_normal_the_files_peaks_stand(sdm, monkeypatch):
|
||||
_file_range_unread(monkeypatch)
|
||||
store, db = sdm
|
||||
dl = _with_unit_peaks(_hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)),
|
||||
**WRONG)
|
||||
dl.compliance = _range(0)
|
||||
row = db.get_event(persist_download(dl, store=store, db=db).db_event_id)
|
||||
assert (row["vert_ppv"], row["peak_vector_sum"]) == pytest.approx((0.385, 0.3852), abs=1e-4)
|
||||
|
||||
|
||||
def test_an_impossible_unit_vector_sum_is_not_kept(sdm, monkeypatch):
|
||||
# Bench finding #4: BE9441's 0C read -0.0 for a vector sum whose channels reach
|
||||
# 1.08. The unit's values are used only when neither range reads.
|
||||
_file_range_unread(monkeypatch)
|
||||
store, db = sdm
|
||||
dl = _with_unit_peaks(_hist_download("K441LTOK.R10", "011106a0", datetime.datetime(2026, 10, 26, 16, 6, 37)),
|
||||
tran=0.25, vert=1.08, long=0.195, micl=0.0001, pvs=-0.0)
|
||||
@@ -349,11 +426,12 @@ def test_the_units_range_reaches_the_store(tmp_path):
|
||||
assert store.geo_range == 1
|
||||
|
||||
|
||||
# Review finding (2026-10-29): a histogram's row is stored at its file's time,
|
||||
# a second before the unit's 0C time on most histograms (#51) -- K441LTOK.QZ0
|
||||
# decodes to 16:06:34, its 0C says 16:06:35 -- so a pre-check on the 0C time
|
||||
# alone missed it, and a live download overwrote the watcher's row and sidecar.
|
||||
# The Blastware name encodes the event's own second and does not miss.
|
||||
# Review finding (2026-10-29): a histogram's row was stored at its file's time,
|
||||
# a second before the unit's 0C time (#51) -- K441LTOK.QZ0 decoded to 16:06:34,
|
||||
# its 0C says 16:06:35 -- so a pre-check on the 0C time alone missed it, and a
|
||||
# live download overwrote the watcher's row and sidecar. Since #51 (dev,
|
||||
# 2026-11-03) the file decodes the event's own second, so the time matches too;
|
||||
# the Blastware name, which encodes that second, stays as the second guard.
|
||||
|
||||
@pytest.mark.parametrize("stored_as", ["K441LTOK.QZ0", "K441LTOK.QZ0H"]) # direct / call-in name
|
||||
def test_a_live_histogram_the_watcher_already_stored_writes_nothing(sdm, stored_as):
|
||||
@@ -365,7 +443,7 @@ def test_a_live_histogram_the_watcher_already_stored_writes_nothing(sdm, stored_
|
||||
db.insert_events([ev], serial="BE9441", waveform_records={ev._waveform_key.hex(): rec},
|
||||
device_family="series3") # as the import route (server.py) does
|
||||
[row0] = db.query_events(serial="BE9441")
|
||||
assert row0["timestamp"] != "2026-10-26T16:06:35" # the case: the row sits a second off
|
||||
assert row0["timestamp"] == "2026-10-26T16:06:35" # #51: the event's own second
|
||||
assert row0["blastware_filename"] == stored_as
|
||||
out = persist_download(_hist_download("K441LTOK.QZ0", "01110000",
|
||||
datetime.datetime(2026, 10, 26, 16, 6, 35)), store=store, db=db)
|
||||
@@ -423,19 +501,43 @@ def test_a_letterless_stored_name_still_matches_a_lettered_download(sdm):
|
||||
assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0H")["blastware_filename"] == "K441LTOK.QZ0"
|
||||
|
||||
|
||||
# #51 (dev, 2026-11-03): a waveform and a histogram recorded in the same second
|
||||
# are two events (UNIQUE(serial, timestamp, record_type)). A live download of one
|
||||
# must not be skipped because its twin is stored -- not by the time, and not by a
|
||||
# letterless Blastware name both twins share. An untyped row at that second still
|
||||
# counts as stored (conservatively: it may be this event).
|
||||
|
||||
# The file reader computes every peak as if the unit were in Normal range (10 in/s);
|
||||
# a Sensitive (1.25 in/s) unit's file peaks come out 8x off (the checker's 33
|
||||
# waveforms). So the file's peaks are taken only when the unit's settings confirm
|
||||
# Normal -- the download check's rule; Sensitive or unread keeps the unit's own.
|
||||
def _stored_twin(store, db, name, record_type):
|
||||
ev, rec = store.save_imported_bw((HIST_FIX / "K441LTOK.QZ0").read_bytes(),
|
||||
source_path=Path(name), serial_hint=None,
|
||||
bw_report_text=(HIST_FIX / "K441LTOK_QZ0_ASCII.TXT").read_bytes())
|
||||
ev.record_type = record_type
|
||||
db.insert_events([ev], serial="BE9441", waveform_records={ev._waveform_key.hex(): rec},
|
||||
device_family="series3")
|
||||
|
||||
@pytest.mark.parametrize("compliance", [_range(1), None], ids=["sensitive", "range-unread"])
|
||||
def test_without_a_confirmed_normal_range_the_units_peaks_stand(sdm, compliance):
|
||||
|
||||
@pytest.mark.parametrize("twin_name", ["K441LTOK.QZ0W", "K441LTOK.QZ0"]) # call-in / direct name
|
||||
def test_a_live_histogram_is_stored_beside_its_same_second_waveform_twin(sdm, twin_name):
|
||||
store, db = sdm
|
||||
dl = _with_unit_peaks(_hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)),
|
||||
tran=0.025, vert=0.048, long=0.032, micl=0.00058, pvs=0.0481)
|
||||
dl.compliance = compliance
|
||||
row = db.get_event(persist_download(dl, store=store, db=db).db_event_id)
|
||||
assert (row["tran_ppv"], row["vert_ppv"], row["long_ppv"]) == pytest.approx((0.025, 0.048, 0.032), abs=1e-6)
|
||||
assert row["peak_vector_sum"] == pytest.approx(0.0481, abs=1e-6)
|
||||
assert row["mic_ppv"] == pytest.approx(0.00058, abs=1e-6)
|
||||
_stored_twin(store, db, twin_name, "Waveform")
|
||||
dl = _hist_download("K441LTOK.QZ0", "01110000", datetime.datetime(2026, 10, 26, 16, 6, 35))
|
||||
dl.filename = "K441LTOK.QZ0H" # a live download carries the letter (s3.py: with_type_letter)
|
||||
out = persist_download(dl, store=store, db=db)
|
||||
assert out.inserted is True
|
||||
assert sorted(r["record_type"] for r in db.query_events(serial="BE9441")) == ["Histogram", "Waveform"]
|
||||
|
||||
|
||||
def test_an_untyped_row_at_that_second_still_counts_as_stored(sdm):
|
||||
store, db = sdm
|
||||
_stored_twin(store, db, "K441LTOK.QZ0", None)
|
||||
out = persist_download(_hist_download("K441LTOK.QZ0", "01110000",
|
||||
datetime.datetime(2026, 10, 26, 16, 6, 35)), store=store, db=db)
|
||||
assert out.inserted is False and out.detail["already_stored"] is True
|
||||
|
||||
|
||||
def test_the_name_lookup_can_be_held_to_a_record_type(sdm):
|
||||
store, db = sdm
|
||||
_stored_twin(store, db, "K441LTOK.QZ0", "Waveform")
|
||||
assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0H", record_type="Histogram") is None
|
||||
assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0", record_type="waveform") is not None
|
||||
assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0") is not None
|
||||
@@ -0,0 +1,123 @@
|
||||
"""An event is identified by unit + time + type (#51).
|
||||
|
||||
The events table was unique on (serial, timestamp): one event per unit per
|
||||
second. A unit records a waveform and a histogram in the same second
|
||||
legitimately -- 209 times in prod's 2026-09-30 store once histograms carry
|
||||
Blastware's start -- so the key is now (serial, timestamp, record_type).
|
||||
Agreed with Brian 2026-11-03.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from minimateplus.models import Event, PeakValues, Timestamp # noqa: E402
|
||||
from sfm.database import SeismoDb # noqa: E402
|
||||
|
||||
T = "2026-08-25T10:33:29"
|
||||
T_EARLY = "2026-08-25T10:33:28"
|
||||
|
||||
|
||||
def _event(when: str, rtype: str, key: str = "0111646a", pvs: float = 0.5) -> Event:
|
||||
t = datetime.datetime.fromisoformat(when)
|
||||
ev = Event(index=0)
|
||||
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=t.year, unknown_byte=0, month=t.month,
|
||||
day=t.day, hour=t.hour, minute=t.minute, second=t.second)
|
||||
ev._waveform_key = bytes.fromhex(key)
|
||||
ev.record_type = rtype
|
||||
ev.peak_values = PeakValues(tran=0.1, vert=0.2, long=0.3, peak_vector_sum=pvs, micl=None)
|
||||
return ev
|
||||
|
||||
|
||||
def _store(db: SeismoDb, ev: Event, filename: str) -> tuple:
|
||||
return db.insert_events([ev], serial="BE12844", device_family="series3",
|
||||
waveform_records={ev._waveform_key.hex(): {"filename": filename}})
|
||||
|
||||
|
||||
def _rows(db: SeismoDb) -> list:
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
c.row_factory = sqlite3.Row
|
||||
return [dict(r) for r in c.execute(
|
||||
"SELECT * FROM events ORDER BY timestamp, record_type")]
|
||||
|
||||
|
||||
def _key_sql(db: SeismoDb) -> str:
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
return c.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
||||
).fetchone()[0]
|
||||
|
||||
|
||||
def test_a_waveform_and_a_histogram_can_share_a_second(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
assert _store(db, _event(T, "Waveform"), "N844LQHB.ZT0W") == (1, 0)
|
||||
assert _store(db, _event(T, "Histogram", key="0111700a"), "N844LQHB.ZT0H") == (1, 0)
|
||||
assert [(r["timestamp"], r["record_type"]) for r in _rows(db)] == [
|
||||
(T, "Histogram"), (T, "Waveform")]
|
||||
|
||||
|
||||
def test_the_same_event_twice_is_still_one_row(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(T, "Histogram"), "N844LQHB.ZT0H")
|
||||
assert _store(db, _event(T, "Histogram", pvs=0.8), "N844LQHB.ZT0H") == (0, 1)
|
||||
(row,) = _rows(db)
|
||||
assert row["peak_vector_sum"] == 0.8 # the upsert refreshed it
|
||||
|
||||
|
||||
def test_a_histogram_moves_onto_its_waveforms_second(tmp_path):
|
||||
# What the release backfill does: the histogram was stored a second early;
|
||||
# its corrected start is the waveform's second. The row moves in place.
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(T, "Waveform"), "N844LQHB.ZT0W")
|
||||
_store(db, _event(T_EARLY, "Histogram", key="0111700a"), "N844LQHB.ZS0H")
|
||||
(before,) = [r for r in _rows(db) if r["record_type"] == "Histogram"]
|
||||
assert _store(db, _event(T, "Histogram", key="0111700a"), "N844LQHB.ZS0H") == (0, 1)
|
||||
rows = _rows(db)
|
||||
assert [(r["timestamp"], r["record_type"]) for r in rows] == [(T, "Histogram"), (T, "Waveform")]
|
||||
assert [r["id"] for r in rows if r["record_type"] == "Histogram"] == [before["id"]]
|
||||
|
||||
|
||||
def test_a_re_typed_event_is_corrected_in_place(tmp_path):
|
||||
# Before v0.33.0 the type came from the filename; a re-import with the
|
||||
# file's own type must correct that row, not add a second one.
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(T, "Waveform"), "N844LQHB.ZT0H")
|
||||
(before,) = _rows(db)
|
||||
_store(db, _event(T, "Histogram"), "N844LQHB.ZT0H")
|
||||
(row,) = _rows(db)
|
||||
assert (row["id"], row["record_type"]) == (before["id"], "Histogram")
|
||||
|
||||
|
||||
def test_an_old_database_is_migrated_keeping_every_row_and_id(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(T, "Waveform"), "N844LQHB.ZT0W")
|
||||
_store(db, _event(T_EARLY, "Histogram", key="0111700a"), "N844LQHB.ZS0H")
|
||||
old_rows = _rows(db)
|
||||
with sqlite3.connect(str(db.db_path)) as c: # put the old key back
|
||||
sql = _key_sql(db).replace("UNIQUE(serial, timestamp, record_type)",
|
||||
"UNIQUE(serial, timestamp)")
|
||||
c.executescript(f"""
|
||||
ALTER TABLE events RENAME TO events_new_key;
|
||||
{sql};
|
||||
INSERT INTO events SELECT * FROM events_new_key;
|
||||
DROP TABLE events_new_key;
|
||||
""")
|
||||
assert "UNIQUE(serial, timestamp)" in _key_sql(db)
|
||||
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db") # opening migrates
|
||||
assert "UNIQUE(serial, timestamp, record_type)" in _key_sql(db)
|
||||
assert _rows(db) == old_rows
|
||||
assert _store(db, _event(T, "Histogram", key="0111700b"), "N844LQHC.ZT0H") == (1, 0)
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
names = {r[0] for r in c.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='events'")}
|
||||
assert {"idx_events_serial", "idx_events_timestamp"} <= names
|
||||
|
||||
|
||||
def test_reopening_keeps_the_new_key(tmp_path):
|
||||
SeismoDb(tmp_path / "seismo_relay.db")
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
assert "UNIQUE(serial, timestamp, record_type)" in _key_sql(db)
|
||||
@@ -22,7 +22,7 @@ from minimateplus.models import Event
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures"
|
||||
WAVEFORM = FIX / "fft-oracle-2026-09-14" / "N844LQHB.ZT0W" # footer ts2 = 2026-08-25 10:33:32
|
||||
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H" # window start 2026-05-10 19:04:50
|
||||
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H" # start 2026-05-10 19:04:51 (#51)
|
||||
|
||||
|
||||
def _tuple(ts):
|
||||
@@ -39,9 +39,10 @@ def test_waveform_timestamp_is_exact_trigger_from_binary():
|
||||
|
||||
def test_histogram_timestamp_is_window_start_unchanged():
|
||||
ev = read_blastware_file(HISTOGRAM)
|
||||
# Histogram event time = the window start (ts1); must NOT get the waveform
|
||||
# ts2 treatment (that would land ~24 h off).
|
||||
assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 50), _tuple(ev.timestamp)
|
||||
# Histogram event time = the window start, from its own event record (#51;
|
||||
# the footer's ts1 is a second earlier); must NOT get the waveform ts2
|
||||
# treatment (that would land ~24 h off).
|
||||
assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 51), _tuple(ev.timestamp)
|
||||
|
||||
|
||||
def test_a_report_does_not_override_the_instruments_event_record():
|
||||
|
||||
@@ -525,18 +525,28 @@ from minimateplus.histogram_codec import ( # noqa: E402
|
||||
|
||||
|
||||
def _mk_multi_block(intervals, seg=0, ctr=256):
|
||||
"""Build one multi-interval block from a list of 8-tuples."""
|
||||
b = bytearray()
|
||||
b += bytes([0x00, seg])
|
||||
b += int(ctr).to_bytes(2, "little")
|
||||
b += bytes([0x0A, 0x00])
|
||||
"""Build one multi-interval block from a list of 8-tuples (T, Tf, V, Vf, L,
|
||||
Lf, M, Mf) in the measured layout: big-endian from byte 5, each record ending
|
||||
in its PVS squared -- here the largest geo peak squared, which every real
|
||||
record is consistent with (34,502,955 / 34,502,955 DL2 intervals)."""
|
||||
b = bytearray([0x00, seg]) + int(ctr).to_bytes(2, "little") + bytes([0x0A])
|
||||
for iv in intervals:
|
||||
for v in iv:
|
||||
b += int(v).to_bytes(2, "big")
|
||||
b += (max(iv[0], iv[2], iv[4]) ** 2).to_bytes(4, "big")
|
||||
b += bytes(7)
|
||||
assert len(b) == 12 + 20 * len(intervals)
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def _mk_legacy_le_block(intervals, seg=0, ctr=256):
|
||||
"""The retracted model's bytes: 8 x uint16 LITTLE-endian from byte 6."""
|
||||
b = bytearray([0x00, seg]) + int(ctr).to_bytes(2, "little") + bytes([0x0A, 0x00])
|
||||
for iv in intervals:
|
||||
for v in iv:
|
||||
b += int(v).to_bytes(2, "little")
|
||||
b += (0).to_bytes(2, "little")
|
||||
b += (5).to_bytes(2, "little")
|
||||
b += (0).to_bytes(2, "little") + (5).to_bytes(2, "little")
|
||||
b += bytes(6)
|
||||
assert len(b) == 12 + 20 * len(intervals)
|
||||
return bytes(b)
|
||||
|
||||
|
||||
@@ -569,7 +579,7 @@ def test_multi_interval_values_are_not_little_endian_from_byte_6():
|
||||
tests/test_histogram_multi_interval.py for the measured cases.
|
||||
"""
|
||||
ivs = [(0x0100, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1)]
|
||||
body = _mk_multi_block(ivs) + _mk_multi_block(ivs, ctr=257)
|
||||
body = _mk_legacy_le_block(ivs) + _mk_legacy_le_block(ivs, ctr=257)
|
||||
assert walk_multi_interval_blocks(body)[0]["t_peak"] != 0x0100
|
||||
|
||||
|
||||
@@ -685,3 +695,10 @@ def test_third_block_still_rejects_a_mismatched_counter():
|
||||
+ _mk_multi_block(ivs, ctr=257)
|
||||
+ _mk_multi_block(ivs, ctr=999)) # counter jumps — not consecutive
|
||||
assert detect_multi_interval_stride(body) != 12 + 20 * 4
|
||||
|
||||
|
||||
def test_half_period_to_hz_follows_the_sample_rate():
|
||||
"""#50: (sample rate / 2) / half-period, measured on 1,725 / 1,725 cells at
|
||||
2048 sps; the old fixed 512 halved them."""
|
||||
assert half_period_to_hz(6, 2048) == pytest.approx(1024 / 6)
|
||||
assert half_period_to_hz(6) == pytest.approx(512 / 6) # 1024 sps by default
|
||||
@@ -56,7 +56,7 @@ def _block(records, *, ctr=0x0100, seg=0, mic=True, last=False) -> bytes:
|
||||
assert len(r) == (8 if mic else 6)
|
||||
for v in r:
|
||||
b += int(v).to_bytes(2, "big")
|
||||
b += b"\x00\x00" + b"\x00\x2d" # the zero word, then one more
|
||||
b += (max(r[0], r[2], r[4]) ** 2).to_bytes(4, "big") # PVS², consistent as on real data
|
||||
b += b"\xfc\xf3\x00" + (TERMINAL if last else b"\x5a\x0a\x00\x00")
|
||||
return bytes(b)
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from micromate.framing import FLAGS_THOR, build_request # noqa:
|
||||
from micromate.opcodes import ENABLEABLE_WRITES, OpcodeRefused # noqa: E402
|
||||
from micromate.protocol import ACK_DATA_LEN, TimeoutError as MmTimeout, UnexpectedResponse # noqa: E402
|
||||
from micromate.writes import ( # noqa: E402
|
||||
WritePlan, WriteStep, plan_call_home_enabled, plan_start_monitoring,
|
||||
WritePlan, WriteStep, plan_start_monitoring,
|
||||
plan_stop_monitoring,
|
||||
)
|
||||
from test_micromate_protocol import frame, proto # noqa: E402
|
||||
@@ -33,8 +33,11 @@ def _ready(responses):
|
||||
return p, t
|
||||
|
||||
|
||||
def test_the_ceiling_is_start_and_stop_only():
|
||||
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97})
|
||||
def test_the_ceiling_is_start_stop_call_home_and_the_setup_push():
|
||||
# Phase 4 (2026-11-02) added the call-home write and its confirm; phase 5
|
||||
# (2026-11-03) the setup push: name, preferences, trigger, setup, confirms.
|
||||
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97, 0x7E, 0x7F,
|
||||
0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72})
|
||||
|
||||
|
||||
def test_execute_sends_exactly_the_plans_frame_and_returns_the_ack():
|
||||
@@ -53,10 +56,10 @@ def test_permission_ends_with_the_call():
|
||||
|
||||
|
||||
def test_a_plan_beyond_the_ceiling_is_refused_and_nothing_is_sent():
|
||||
content = bytes(5) + b"\x05" + bytes(120)
|
||||
# 0xA8 (delete one event) stays above the ceiling (0x71 joined it in phase 5).
|
||||
p, t = _ready([])
|
||||
with pytest.raises(OpcodeRefused, match="ceiling"):
|
||||
p.execute(plan_call_home_enabled(content, False))
|
||||
p.execute(WritePlan("delete", (WriteStep(0xA8, 0x0000, bytes(4)),)))
|
||||
assert t.written == []
|
||||
|
||||
|
||||
@@ -110,7 +113,7 @@ def test_a_duck_typed_plan_is_refused():
|
||||
def test_a_forged_step_in_a_real_plan_is_refused_at_the_step():
|
||||
p, t = _ready([])
|
||||
plan = plan_start_monitoring()
|
||||
object.__setattr__(plan, "steps", (WriteStep(0x7E, 0),)) # subs now reads 0x7E too
|
||||
object.__setattr__(plan, "steps", (WriteStep(0xA8, 0),)) # subs now reads 0xA8 too
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan)
|
||||
assert t.written == []
|
||||
@@ -121,7 +124,7 @@ def test_a_forged_step_hidden_behind_a_good_plan_is_refused():
|
||||
@property
|
||||
def subs(self):
|
||||
return frozenset({0x96})
|
||||
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0x7E, 0)))
|
||||
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0xA8, 0)))
|
||||
p, t = _ready([ACK_START])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan)
|
||||
|
||||
@@ -373,7 +373,10 @@ def test_whole_captured_sessions_parse_with_no_bad_checksums():
|
||||
bad = [f for f in frames if not f.checksum_valid]
|
||||
assert not bad, f"{path.name}: {len(bad)} bad checksums"
|
||||
total += len(frames)
|
||||
assert total == 251, f"expected 251 response frames across the corpus, got {total}"
|
||||
# A floor, not an exact count: the corpus is a gitignored folder that grows
|
||||
# (2026-11-02, the full copy from the BW VM: 287 responses, 241 reads, every
|
||||
# one passing the same rule). Fewer than first verified means a lost file.
|
||||
assert total >= 251, f"expected at least 251 response frames across the corpus, got {total}"
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
@@ -410,7 +413,10 @@ def test_builder_reproduces_every_captured_read_frame():
|
||||
)
|
||||
checked += 1
|
||||
i = j + 1
|
||||
assert checked == 218, f"expected 218 read frames, checked {checked}"
|
||||
# A floor, not an exact count: the corpus is a gitignored folder that grows
|
||||
# (2026-11-02, the full copy from the BW VM: 287 responses, 241 reads, every
|
||||
# one passing the same rule). Fewer than first verified means a lost file.
|
||||
assert checked >= 218, f"expected at least 218 read frames, checked {checked}"
|
||||
|
||||
# ── the data section (writes) ─────────────────────────────────────────────────
|
||||
|
||||
@@ -523,4 +529,7 @@ def test_builder_reproduces_every_captured_request_frame_including_writes():
|
||||
)
|
||||
checked += 1
|
||||
i = j + 1
|
||||
assert checked == 251, f"expected 251 request frames, checked {checked}"
|
||||
# A floor, not an exact count: the corpus is a gitignored folder that grows
|
||||
# (2026-11-02, the full copy from the BW VM: 287 responses, 241 reads, every
|
||||
# one passing the same rule). Fewer than first verified means a lost file.
|
||||
assert checked >= 251, f"expected at least 251 request frames, checked {checked}"
|
||||
@@ -81,7 +81,7 @@ def test_a_frame_that_is_not_a_request_is_refused_not_sent():
|
||||
|
||||
def test_every_protocol_read_sub_is_in_the_read_table():
|
||||
consts = {k: v for k, v in vars(mm_proto).items() if k.startswith("SUB_")}
|
||||
assert len(consts) == 19
|
||||
assert len(consts) == 21 # + 0x48 and 0x94, the file read (phase 5)
|
||||
assert set(consts.values()) <= set(READ_SUBS)
|
||||
assert {0x94, 0x48} <= set(READ_SUBS)
|
||||
|
||||
@@ -98,7 +98,7 @@ def test_an_unknown_opcode_is_refused_and_nothing_is_written(sub):
|
||||
assert t.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sub", [0xEE, 0x7E, 0xA8])
|
||||
@pytest.mark.parametrize("sub", [0xEE, 0xA8, 0xAA]) # delete and its confirm stay above the ceiling
|
||||
def test_a_permit_beyond_the_ceiling_is_refused_at_the_wire(sub):
|
||||
p, t = proto([])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Reading a Micromate's schedule file, read-only (phase 5).
|
||||
|
||||
A Micromate's scheduled start loads the setup it names, so a settings change to
|
||||
another setup would be undone at the next start: SFM reads the schedule to refuse
|
||||
that case. Ground truth is THOR's 2026-09-24/25 captures of UM12947
|
||||
(bridges/captures/9-24-26 - micromate2): its read of `schedule.dat` (0x94, then
|
||||
0x48 pages) and its writes of a two- and a five-entry schedule (0x8E bodies).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from micromate.client import MicromateClient # noqa: E402
|
||||
from micromate.framing import MicromateFrameParser, unstuff # noqa: E402
|
||||
from micromate.protocol import MicromateProtocol # noqa: E402
|
||||
from micromate.schedule import ( # noqa: E402
|
||||
SCHEDULE_PATH, ScheduleEntry, parse_schedule, schedule_conflicts,
|
||||
)
|
||||
from test_micromate_protocol import ScriptedTransport, frame # noqa: E402
|
||||
from test_minimate_write_frames import _frames # noqa: E402
|
||||
|
||||
D = Path(__file__).resolve().parent.parent / "bridges" / "captures" / "9-24-26 - micromate2"
|
||||
READ_S3 = D / "raw_s3_20260924_191835_read_scheduler.bin"
|
||||
READ_BW = D / "raw_bw_20260924_191835_read_scheduler.bin"
|
||||
ACTIONCHECK_BW = D / "raw_bw_20260925_005122_actioncheck.bin"
|
||||
pytestmark = pytest.mark.skipif(not D.is_dir(), reason="bridges/captures is not on this machine")
|
||||
|
||||
|
||||
def _payloads(path: Path) -> list:
|
||||
return [unstuff(f[2:-1])[:-1] for f in _frames(path.read_bytes())]
|
||||
|
||||
|
||||
def _written_schedule(path: Path) -> bytes:
|
||||
"""The schedule body THOR wrote: the 0x8E chunks after the 0x8D that opens
|
||||
schedule.dat, joined (a long body goes in 1,024-byte pieces)."""
|
||||
body, current = b"", None
|
||||
for p in _payloads(path):
|
||||
if p[2] == 0x8D:
|
||||
current = p[16:] == SCHEDULE_PATH.encode("ascii")
|
||||
elif p[2] == 0x8E and current:
|
||||
body += p[16:]
|
||||
return body
|
||||
|
||||
|
||||
def _read_replies() -> list:
|
||||
"""The unit's replies to THOR's schedule read: 0x6B, then three 0xB7 pages."""
|
||||
fr = MicromateFrameParser().feed(READ_S3.read_bytes())
|
||||
i = next(k for k, f in enumerate(fr) if f.sub == 0x6B)
|
||||
return fr[i:i + 4]
|
||||
|
||||
|
||||
def test_the_read_capture_parses():
|
||||
body = bytes(_read_replies()[2].data)[11:]
|
||||
assert len(body) == 524
|
||||
e = parse_schedule(body)
|
||||
assert [(x.time, x.actions) for x in e] == [("07:30", ("start_with_setup",)), ("19:30", ("call_home",))]
|
||||
assert len(e[0].setup) == 40 and e[1].setup == ""
|
||||
assert e[0].day == 3 and e[0].action_bits == 2
|
||||
|
||||
|
||||
def test_the_five_entry_schedule_parses():
|
||||
e = parse_schedule(_written_schedule(ACTIONCHECK_BW))
|
||||
assert [(x.time, x.actions, x.setup) for x in e] == [
|
||||
("07:30", ("start_with_setup",), "TEST1.mmb"),
|
||||
("08:00", ("stop",), ""),
|
||||
("08:30", ("self_check",), ""),
|
||||
("09:00", ("start_with_setup",), "test2.mmb"),
|
||||
("19:30", ("call_home",), ""),
|
||||
]
|
||||
|
||||
|
||||
def test_conflicts_are_case_insensitive():
|
||||
e = parse_schedule(_written_schedule(ACTIONCHECK_BW))
|
||||
assert [x.setup for x in schedule_conflicts(e, "test1.MMB")] == ["test2.mmb"]
|
||||
assert [x.setup for x in schedule_conflicts(e, " TEST2.mmb ")] == ["TEST1.mmb"]
|
||||
|
||||
|
||||
def test_no_schedule_records_is_no_conflict():
|
||||
assert parse_schedule(bytes(524)) == []
|
||||
assert schedule_conflicts(parse_schedule(bytes(524)), "x.mmb") == []
|
||||
|
||||
|
||||
def test_an_unknown_action_bit_is_named_not_dropped():
|
||||
rec = bytearray(260)
|
||||
rec[4], rec[5], rec[6] = 14, 3, 0x01 # 07:00, the setup-less start THOR never sends?
|
||||
(e,) = parse_schedule(bytes(rec))
|
||||
assert e.actions == ("unknown(0x01)",) and e.setup == ""
|
||||
assert schedule_conflicts([e], "a.mmb") == [] # no setup named: nothing to undo the change
|
||||
|
||||
|
||||
def test_read_file_sends_thors_frames_and_stops_at_zeros():
|
||||
replies = [frame(f.sub, bytes(f.data), flags=f.flags, page=f.page_key) for f in _read_replies()]
|
||||
t = ScriptedTransport(replies)
|
||||
body = MicromateProtocol(t, recv_timeout=0.5).read_file(SCHEDULE_PATH)
|
||||
thor = [f for f in _frames(READ_BW.read_bytes()) if unstuff(f[2:-1])[2] in (0x94, 0x48)]
|
||||
assert t.written == thor[:4] # 0x94 + path, 0x48 (first page), 0x48, 0x48
|
||||
assert body == bytes(_read_replies()[2].data)[11:]
|
||||
|
||||
|
||||
class _Proto:
|
||||
def __init__(self, data: bytes):
|
||||
self.data = data
|
||||
|
||||
def read_active_setup_name(self):
|
||||
return self.data
|
||||
|
||||
def read_event_index(self):
|
||||
return self.data
|
||||
|
||||
def read_trigger_config(self):
|
||||
return self.data
|
||||
|
||||
def read_compliance_config(self):
|
||||
return self.data
|
||||
|
||||
|
||||
def _client(data: bytes) -> MicromateClient:
|
||||
c = MicromateClient.__new__(MicromateClient)
|
||||
c._proto = _Proto(data)
|
||||
return c
|
||||
|
||||
|
||||
def test_get_active_setup_raw_keeps_spaces():
|
||||
c = _client(bytes(11) + b" LOC 4 .mmb \x00junk")
|
||||
assert c.get_active_setup_raw() == " LOC 4 .mmb "
|
||||
assert c.get_active_setup() == "LOC 4 .mmb"
|
||||
|
||||
|
||||
def test_block_content_getters_strip_the_prefix():
|
||||
c = _client(bytes(range(11)) + b"content")
|
||||
assert c.get_prefs_content() == c.get_trigger_content() == c.get_setup_content() == b"content"
|
||||
|
||||
|
||||
def test_schedule_entry_is_a_value():
|
||||
assert ScheduleEntry(0, "07:00", 3, 2, ("start_with_setup",), "a") == \
|
||||
ScheduleEntry(0, "07:00", 3, 2, ("start_with_setup",), "a")
|
||||
@@ -193,12 +193,22 @@ def test_steps_cannot_be_reassigned():
|
||||
|
||||
def test_call_home_off_from_an_unobserved_start_value_carries_a_warning():
|
||||
r = bytearray(_call_home_reads()[0])
|
||||
r[5] = 0x01 # UM20147 reads 0x01, not THOR's 0x04/0x05
|
||||
r[5] = 0x03 # a value no unit has been seen holding
|
||||
plan = plan_call_home_enabled(bytes(r), False)
|
||||
assert any("unobserved" in w and "0x01 -> 0x00" in w for w in plan.warnings)
|
||||
assert any("unobserved" in w and "0x03 -> 0x02" in w for w in plan.warnings)
|
||||
assert plan.describe()["warnings"] and plan.describe()["warnings"] == list(plan.warnings)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("start,enabled", [(0x01, False), (0x00, True)])
|
||||
def test_um20147s_values_are_observed_since_the_bench(start, enabled):
|
||||
# Bench 2026-11-03 (UM20147): 0x01 -> 0x00 and 0x00 -> 0x01 both acknowledged, read
|
||||
# back, and matched in the unit's own menu (and again 2026-11-04).
|
||||
r = bytearray(_call_home_reads()[0])
|
||||
r[5] = start
|
||||
plan = plan_call_home_enabled(bytes(r), enabled)
|
||||
assert not any("unobserved" in w for w in plan.warnings)
|
||||
|
||||
|
||||
def test_call_home_on_when_already_on_says_it_changes_nothing():
|
||||
r = next(x for x in _call_home_reads() if x[5] == 0x05)
|
||||
plan = plan_call_home_enabled(r, True)
|
||||
@@ -265,3 +275,10 @@ def test_setup_push_refuses_a_block_whose_own_length_header_is_wrong():
|
||||
bad[0:2] = (int.from_bytes(bad[0:2], "big") + 1).to_bytes(2, "big")
|
||||
with pytest.raises(ValueError, match="header"):
|
||||
plan_setup_push(reads[0x08], reads[0x2E], bytes(bad), "x.mmb")
|
||||
|
||||
|
||||
|
||||
def test_call_home_refuses_a_block_whose_header_is_not_its_length():
|
||||
# 126 bytes, but not the call-home block: its header must be its own length (00 7C).
|
||||
with pytest.raises(ValueError, match="header"):
|
||||
plan_call_home_enabled(bytes(126), True)
|
||||
@@ -213,40 +213,8 @@ def test_each_read_returns_the_block_blastware_then_wrote(read, sub, size):
|
||||
assert block[:-2] == want[:-2] if sub == 0x69 else block == want[:-2]
|
||||
|
||||
|
||||
# -- apply_config writes this unit's own trigger block ---------------------------
|
||||
|
||||
class StubProto:
|
||||
"""Serves BE9441's blocks as read on 2026-10-26; records every write."""
|
||||
|
||||
def __init__(self):
|
||||
self.writes = []
|
||||
|
||||
def read_event_index(self):
|
||||
return _image(0x68)[:-2]
|
||||
|
||||
def read_compliance_config(self):
|
||||
return _image(0x71)[:-2]
|
||||
|
||||
def read_waveform_data_raw(self):
|
||||
return _image(0x69)
|
||||
|
||||
def read_trigger_config(self):
|
||||
return _image(0x82)[:-2]
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name.startswith("write_"):
|
||||
return lambda *a, **k: self.writes.append((name, a))
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
def test_apply_config_writes_the_units_own_trigger_block():
|
||||
from minimateplus.client import MiniMateClient
|
||||
c = MiniMateClient(transport=object())
|
||||
c._proto = StubProto()
|
||||
c.apply_config() # nothing changed: a round trip
|
||||
trig = [a[0] for n, a in c._proto.writes if n == "write_trigger_config"]
|
||||
assert trig == [_image(0x82)[:-2]]
|
||||
assert trig[0][5] == 0x01 # BE9441's; the March copy had 0x03
|
||||
# -- the unit's own trigger block is sent back: tests/test_device_access_s3_settings.py
|
||||
# (test_s3_trigger_change_sends_the_units_own_blocks), phase 5.
|
||||
|
||||
|
||||
def test_a_bad_block_is_refused_before_the_first_write_goes_out():
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Series 3 call-home: the enable byte from the unescaped 0x2C block, a write that
|
||||
changes byte 5 only, and the audited change (phase 4). The live send stays
|
||||
refused until its frame is reproduced from a Blastware capture (task 4)."""
|
||||
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 sfm.device_access.s3 as s3mod # noqa: E402
|
||||
from device_access_fakes import FakeMiniMateClient, s3_call_home_raw # noqa: E402
|
||||
from minimateplus.protocol import ( # noqa: E402
|
||||
SUB_CALL_HOME_WRITE, call_home_enabled, call_home_image, write_image,
|
||||
)
|
||||
from sfm.device_access.errors import NotSupported, UnitStateUnknown # noqa: E402
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s3 import Series3Adapter # noqa: E402
|
||||
|
||||
TCP = UnitAddress(host="10.0.0.6", tcp_port=12345, 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 adapter(fake):
|
||||
calls = []
|
||||
|
||||
def factory(address, **kw):
|
||||
calls.append(kw)
|
||||
return fake
|
||||
a = Series3Adapter(client_factory=factory)
|
||||
a.factory_calls = calls
|
||||
return a
|
||||
|
||||
|
||||
def change(a, *, enabled, dry_run=False, even_if_already=False):
|
||||
return a.change_call_home(TCP, "BE18193", enabled=enabled, dry_run=dry_run,
|
||||
even_if_already=even_if_already, audit=Audit(), caller="test",
|
||||
sleep=lambda s: None, verify_timeout_s=3.0, verify_interval_s=1.0)
|
||||
|
||||
|
||||
def test_s3_enable_byte_reads_from_the_unescaped_block():
|
||||
raw = s3_call_home_raw()
|
||||
assert call_home_enabled(raw) is True
|
||||
assert call_home_enabled(s3_call_home_raw(0x00)) is False
|
||||
# An escaped byte before [5] moves the raw index; the unescaped one does not.
|
||||
shifted = raw[:2] + b"\x10\x03" + raw[3:]
|
||||
assert shifted[5] != raw[5] and call_home_enabled(shifted) is True
|
||||
assert call_home_enabled(s3_call_home_raw(0x07)) is None
|
||||
|
||||
|
||||
def test_s3_image_changes_only_byte_5():
|
||||
raw = s3_call_home_raw()
|
||||
img = call_home_image(raw, False)
|
||||
base = write_image(SUB_CALL_HOME_WRITE, raw)
|
||||
assert len(img) == 126 == 0x7C + 2
|
||||
assert [i for i in range(len(img)) if img[i] != base[i]] == [5]
|
||||
assert img[5] == 0x00 and call_home_image(raw, True)[5] == 0x01
|
||||
|
||||
|
||||
def test_s3_image_refuses_an_unknown_byte_5():
|
||||
with pytest.raises(ValueError):
|
||||
call_home_image(s3_call_home_raw(0x07), True)
|
||||
|
||||
|
||||
def test_s3_call_home_state():
|
||||
fake = FakeMiniMateClient()
|
||||
st = adapter(fake).call_home_state(TCP, "BE18193")
|
||||
assert (st.serial, st.series, st.enabled, st.dial_string) == ("BE18193", 3, True, "RADIO RING")
|
||||
assert st.detail["serial_verified"] is False and st.detail["byte5"] == "0x01"
|
||||
assert fake.calls.index("wake") < fake.calls.index("read_call_home_raw")
|
||||
|
||||
|
||||
def test_the_gate_is_open_and_names_its_proof():
|
||||
assert s3mod.S3_CALL_HOME_FRAME_VERIFIED is True
|
||||
assert "tests/test_s3_call_home_bw_frames.py" in open(s3mod.__file__).read()
|
||||
|
||||
|
||||
def test_s3_live_change_is_refused_while_the_gate_is_shut(monkeypatch):
|
||||
monkeypatch.setattr(s3mod, "S3_CALL_HOME_FRAME_VERIFIED", False)
|
||||
a = adapter(FakeMiniMateClient())
|
||||
with pytest.raises(NotSupported) as e:
|
||||
change(a, enabled=False)
|
||||
assert e.value.http_status == 501 and "Blastware" in str(e.value)
|
||||
assert a.factory_calls == [] # refused before any connection
|
||||
|
||||
|
||||
def test_s3_dry_run_shows_both_frames():
|
||||
fake = FakeMiniMateClient()
|
||||
r = change(adapter(fake), enabled=False, dry_run=True)
|
||||
assert r.outcome == "dry_run"
|
||||
assert [st["sub"] for st in r.plan["steps"]] == ["0x7E", "0x7F"]
|
||||
assert fake.writes == []
|
||||
|
||||
|
||||
def test_s3_change_once_verified(monkeypatch):
|
||||
monkeypatch.setattr(s3mod, "S3_CALL_HOME_FRAME_VERIFIED", True)
|
||||
fake = FakeMiniMateClient()
|
||||
r = change(adapter(fake), enabled=False)
|
||||
assert (r.outcome, r.verified, r.state_after, r.action) == ("sent", "ok", "disabled", "disable call-home")
|
||||
assert fake.writes == ["call_home"]
|
||||
assert r.detail["snapshot"]["changed_offsets"] == [5]
|
||||
|
||||
|
||||
def test_s3_unknown_byte_5_sends_nothing(monkeypatch):
|
||||
monkeypatch.setattr(s3mod, "S3_CALL_HOME_FRAME_VERIFIED", True)
|
||||
fake = FakeMiniMateClient(call_home_raw=s3_call_home_raw(0x07))
|
||||
with pytest.raises(UnitStateUnknown):
|
||||
change(adapter(fake), enabled=False)
|
||||
assert fake.writes == []
|
||||
|
||||
|
||||
def test_s3_dry_run_with_an_unknown_byte_5_shows_no_frames():
|
||||
fake = FakeMiniMateClient(call_home_raw=s3_call_home_raw(0x07))
|
||||
r = change(adapter(fake), enabled=False, dry_run=True)
|
||||
assert r.plan["steps"] == [] and any("0x07" in w for w in r.plan["warnings"])
|
||||
|
||||
|
||||
|
||||
def test_a_pre_wire_refusal_is_recorded_as_nothing_sent():
|
||||
# Final review #2: a refusal raised before the frame went out must not be
|
||||
# audited as "sent, acknowledgement lost".
|
||||
from minimateplus.protocol import ImageRefused
|
||||
audit = Audit()
|
||||
fake = FakeMiniMateClient(write_error=ImageRefused("write SUB 0x7E: not a whole block"))
|
||||
from sfm.device_access.errors import DeviceError
|
||||
with pytest.raises(DeviceError) as e: # the adapter wraps it, as it does OpcodeRefused
|
||||
adapter(fake).change_call_home(TCP, "BE18193", enabled=False, dry_run=False, even_if_already=False,
|
||||
audit=audit, caller="test", sleep=lambda s: None,
|
||||
verify_timeout_s=3.0, verify_interval_s=1.0)
|
||||
assert isinstance(e.value.__cause__, ImageRefused)
|
||||
((_, row),) = audit.rows.items()
|
||||
assert (row["outcome"], row["sent"]) == ("failed", 0)
|
||||
assert row["error"].startswith("refused before sending")
|
||||
|
||||
|
||||
|
||||
# Measured 2026-11-03 (BE9441): while monitoring, a MiniMate answers the 0x2C read
|
||||
# with its DEVICE-INFO block ("Instantel", "MiniMate Plus", its serial), not its
|
||||
# call-home block -- as it answers 1A. Idle again, it returns the call-home block.
|
||||
# SFM says so plainly instead of "run state unknown(0x6E)".
|
||||
|
||||
def device_info_shaped(serial=b"BE9441"):
|
||||
"""Shaped like BE9441's reply (its first bytes: 00 00 00 08 'Instantel')."""
|
||||
block = b"\x00\x00\x00\x08Instantel".ljust(26, b"\x00") + b"MiniMate Plus".ljust(16, b"\x00") + serial
|
||||
return block.ljust(126, b"\x00")
|
||||
|
||||
|
||||
def test_a_call_home_block_is_told_from_the_device_info_block():
|
||||
from minimateplus.protocol import is_call_home_block
|
||||
assert is_call_home_block(s3_call_home_raw()) is True
|
||||
assert is_call_home_block(device_info_shaped()) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dry_run", [True, False])
|
||||
def test_a_monitoring_minimate_is_told_to_stop_first_and_nothing_is_sent(dry_run):
|
||||
fake = FakeMiniMateClient(call_home_raw=device_info_shaped())
|
||||
with pytest.raises(UnitStateUnknown) as e:
|
||||
change(adapter(fake), enabled=True, dry_run=dry_run)
|
||||
msg = str(e.value)
|
||||
assert "monitoring" in msg and "stop" in msg and "nothing sent" in msg
|
||||
assert e.value.http_status == 409 and fake.writes == []
|
||||
|
||||
|
||||
def test_the_call_home_state_of_a_monitoring_minimate_says_why():
|
||||
st = adapter(FakeMiniMateClient(call_home_raw=device_info_shaped())).call_home_state(TCP, "BE18193")
|
||||
assert st.enabled is None
|
||||
assert "monitoring" in st.detail["reason"]
|
||||
@@ -0,0 +1,64 @@
|
||||
"""SFM's MiniMate call-home write is Blastware's, frame for frame (phase 4).
|
||||
|
||||
Ground truth: Blastware changing BE11529's call-home settings on 2026-04-20
|
||||
(Remote Access -> Setup Unit), recorded as paired raw files -- what Blastware
|
||||
sent (raw_bw_*) and what the unit answered (raw_s3_*). Copied from
|
||||
bridges/captures/4-20-26/call home settings/: the read, the enable, the disable.
|
||||
For each 0x7E, SFM builds its frame from the unit's own read just before it and
|
||||
the value Blastware asked for; it must equal Blastware's frame byte for byte.
|
||||
This test is what opens sfm.device_access.s3.S3_CALL_HOME_FRAME_VERIFIED.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from test_minimate_write_frames import _frames, _payload # noqa: E402
|
||||
from minimateplus.framing import S3FrameParser, build_bw_write_frame # noqa: E402
|
||||
from minimateplus.protocol import ( # noqa: E402
|
||||
SUB_CALL_HOME, SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, call_home_image, write_image,
|
||||
)
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures" / "s3-call-home-bw"
|
||||
ACTIONS = ["162148_pull_call_home_options", "162221_enable_auto_call_home", "162255_disable_auto_call_home"]
|
||||
|
||||
|
||||
def _action(tag):
|
||||
bw = _frames((FIX / f"raw_bw_20260420_{tag}.bin").read_bytes())
|
||||
requests = [(_payload(f)[2], f) for f in bw]
|
||||
reads = [bytes(f.data)[11:] for f in S3FrameParser().feed((FIX / f"raw_s3_20260420_{tag}.bin").read_bytes())
|
||||
if f.sub == 0xFF - SUB_CALL_HOME and len(f.data) > 100]
|
||||
return requests, reads
|
||||
|
||||
|
||||
def test_sfm_builds_blastwares_call_home_write():
|
||||
last_read, asserted, confirms = None, [], 0
|
||||
for tag in ACTIONS:
|
||||
requests, reads = _action(tag)
|
||||
subs = [s for s, _ in requests]
|
||||
if reads and SUB_CALL_HOME_WRITE in subs:
|
||||
# this action's read went out before its write
|
||||
last_2c = max(i for i, s in enumerate(subs) if s == SUB_CALL_HOME)
|
||||
assert last_2c < subs.index(SUB_CALL_HOME_WRITE)
|
||||
last_read = reads[-1]
|
||||
for sub, frame in requests:
|
||||
if sub == SUB_CALL_HOME_WRITE:
|
||||
bw_image = _payload(frame)[16:]
|
||||
wanted = bw_image[5]
|
||||
base = write_image(SUB_CALL_HOME_WRITE, last_read)
|
||||
assert wanted in (0x00, 0x01)
|
||||
assert [i for i in range(len(base)) if base[i] != bw_image[i] and i != 5] == []
|
||||
assert build_bw_write_frame(SUB_CALL_HOME_WRITE, call_home_image(last_read, wanted == 0x01)) == frame
|
||||
asserted.append((tag, base[5], wanted))
|
||||
elif sub == SUB_CALL_HOME_CONFIRM:
|
||||
assert build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"") == frame
|
||||
confirms += 1
|
||||
if reads and SUB_CALL_HOME_WRITE not in subs:
|
||||
last_read = reads[-1]
|
||||
# Blastware turned call-home on (read 0x00 -> 0x01), then off (read 0x01 -> 0x00).
|
||||
assert asserted == [("162221_enable_auto_call_home", 0x00, 0x01),
|
||||
("162255_disable_auto_call_home", 0x01, 0x00)]
|
||||
assert confirms == 2
|
||||
@@ -0,0 +1,125 @@
|
||||
"""The MiniMate call-home send path frames the built image exactly once
|
||||
(phase-4 final review #1, 2026-11-02).
|
||||
|
||||
`call_home_image` is already unescaped; passing it through `write_image` again
|
||||
strips any real 0x10 that precedes 02/03/04 -- a call-in time of 16:02-16:04
|
||||
(hour 0x10) is exactly that. One such time made the send refuse; two made it
|
||||
send a block shifted by two bytes. Driven through the real MiniMateClient ->
|
||||
MiniMateProtocol over a stub answering with the unit's recorded acks (BE11529,
|
||||
2026-04-20).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import minimateplus.protocol as mp # noqa: E402
|
||||
from minimateplus.client import MiniMateClient # noqa: E402
|
||||
from minimateplus.framing import S3FrameParser, build_bw_write_frame # noqa: E402
|
||||
from minimateplus.protocol import ( # noqa: E402
|
||||
SUB_CALL_HOME, SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, call_home_image, write_image,
|
||||
)
|
||||
from test_minimate_write_frames import _payload # noqa: E402
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures" / "s3-call-home-bw"
|
||||
|
||||
|
||||
def _recorded_ack(path: Path, ack_sub: int) -> bytes:
|
||||
raw, start, p = path.read_bytes(), 0, S3FrameParser()
|
||||
for i in range(len(raw)):
|
||||
for f in p.feed(raw[i:i + 1]):
|
||||
w = raw[start:i + 1]
|
||||
if f.sub == ack_sub:
|
||||
return w[w.index(b"\x10\x02"):]
|
||||
start = i + 1
|
||||
raise AssertionError(f"no 0x{ack_sub:02X} ack in {path.name}")
|
||||
|
||||
|
||||
ENABLE_S3 = FIX / "raw_s3_20260420_162221_enable_auto_call_home.bin"
|
||||
ACKS = {SUB_CALL_HOME_WRITE: _recorded_ack(ENABLE_S3, 0xFF - SUB_CALL_HOME_WRITE),
|
||||
SUB_CALL_HOME_CONFIRM: _recorded_ack(ENABLE_S3, 0xFF - SUB_CALL_HOME_CONFIRM)}
|
||||
|
||||
|
||||
class Acks:
|
||||
def __init__(self):
|
||||
self.sent, self._buf = [], b""
|
||||
|
||||
def write(self, data):
|
||||
data = bytes(data)
|
||||
self.sent.append(data)
|
||||
self._buf += ACKS[_payload(data)[2]]
|
||||
|
||||
def read(self, n):
|
||||
out, self._buf = self._buf[:n], self._buf[n:]
|
||||
return out
|
||||
|
||||
|
||||
def _client():
|
||||
t = Acks()
|
||||
c = MiniMateClient("unused")
|
||||
c._proto = mp.MiniMateProtocol(t)
|
||||
return c, t
|
||||
|
||||
|
||||
def _fixture_read() -> bytes:
|
||||
p = FIX / "raw_s3_20260420_162148_pull_call_home_options.bin"
|
||||
return [bytes(f.data)[11:] for f in S3FrameParser().feed(p.read_bytes())
|
||||
if f.sub == 0xFF - SUB_CALL_HOME and len(f.data) > 100][-1]
|
||||
|
||||
|
||||
def _as_read(logical: bytes) -> bytes:
|
||||
"""A block as S3FrameParser returns it: each 02/03/04 keeps its 10 escape
|
||||
(a logical 0x10 arrives as 10 10, which the parser collapses to one 10)."""
|
||||
out = bytearray()
|
||||
for b in logical:
|
||||
out += bytes([0x10, b]) if b in (0x02, 0x03, 0x04) else bytes([b])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _with_times(t1: bytes, t2: bytes = None) -> bytes:
|
||||
logical = bytearray(write_image(SUB_CALL_HOME_WRITE, _fixture_read())[:-2]) # the N = 124 bytes
|
||||
logical[101:103] = t1
|
||||
if t2 is not None:
|
||||
logical[105:107] = t2
|
||||
return _as_read(bytes(logical))
|
||||
|
||||
|
||||
def _frames(image):
|
||||
return [build_bw_write_frame(SUB_CALL_HOME_WRITE, image), build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
def test_the_units_own_read_goes_out_framed_once(enabled):
|
||||
c, t = _client()
|
||||
image = call_home_image(_fixture_read(), enabled)
|
||||
c.write_call_home_image(image)
|
||||
assert t.sent == _frames(image)
|
||||
|
||||
|
||||
def test_a_16_02_call_in_time_is_sent_as_read():
|
||||
raw = _with_times(b"\x10\x02")
|
||||
image = call_home_image(raw, False)
|
||||
assert image[101:103] == b"\x10\x02" # the image itself is right
|
||||
c, t = _client()
|
||||
c.write_call_home_image(image)
|
||||
assert t.sent == _frames(image)
|
||||
|
||||
|
||||
def test_two_such_times_are_not_shifted():
|
||||
raw = _with_times(b"\x10\x03", b"\x10\x04")
|
||||
image = call_home_image(raw, True)
|
||||
c, t = _client()
|
||||
c.write_call_home_image(image)
|
||||
assert t.sent == _frames(image)
|
||||
|
||||
|
||||
def test_a_malformed_image_is_refused_before_the_wire():
|
||||
c, t = _client()
|
||||
with pytest.raises(mp.ImageRefused):
|
||||
c.write_call_home_image(call_home_image(_fixture_read(), True)[:-1])
|
||||
assert t.sent == []
|
||||
@@ -96,30 +96,5 @@ def test_a_reply_without_the_settings_block_reads_as_unknown():
|
||||
(None, None, None, None)
|
||||
|
||||
|
||||
# The write side (review finding, 2026-10-29). _encode_compliance_config patches
|
||||
# the RAW bytes at offsets measured at 1024 sps (April 2026), where an escape sits
|
||||
# between the mode and the anchor. At other rates the mode is one byte later, so
|
||||
# a mode change rewrote the byte in front of it. A payload that would not read
|
||||
# back as asked is refused before anything is sent.
|
||||
|
||||
from minimateplus.client import _encode_compliance_config # noqa: E402
|
||||
|
||||
|
||||
def _block(i):
|
||||
return _settings_replies()[i].ljust(2126, b"\x00") # a whole block's length
|
||||
|
||||
|
||||
@pytest.mark.parametrize("i, change", [
|
||||
(0, {"recording_mode": 0}), # 10-25 Continuous / 4096: mode sits at -7, not -8
|
||||
(1, {"sample_rate": 4096}), # 10-26 Histogram+Continuous / 2048: escaped mode shifts the rate
|
||||
])
|
||||
def test_a_change_that_would_not_read_back_is_refused(i, change):
|
||||
with pytest.raises(ValueError, match="read back"):
|
||||
_encode_compliance_config(_block(i), **change)
|
||||
|
||||
|
||||
def test_a_change_that_reads_back_as_asked_is_built():
|
||||
out = _encode_compliance_config(_block(0), record_time=7.0)
|
||||
cc = _decode(out)
|
||||
assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, cc.record_time) == \
|
||||
(1, 4096, 5, 7.0)
|
||||
# The write side moved to the shared settings codec in phase 5 (2026-11-03):
|
||||
# tests/test_setup_fields.py reproduces every Blastware write byte for byte.
|
||||
@@ -0,0 +1,151 @@
|
||||
"""A MiniMate's settings read, assembled into the logical 2,090-byte block (phase 5).
|
||||
|
||||
Measured 2026-11-03 on BE9441's 10-26 recording (12 reads): unescape each 1A
|
||||
data frame and take data[11:]; every frame but the last starts with one `00`
|
||||
that is not content -- drop it. The result is the block Blastware writes back:
|
||||
the read after each of its two writes equals the image it had just written.
|
||||
While monitoring, the unit answers with its device-info block instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import minimateplus.protocol as mp # noqa: E402
|
||||
from minimateplus.framing import S3FrameParser # noqa: E402
|
||||
from minimateplus.protocol import ( # noqa: E402
|
||||
COMPLIANCE_CONTENT_LEN, assemble_compliance_content, is_compliance_content,
|
||||
)
|
||||
from test_minimate_write_frames import WRITES, _payload # noqa: E402
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
|
||||
|
||||
|
||||
def _reads() -> list:
|
||||
"""Each recorded 1A read as its data frames' `data`, in order (a probe reply,
|
||||
11 bytes of data, starts each read)."""
|
||||
reads, cur = [], None
|
||||
for f in S3FrameParser().feed((FIX / "unit_replies.bin").read_bytes()):
|
||||
if f.sub != 0xE5:
|
||||
continue
|
||||
if len(f.data) == 11:
|
||||
cur = []
|
||||
reads.append(cur)
|
||||
else:
|
||||
cur.append(bytes(f.data))
|
||||
return reads
|
||||
|
||||
|
||||
READS = _reads()
|
||||
IMAGES = [b"".join(_payload(f)[16:] for f in WRITES[k:k + 13] if _payload(f)[2] == 0x71)
|
||||
for k in (0, 13)]
|
||||
|
||||
|
||||
def test_the_recording_holds_twelve_reads_in_both_patterns():
|
||||
assert len(READS) == 12
|
||||
assert sorted({len(r) for r in READS}) == [3, 5] # SFM's 1024+1024+42, Blastware's 4x512+42
|
||||
|
||||
|
||||
def test_reads_assemble_to_2090_bytes():
|
||||
assert COMPLIANCE_CONTENT_LEN == 2090
|
||||
assert all(len(assemble_compliance_content(r)) == 2090 for r in READS)
|
||||
|
||||
|
||||
def test_a_read_after_a_blastware_write_equals_the_write():
|
||||
assert assemble_compliance_content(READS[1]) == IMAGES[0][:2090]
|
||||
assert assemble_compliance_content(READS[2]) == IMAGES[1][:2090]
|
||||
|
||||
|
||||
def test_a_monitoring_units_answer_is_not_settings():
|
||||
# reads 3-7 were taken while BE9441 was monitoring: they start 0e 'BE9441'
|
||||
assert [is_compliance_content(assemble_compliance_content(r)) for r in READS[3:8]] == [False] * 5
|
||||
assert all(is_compliance_content(assemble_compliance_content(r)) for r in READS[:3] + READS[8:])
|
||||
|
||||
|
||||
def _s3_reply(sub: int, data: bytes) -> bytes:
|
||||
"""A unit reply on the wire: DLE STX, the payload with every 0x10 doubled, ETX.
|
||||
(`data` here holds no 02/03/04, so no escape is needed.)"""
|
||||
body = bytes([0x00, 0x10, sub, 0x00, 0x00]) + data
|
||||
body += bytes([sum(body) & 0xFF])
|
||||
return b"\x10\x02" + body.replace(b"\x10", b"\x10\x10") + b"\x03"
|
||||
|
||||
|
||||
class _ProbeAndOneFrame:
|
||||
"""Answers the probe and frame B, then goes silent: frame C never arrives."""
|
||||
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
self._replies = [_s3_reply(0xE5, bytes(11)), _s3_reply(0xE5, bytes(11) + bytes(1025))]
|
||||
self._buf = b""
|
||||
|
||||
def write(self, data):
|
||||
self.sent.append(bytes(data))
|
||||
if self._replies:
|
||||
self._buf += self._replies.pop(0)
|
||||
|
||||
def read(self, n):
|
||||
out, self._buf = self._buf[:n], self._buf[n:]
|
||||
return out
|
||||
|
||||
|
||||
def test_read_compliance_content_refuses_a_missing_frame():
|
||||
t = _ProbeAndOneFrame()
|
||||
proto = mp.MiniMateProtocol(t, recv_timeout=0.2)
|
||||
with pytest.raises(mp.ProtocolError):
|
||||
proto.read_compliance_content()
|
||||
assert len(t.sent) == 3 # probe, B, C -- and no D after C went unanswered
|
||||
|
||||
|
||||
# Bench 2026-11-04 (BE9441, live): frame B of a 1A read came back one byte long,
|
||||
# ending in a lone 0x10 -- the kept escape of a checksum byte that was itself
|
||||
# escaped (02 / 03 / 04: about one frame in 85); the parser strips only the byte
|
||||
# after it. The 12 recorded reads never hit it. The read knows how much it asked
|
||||
# for, so it takes exactly that; a leftover other than that one 0x10 is kept, and
|
||||
# the block then fails is_compliance_content.
|
||||
|
||||
def test_a_frame_with_an_escaped_checksums_stray_byte_is_trimmed_to_what_was_asked():
|
||||
sfm_read = READS[8] # SFM's own 1024 + 1024 + 42 pattern
|
||||
good = assemble_compliance_content(sfm_read, lengths=(1024, 1024, 42))
|
||||
assert good == assemble_compliance_content(sfm_read) and is_compliance_content(good)
|
||||
stray = [sfm_read[0] + b"\x10", sfm_read[1], sfm_read[2]]
|
||||
assert len(assemble_compliance_content(stray)) == 2091 # what the bench saw
|
||||
assert assemble_compliance_content(stray, lengths=(1024, 1024, 42)) == good
|
||||
|
||||
|
||||
def test_a_leftover_that_is_not_the_stray_escape_is_not_trimmed():
|
||||
sfm_read = READS[8]
|
||||
odd = [sfm_read[0] + b"\x55", sfm_read[1], sfm_read[2]]
|
||||
assert not is_compliance_content(assemble_compliance_content(odd, lengths=(1024, 1024, 42)))
|
||||
|
||||
|
||||
# The same artifact on the waveform-data read a settings write echoes back: it asks
|
||||
# for 0xCA = 202 bytes; one extra trailing 0x10 is the escaped checksum's DLE.
|
||||
# (Unfixed, it fails closed: the write's own block check refuses 203 bytes.)
|
||||
class _Replies:
|
||||
def __init__(self, data):
|
||||
self._data = data
|
||||
self.sent = []
|
||||
|
||||
def __call__(self, frame):
|
||||
self.sent.append(frame)
|
||||
|
||||
|
||||
def _waveform_proto(data_reply: bytes):
|
||||
from types import SimpleNamespace
|
||||
p = mp.MiniMateProtocol(object())
|
||||
p._send = _Replies(None)
|
||||
replies = [SimpleNamespace(data=bytes(11)), SimpleNamespace(data=bytes(11) + data_reply)]
|
||||
p._recv_one = lambda expected_sub=None, **kw: replies.pop(0)
|
||||
return p
|
||||
|
||||
|
||||
def test_the_waveform_read_drops_an_escaped_checksums_stray_byte():
|
||||
block = (200).to_bytes(2, "big") + bytes(range(198)) + b"\x17\x17" # N = 200, plus its 2 tail bytes
|
||||
assert _waveform_proto(block).read_waveform_data_raw() == block
|
||||
assert _waveform_proto(block + b"\x10").read_waveform_data_raw() == block
|
||||
assert _waveform_proto(block + b"\x55").read_waveform_data_raw() == block + b"\x55" # anything else is kept
|
||||
@@ -2,6 +2,8 @@
|
||||
FastAPI Query() defaults are FieldInfo objects, not values."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -418,10 +420,13 @@ def test_a_change_unconfirmed_keeps_its_cause_status_and_names_the_audit_record(
|
||||
"failed: silent -- audit record c7", audit_id="c7", sent="acknowledged",
|
||||
http_status=504)
|
||||
monkeypatch.setattr(srv, "_device_access_instance", Raises())
|
||||
with pytest.raises(HTTPException) as e:
|
||||
srv.device_monitor_start(**CH)
|
||||
assert e.value.status_code == 504
|
||||
assert "audit record c7" in e.value.detail
|
||||
resp = srv.device_monitor_start(**CH)
|
||||
assert resp.status_code == 504 # the cause's status, unchanged
|
||||
body = json.loads(resp.body)
|
||||
assert "audit record c7" in body["detail"]
|
||||
# #10 (2026-11-02): the page tells "may have been sent" from "nothing sent" by
|
||||
# these, not by matching the message.
|
||||
assert (body["sent"], body["audit_id"]) == ("acknowledged", "c7")
|
||||
|
||||
|
||||
def test_device_commands_normalises_the_serial(tmp_path, monkeypatch):
|
||||
@@ -430,3 +435,63 @@ def test_device_commands_normalises_the_serial(tmp_path, monkeypatch):
|
||||
action="start monitoring", tier="change", request={}, caller="test")
|
||||
monkeypatch.setattr(srv, "_get_db", lambda: db)
|
||||
assert len(srv.db_device_commands(serial=" um20147 ", limit=100)["commands"]) == 1
|
||||
|
||||
|
||||
|
||||
# ── call-home by serial (phase 4) ─────────────────────────────────────────────
|
||||
|
||||
from device_access_fakes import um12947_call_home # noqa: E402
|
||||
|
||||
CH_STATE = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034, serial="UM20147")
|
||||
|
||||
|
||||
def test_call_home_state_route(monkeypatch):
|
||||
_s4(monkeypatch, FakeMicromateClient())
|
||||
st = srv.device_call_home_state(**CH_STATE)
|
||||
assert (st["series"], st["enabled"], st["dial_string"]) == (4, True, "RADIO RING")
|
||||
|
||||
|
||||
def test_enable_route_returns_the_change_result(monkeypatch):
|
||||
_s4(monkeypatch, FakeMicromateClient(call_home=um12947_call_home(False)))
|
||||
resp = srv.device_call_home_enable(**CH)
|
||||
assert resp.status_code == 200 and _body(resp)["action"] == "enable call-home"
|
||||
|
||||
|
||||
def test_disable_route_returns_the_change_result(monkeypatch):
|
||||
_s4(monkeypatch, FakeMicromateClient())
|
||||
resp = srv.device_call_home_disable(**CH)
|
||||
assert resp.status_code == 200 and _body(resp)["state_after"] == "disabled"
|
||||
|
||||
|
||||
def _asgi(method, path, query=""):
|
||||
import asyncio
|
||||
msgs = []
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": b"", "more_body": False}
|
||||
|
||||
async def send(m):
|
||||
msgs.append(m)
|
||||
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method,
|
||||
"scheme": "http", "path": path, "raw_path": path.encode(), "root_path": "",
|
||||
"query_string": query.encode(), "headers": [(b"host", b"sfm.local")],
|
||||
"server": ("sfm.local", 80), "client": ("127.0.0.1", 1)}
|
||||
asyncio.run(srv.app(scope, receive, send))
|
||||
return next(m for m in msgs if m["type"] == "http.response.start")["status"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path", [("GET", "/device/call_home/state"),
|
||||
("POST", "/device/call_home/enable"),
|
||||
("POST", "/device/call_home/disable")])
|
||||
def test_call_home_routes_need_a_serial(method, path):
|
||||
assert _asgi(method, path, "host=10.0.0.5&tcp_port=9034") == 422
|
||||
|
||||
|
||||
def test_call_home_routes_are_serial_aware():
|
||||
assert {"/device/call_home/state", "/device/call_home/enable",
|
||||
"/device/call_home/disable"} <= srv._SERIAL_AWARE_PATHS
|
||||
|
||||
|
||||
def test_legacy_call_home_post_still_refuses_a_micromate_serial():
|
||||
refusal = srv._device_guard("/device/call_home", {"serial": "UM20147"})
|
||||
assert refusal is not None and refusal[0] == 501
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user