Compare commits
50
Commits
No files matched your search
+345
-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
|
||||
@@ -92,6 +208,154 @@ All notable changes to seismo-relay are documented here.
|
||||
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`
|
||||
@@ -113,7 +377,47 @@ All notable changes to seismo-relay are documented here.
|
||||
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
|
||||
@@ -155,6 +459,46 @@ All notable changes to seismo-relay are documented here.
|
||||
- **CLAUDE.md "Where things stand"** now reflects the range fix.
|
||||
- Docs only: no code change, no migration.
|
||||
|
||||
### Migration
|
||||
|
||||
⚠ **Schema migration and backfill.** Rehearsed twice on a copy of prod's
|
||||
2026-09-30 snapshot (15,432 events), before and after the parity merge, with
|
||||
identical results.
|
||||
|
||||
**Before you start:**
|
||||
- `TOOL_VERSION` is bumped to **0.34.0**, which gates the regeneration, so no
|
||||
`--force` is needed.
|
||||
- **Back up `seismo_relay.db` first.**
|
||||
|
||||
**Then:**
|
||||
1. **Deploy.** On first start SFM migrates the database by itself.
|
||||
- The events table is re-keyed `UNIQUE(serial, timestamp, record_type)`
|
||||
(Migration 3): every row and id is kept and the indexes are rebuilt.
|
||||
Rehearsal: 0.27 s, every row identical, integrity ok.
|
||||
- `device_commands` is created.
|
||||
2. **In the `sfm` container, `python scripts/backfill_sidecars.py`** re-decodes
|
||||
every event file. ⚠ **Plan an overnight run:** the store holds about 64,000
|
||||
events after the 2200-day watcher forward, at about 1.5 files/s on the NAS,
|
||||
so roughly 12 hours.
|
||||
- **Every Series-3 histogram's time moves forward one second, in place**,
|
||||
with id and review state kept. Rehearsal: 9,852 moved, 0 refused, no id
|
||||
lost.
|
||||
- **The same-second waveform/histogram pairs coexist** (209 in the
|
||||
snapshot).
|
||||
- It also creates a row for any store file that never had one (341 in the
|
||||
snapshot): the known one-time behaviour, not duplicates.
|
||||
- **Report-less events** pick up every new field. **Report-paired events**
|
||||
keep the report's overlaid peaks, notes, sample rate and record time.
|
||||
3. **`python scripts/backfill_event_shape.py --db-path bridges/captures/seismo_relay.db
|
||||
--store-root bridges/captures/waveforms`** recomputes shape and offset
|
||||
metrics. Rehearsal: exit 0, `cleared_stale` 0.
|
||||
|
||||
**Terra-View** needs no change: it pairs twins by peak values and reads rows by
|
||||
id. Moving a histogram forward one second can carry an event across a
|
||||
deployment-window edge.
|
||||
|
||||
**Series-4** event times do not move.
|
||||
|
||||
## v0.33.0 — 2026-11-01
|
||||
|
||||
**SFM reads Series-3 events from the file alone, and proves it against
|
||||
|
||||
@@ -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
|
||||
@@ -45,13 +45,40 @@ Read this first when picking the project back up.
|
||||
- **Byte layouts** of every field read from the file:
|
||||
`docs/instantel_protocol_reference.md` Appendix **D.6**.
|
||||
|
||||
**Where the decoder stands on `dev`** (2026-11-03, run `20261103-121047`):
|
||||
**18 of 88 fields match on every event**, up from about 6 before v0.33.0.
|
||||
The four `dev` fixes below share one release and one backfill.
|
||||
**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).
|
||||
@@ -65,18 +92,14 @@ Read this first when picking the project back up.
|
||||
- ✅ **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; fixing it moves every stored
|
||||
histogram by 1 s, and the event key is (serial, time), so it needs a
|
||||
decision first)
|
||||
- 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, in the order proposed** (2026-11-03):
|
||||
- **A. Setup fields:** trigger source and levels, stop mode, mic type,
|
||||
display units, firmware version, serial number, calibration, battery.
|
||||
- **B. Histogram interval detail:** per-interval frequencies (#50: they
|
||||
assume 1024 sps), per-interval PVS, interval size, stop time.
|
||||
- **C. #51 timing:** start time, per-interval times, peak times.
|
||||
- ~~**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.**
|
||||
@@ -285,7 +308,7 @@ Read this first when picking the project back up.
|
||||
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, bench pending:** change a unit's settings by serial,
|
||||
**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):
|
||||
@@ -296,8 +319,17 @@ Read this first when picking the project back up.
|
||||
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`.
|
||||
- ⚠ Not yet sent to a unit. The MiniMate alarm level is read-only until a
|
||||
bench write is checked (`S3_ALARM_WRITE_MEASURED`).
|
||||
- **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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
@@ -647,18 +666,19 @@ Implementation steps (concrete):
|
||||
3. flip ingest so reports are kept only for checking (retire the overlay)
|
||||
4. stop the watchers forwarding reports
|
||||
|
||||
**Done so far: 18 of 88 report fields match on every DL2 event.**
|
||||
**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:**
|
||||
- setup fields still unread: trigger, stop mode, units, serial, calibration, battery
|
||||
- histogram interval detail: frequencies (#50), per-interval PVS, interval size, stop time
|
||||
- histogram start times (#51)
|
||||
- the values Blastware computes itself: ZC frequency, acceleration, displacement, time of peak
|
||||
- the sensor check results
|
||||
- the monitor log
|
||||
|
||||
@@ -11,7 +11,11 @@
|
||||
|
||||
| Date | Section | Change |
|
||||
|---|---|---|
|
||||
| 2026-11-03 | 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-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. |
|
||||
@@ -3800,28 +3804,156 @@ Each interval stores its peak vector sum **squared**:
|
||||
- **Verified:** interval psi mismatches fell from 42,783 to 26, and mic peak mismatches from 345
|
||||
to 40.
|
||||
|
||||
#### D.6.7 Not read from the file yet
|
||||
**Three things share the word "units". Keep them apart** (2026-11-03):
|
||||
|
||||
*Updated 2026-11-03. 18 of 88 report fields now match on every DL2 event.*
|
||||
| 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:**
|
||||
- trigger source and levels, stop mode, mic type, display units, firmware version, serial
|
||||
number, calibration, battery
|
||||
- per-interval frequencies (#50: they assume 1024 sps), per-interval PVS, interval size,
|
||||
histogram stop time
|
||||
- extended notes
|
||||
- the values Blastware computes: ZC frequency, acceleration, displacement, time of peak
|
||||
- sensor check results
|
||||
- monitor log
|
||||
- **Open cases:**
|
||||
- histogram start times are 1 s early (#51)
|
||||
- about 20 one-minute histograms with a mic peak an interval or two off
|
||||
- Blastware prints `OORANGE` when the vector sum alone exceeds the range (a carve-out still to
|
||||
prove)
|
||||
- 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)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2745,6 +2745,39 @@ were wrong.
|
||||
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.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# 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`); bench pending. Phase 5 of
|
||||
(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`.
|
||||
@@ -342,6 +343,37 @@ intervals 2/5/15/60/300/900 s, and each series' measured mode codes.
|
||||
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
|
||||
|
||||
@@ -61,7 +61,7 @@ _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, read; a write waits for the bench
|
||||
_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}
|
||||
|
||||
@@ -70,9 +70,10 @@ _RANGES = {"normal": 0, "sensitive": 1}
|
||||
# unknown -- SFM writes what Blastware writes. Series 3 only.
|
||||
S3_BLASTWARE_FIXED = {26: b"\x00\x00"}
|
||||
|
||||
# A Series-3 alarm-level write has never been seen; the bench measures one, with
|
||||
# Brian's go, before this turns on.
|
||||
S3_ALARM_WRITE_MEASURED = False
|
||||
# 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},
|
||||
|
||||
+9
-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
|
||||
@@ -113,9 +114,10 @@ def plan_call_home_enabled(call_home: bytes, enabled: bool) -> WritePlan:
|
||||
|
||||
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 "
|
||||
@@ -128,9 +130,10 @@ def plan_call_home_enabled(call_home: bytes, enabled: bool) -> WritePlan:
|
||||
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")
|
||||
|
||||
+143
-16
@@ -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,6 +33,50 @@ 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:
|
||||
@@ -40,6 +87,27 @@ class SfmSide:
|
||||
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,9 +137,46 @@ 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,
|
||||
@@ -82,6 +187,8 @@ def sfm_side(raw: bytes) -> SfmSide:
|
||||
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`."""
|
||||
|
||||
@@ -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,10 +94,13 @@ 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,
|
||||
)
|
||||
|
||||
@@ -106,4 +124,29 @@ INTERVAL_COUNT_IS_DURATION = Carveout(
|
||||
applies=_interval_count_is_duration,
|
||||
)
|
||||
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION, 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)
|
||||
+238
-28
@@ -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]:
|
||||
@@ -1047,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)."""
|
||||
@@ -1195,8 +1365,10 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
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":
|
||||
decoded = decode_histogram_body(body)
|
||||
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)
|
||||
@@ -1205,7 +1377,8 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
decoded = decode_waveform_v2(body)
|
||||
is_waveform_body = decoded is not None
|
||||
if decoded is None:
|
||||
decoded = decode_histogram_body(body)
|
||||
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) — "
|
||||
@@ -1236,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
|
||||
@@ -1266,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:
|
||||
@@ -1298,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
|
||||
@@ -1327,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:
|
||||
|
||||
@@ -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 ───────────────────────────────────────────────
|
||||
@@ -548,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
|
||||
|
||||
@@ -185,14 +185,26 @@ class ImageRefused(ValueError):
|
||||
# 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]") -> bytes:
|
||||
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."""
|
||||
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]
|
||||
return b"".join(p[1:] for p in parts[:-1]) + (parts[-1] if parts else b"")
|
||||
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:
|
||||
@@ -621,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
|
||||
|
||||
@@ -1074,11 +1090,11 @@ class MiniMateProtocol:
|
||||
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 ((0x0400, 0x00), (0x0400, 0x04), (0x002A, 0x08)):
|
||||
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)
|
||||
return assemble_compliance_content(frames, lengths=tuple(o for o, _ in _COMPLIANCE_READ_STEPS))
|
||||
|
||||
# ── Write commands (SUBs 68–83) ───────────────────────────────────────────
|
||||
|
||||
|
||||
+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
|
||||
|
||||
|
||||
@@ -69,7 +69,12 @@ _S3_SETTINGS_STEPS = ((0x68, "event index (as read)"), (0x73, "confirm B"),
|
||||
(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; effect unmeasured)")
|
||||
"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"}
|
||||
|
||||
@@ -525,7 +530,7 @@ class Series3Adapter:
|
||||
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_TAIL_WARNING]}
|
||||
"revision": st["revision"], "warnings": [_S3_MENU_WARNING, _S3_TAIL_WARNING]}
|
||||
|
||||
def send() -> dict:
|
||||
b = st["blocks"]
|
||||
|
||||
@@ -34,6 +34,14 @@ Layout written to `<filename>.h5`:
|
||||
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
|
||||
@@ -262,6 +270,24 @@ def write_event_hdf5(
|
||||
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)
|
||||
@@ -283,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:
|
||||
|
||||
+33
-6
@@ -134,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:
|
||||
|
||||
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>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"
|
||||
@@ -365,3 +365,160 @@ def test_a_waveform_with_the_early_record_is_timed_from_its_trigger():
|
||||
# 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):
|
||||
|
||||
+137
-3
@@ -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
|
||||
|
||||
|
||||
@@ -95,7 +97,7 @@ def test_zc_frequency_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)
|
||||
|
||||
@@ -221,3 +223,135 @@ def test_blastware_counting_the_monitoring_time_is_accepted():
|
||||
|
||||
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])
|
||||
@@ -231,3 +231,11 @@ def test_push_config_raw_writes_a_logical_block_with_a_literal_escape_byte_intac
|
||||
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"])
|
||||
@@ -426,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):
|
||||
@@ -442,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)
|
||||
@@ -498,3 +499,45 @@ def test_a_letterless_stored_name_still_matches_a_lettered_download(sdm):
|
||||
store, db = sdm
|
||||
_stored_as(store, db, "K441LTOK.QZ0")
|
||||
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).
|
||||
|
||||
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("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
|
||||
_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():
|
||||
|
||||
@@ -695,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
|
||||
@@ -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)
|
||||
|
||||
@@ -99,3 +99,53 @@ def test_read_compliance_content_refuses_a_missing_frame():
|
||||
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
|
||||
@@ -196,11 +196,17 @@ def test_field_not_offered_for_the_series():
|
||||
_refused(S4_BLOCK, 4, {"no_such_field": 1})
|
||||
|
||||
|
||||
def test_alarm_is_read_only_until_measured():
|
||||
assert sf.S3_ALARM_WRITE_MEASURED is False
|
||||
_refused(S3_BLOCK, 3, {"geo_alarm_ips": 1.0})
|
||||
def test_the_alarm_is_writable_since_the_bench():
|
||||
# Bench 2026-11-04, BE9441: 1.0 -> 1.5 -> 1.0, 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).
|
||||
assert sf.S3_ALARM_WRITE_MEASURED is True
|
||||
assert check_changes(S3_BLOCK, 3, {"geo_alarm_ips": 1.5}) == {"geo_alarm_ips": 1.5}
|
||||
alarm = next(d for d in editable_fields(S3_BLOCK, 3) if d["field"] == "geo_alarm_ips")
|
||||
assert alarm["readonly"] is True
|
||||
assert alarm["readonly"] is False
|
||||
out = encode_setup(S3_BLOCK, 3, {"geo_alarm_ips": 1.5})
|
||||
assert [i for i in range(2090) if out[i] != S3_BLOCK[i] and i not in (26, 27)] == [1747, 1795, 1843]
|
||||
_refused(S4_BLOCK, 4, {"geo_alarm_ips": 1.5}) # still Series 3 only
|
||||
|
||||
|
||||
def _with_unit(block: bytes, unit: bytes) -> bytes:
|
||||
|
||||
Reference in new issue
Block a user