Compare commits
10
Commits
v0.34.0
...
7b45647b23
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b45647b23 | ||
|
|
47da0ddef0 | ||
|
|
89c5234ac0 | ||
|
|
d2fe675650 | ||
|
|
6591b09b31 | ||
|
|
8e9a3ac9cf | ||
|
|
b53de5448f | ||
|
|
f5feb0eabc | ||
|
|
8d5c16b03b | ||
|
|
9091fe75a9 |
No files matched your search
@@ -4,6 +4,68 @@ All notable changes to seismo-relay are documented here.
|
||||
|
||||
---
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **ZC frequency, peak displacement and times of peak come from the unit's own
|
||||
event summary** (group D, part 2 of the file-only decode;
|
||||
`feat/waveform-zc-displacement`, merged 2026-11-06). Measured on DL2
|
||||
2026-11-05.
|
||||
- **Where they are:** every event file carries the unit's per-channel
|
||||
summary right after its embedded event record. It is a chain of
|
||||
`[length][id][payload]` records, ids `0x32`–`0x35`, each holding min, max,
|
||||
peak sample, half-period and a displacement integral (reference D.6.12).
|
||||
Blastware prints these values as they are.
|
||||
- **ZC frequency** = (rate / 2) / half-period, on every record type. It
|
||||
matches 25,966 / 25,966 waveform and 253,958 / 253,958 histogram channel
|
||||
values, including the words (">100", "N/A", "<1.0"). Above range the value
|
||||
is Blastware's threshold, flagged, as when it comes from a report.
|
||||
- **Peak displacement** = half the integral (new
|
||||
`PeakValues.*_peak_disp_in`): 19,479 / 19,479.
|
||||
- **Times of peak and the vector-sum time** now come from the unit's peak
|
||||
samples. They differ from the samples' own only on O117I1NK.R70W, whose
|
||||
stored samples wrap at the trigger. Blastware's own sample table has the
|
||||
same wrapped values.
|
||||
- **Why recomputing failed:** from the samples, ZC frequency had matched 46%
|
||||
and displacement 84%. The unit computes them at full resolution.
|
||||
- **Peak acceleration** stays Blastware's own computation from the samples.
|
||||
The unit stores its own largest step too (`[15:21]`, inferred), and
|
||||
Blastware ignores it.
|
||||
- **Decode checker:** 59 of 88 fields now match on every DL2 event, 47 before
|
||||
group D (run `20261105-140021`, 0 regressions). Still open: O117I1NK's three
|
||||
accelerations and S353I5PZ.EP0W's Vert acceleration.
|
||||
- ⚠ **Operational:** codec change.
|
||||
- The next release bumps `TOOL_VERSION`, then runs `backfill_sidecars.py`
|
||||
and `backfill_event_shape.py`: about 8 h on the NAS (v0.34.0's took
|
||||
13:13 → 21:16 on 2026-11-05).
|
||||
- No schema change, no migration, and no stored time moves.
|
||||
- **Report-less events gain a ZC frequency** in the existing `*_zc_freq` /
|
||||
`*_zc_above_range` columns, so Terra-View shows a frequency where it
|
||||
showed "—".
|
||||
- Report-paired events keep the report's values, which are equal. A
|
||||
report's "<1.0" still overlays as no value until the overlay is retired.
|
||||
- Displacement and times of peak are not stored in the DB or `.h5` yet.
|
||||
|
||||
### Fixed
|
||||
- **The decode checker reads the mic's above-range ZC flag under its real name**
|
||||
(`mic_zc_above_range`). A mic ">100" could never match before.
|
||||
|
||||
### Protocol / Documentation
|
||||
- **Reference D.6.12 (new):**
|
||||
- the unit's event summary: its layout, and what Blastware prints from it
|
||||
- why recomputing failed
|
||||
- the two odd 2019 files
|
||||
- group D part 1 (time of peak, acceleration with the fitted g),
|
||||
documented there too
|
||||
- **Reference §7.8.9:** its "constant, meaning ❓" bytes amended in place. They
|
||||
are the vector-sum peak's sample, then the next record's lead.
|
||||
- **Reference D.6.11 and CLAUDE.md:** the 59 / 88 status. Leads for E: records
|
||||
`0x3c` / `0x3d`, probably the sensor check. Leads for F: a waveform's
|
||||
monitor log may be its event record's start and stop.
|
||||
- **Reference D.6, "Reading a mismatch":** 256, 4,096 and 65,536 mean a number
|
||||
outgrew its 8-, 12- or 16-bit box. Every case so far is listed (Brian's
|
||||
observation, 2026-11-05).
|
||||
|
||||
## v0.34.0 — 2026-11-04
|
||||
|
||||
**SFM reaches Series-4 parity, and reads most of Blastware's report from the
|
||||
|
||||
@@ -10,7 +10,7 @@ pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
|
||||
|
||||
---
|
||||
|
||||
## Where things stand (updated 2026-11-03)
|
||||
## Where things stand (updated 2026-11-05)
|
||||
|
||||
Read this first when picking the project back up.
|
||||
|
||||
@@ -45,10 +45,12 @@ 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-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.
|
||||
**Where the decoder stands on `dev`** (2026-11-05, run `20261105-140021`):
|
||||
**59 of 88 fields match on every event**, up from about 6 before v0.33.0 and
|
||||
47 before group D.
|
||||
- Groups A, B, C and D part 1 shipped in v0.34.0 (#50, #51).
|
||||
- D part 2 (the unit's own summary) is on `dev` and owes the next release
|
||||
a backfill.
|
||||
- 🔑 **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
|
||||
@@ -66,6 +68,15 @@ Read this first when picking the project back up.
|
||||
- group B (`dev`, D.6.9): interval frequencies, vector sums, size, stop
|
||||
- group C (`dev`, D.6.10): histogram start and stop from the histogram's
|
||||
own event record, interval times, and the peak dates and times
|
||||
- group D (D.6.12): ZC frequency on every record type, peak displacement,
|
||||
times of peak and the vector-sum time.
|
||||
- These are **the unit's own values**, stored in the file right after
|
||||
the event record. Blastware prints them; recomputing from the samples
|
||||
reached only 46% and 84%.
|
||||
- Peak acceleration is Blastware's own computation from the samples
|
||||
(fitted g 386.2238): 6,522–6,523 / 6,524. The unit stores its own
|
||||
too, which Blastware ignores. The misses are O117I1NK.R70W, whose
|
||||
samples wrap at the trigger, and S353I5PZ.EP0W Vert (open).
|
||||
- 🔑 **"Units" means three different things — keep them apart** (reference
|
||||
D.6.6):
|
||||
- **Recorded data:** the mic samples and interval peaks in the file, as
|
||||
@@ -100,10 +111,14 @@ Read this first when picking the project back up.
|
||||
- ~~**B. Histogram interval detail**~~ ✅ done on `dev`. Frequencies (#50),
|
||||
per-interval PVS, interval size, stop.
|
||||
- ~~**C. #51 timing**~~ ✅ done on `dev`.
|
||||
- **D. Blastware's waveform calculations:** ZC frequency, acceleration,
|
||||
displacement, time of peak.
|
||||
- **E. Sensor check results.**
|
||||
- **F. Monitor log:** probably not in the event file at all.
|
||||
- ~~**D. Blastware's waveform calculations**~~ ✅ done. ZC frequency,
|
||||
displacement and time of peak are the unit's own (D.6.12); acceleration
|
||||
is Blastware's.
|
||||
- **E. Sensor check results.** Probably records `0x3c` / `0x3d`, which
|
||||
follow the unit's summary (inferred, D.6.12).
|
||||
- **F. Monitor log:** probably not in the event file at all. Lead, not
|
||||
measured: O117I1NK's report prints its log as the event record's
|
||||
start – stop.
|
||||
- 🔶 **#48 is still open.** The event file's setup block puts the pre-trigger
|
||||
where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though,
|
||||
it is **each event's own pre-trigger**, not the setting: 253–256 samples at
|
||||
@@ -325,9 +340,12 @@ Read this first when picking the project back up.
|
||||
- ⚠ **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.
|
||||
- ~~⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data
|
||||
(about 1 frame in 85).~~ **Fixed in the parser (#58, 2026-11-06, measured):**
|
||||
a checksum of 02/03/04 arrives as `10 X`, and that `10` is never data (7,747 /
|
||||
7,747 recorded replies check). It had misread 1C battery/memory (419.84 V) and
|
||||
the 2C call-home read; the 5A file builder's own compensation is gone with it,
|
||||
and pre-fix `.a5.pkl` frames are converted on load (pickle version 2).
|
||||
- ⚠ The Micromate scheduler switch is not in any block SFM reads, so a leftover
|
||||
schedule blocks a change even with the scheduler Off.
|
||||
**Ring path measured the same night:** with THOR's watchdog off, a call-home
|
||||
@@ -460,9 +478,11 @@ Read this first when picking the project back up.
|
||||
retracted 5A model: SUB 71's "offset 0x1004" reads as length 0x0400 escaped, and
|
||||
Blastware escapes `03` in write data. A write whose payload holds a bare
|
||||
02/03/04/10 may be malformed. One Blastware config-write capture settles it.
|
||||
🔑 **Replies follow the same rule (measured, 748/748):** every 02/03/04/10 escaped,
|
||||
checksum = SUM8 of the unescaped payload. The "S3 checksums frequently fail" belief
|
||||
is `S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it.
|
||||
🔑 **Replies follow the same rule (measured, 748/748; 7,747 / 7,747 across every
|
||||
recording, #58):** every 02/03/04/10 escaped, the checksum too, and checksum = SUM8
|
||||
of the unescaped payload. The "S3 checksums frequently fail" belief was
|
||||
`S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it
|
||||
(fixed 2026-11-06: `checksum_valid` holds on every recorded reply).
|
||||
~~**⚠ KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB.**~~
|
||||
`parse_strt_end_offset()` returns only `(end_key[2] << 8) | end_key[3]`,
|
||||
discarding the key's page byte. An event starting at `0x0111F2A2` and ending
|
||||
@@ -2011,7 +2031,8 @@ A re-analysis in the prior session incorrectly concluded `section[1]` is always
|
||||
and is device-specific. The 2026-04-09 re-analysis confirms `section[1]` was right.
|
||||
|
||||
**IMPORTANT — `frame.data` has checksum already stripped** by `S3FrameParser._finalise()`
|
||||
(`raw_payload = body[:-1]`; `data = raw_payload[5:]`). There is NO trailing checksum byte in
|
||||
(`raw_payload` = the body less its checksum, and less the `10` of an escaped one since #58;
|
||||
`data = raw_payload[5:]`). There is NO trailing checksum byte in
|
||||
`section`. All relative-from-end offsets must account for this.
|
||||
|
||||
Battery and memory fields are present in **both** states:
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
| Date | Section | Change |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | §3 (replies), SUB 1C, 2C, 15, 5A file build | ✅ **An escaped checksum is the checksum, not data (#58, measured).** A reply whose checksum is 02, 03 or 04 sends it as `10 X`, and `S3FrameParser` kept that `10` as the frame's last data byte (first seen on BE9441's 1A read, 2026-11-04). **Across every recorded reply** (60 captures, March to October 2026, three units) SUM8 of the unescaped payload is the checksum on **7,747 / 7,747**, widening 2026-10-26 (4)'s 748 / 748. **272** checksums arrived escaped; every one checks as an escape pair, and no checksum ever arrived as a bare 02/03/04. **What the stray byte did:** **SUB 1C** battery and memory are counted from the end, so 12 of 760 recorded status replies read 419.84 V and 251,654,656 bytes (for 6.76 V and 983,026). A **SUB 2C** call-home read came out one byte long and was refused as "monitoring". The **SUB 15 probe reply** (`00 00 00 00 0a …`, the same on BE11529, BE18189 and BE9441) always has an escaped checksum: 230 of the 272, harmless, as nothing reads it. The **5A file builder** had compensated since 2026-04-21 (the "split pair" rule). With the parser fixed, that rule would drop a real `0x10` ending a chunk (one A5 chunk in ten ends in one; none recorded with an escaped checksum as well), so it is removed. The 1A and 09 reads' length trims (2026-11-04) stay as guards. `checksum_valid` now sums the unescaped payload, and every recorded reply checks. |
|
||||
| 2026-11-05 | Appendix D.6.12 (NEW), D.6.11, §7.8.9 | ✅ **The unit's own event summary, in every event file.** The embedded event record is the first of a `[length][id][payload]` chain. It holds the vector-sum peak's sample (6,492 / 6,493). Then one 22-byte record per channel, ids `0x32` Tran … `0x35` MicL: min, max, peak sample, **half-period** and a **displacement integral**. Blastware prints them as they are. **ZC frequency** = (rate / 2) / half-period, with the interval rule's words: 25,966 / 25,966 waveform and 253,958 / 253,958 histogram channel values. **Peak displacement** = half the integral: 19,479 / 19,479. Recomputing from the samples had reached 46% and 84%: the unit works at full resolution. **Times of peak** follow the unit's peak sample. That differs from the samples only on **O117I1NK.R70W**, whose stored samples wrap at the trigger by 65,536 counts (Blastware's own table has the same values). Peak acceleration is Blastware's own computation from the stored samples (group D part 1, documented here too). The unit stores its own largest step at `[15:21]` (inferred), which Blastware does not print. §7.8.9's "constant, meaning ❓" bytes amended in place. 59 of 88 report fields now match on every DL2 event (47 before group D). |
|
||||
| 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. |
|
||||
@@ -2277,6 +2279,13 @@ labels "unknown", after the notes and channel blocks.
|
||||
| `[M+10:M+18]` | **stop**, same format | = the footer's `ts2` on 7,836; one second before it on 99 ✅ |
|
||||
| `[M+18:M+40]` | `[+18]` `00` (7,933/7,935), `[+22:24]` `00 00`, `[+26:34]` eight `00`, `[+36]` `00`, `[+37:39]` `16 32`, `[+39]` `00` | constant; meaning ❓ |
|
||||
|
||||
> ⚠ **AMENDED 2026-11-05 (measured on DL2):** the record is the first of a chain of
|
||||
> `[length uint16 BE][id][payload]` records. `00 28 05` is length 40 and id `0x05`, so the
|
||||
> next record starts at `M + 36`. `[M+22:M+26]` is the vector-sum peak's sample, a uint32 BE
|
||||
> (its high bytes are the `00 00` above). The bytes from `[+36]` are the next record's lead,
|
||||
> `00 16 32`: the unit's per-channel summary. Layout and what Blastware prints from it:
|
||||
> Appendix D.6.12.
|
||||
|
||||
**Relations** (7,935/7,935): footer `ts1` (session start) ≤ trigger ≤ stop; and
|
||||
`(stop - trigger) - record time` lies in −3 … +6 s.
|
||||
|
||||
@@ -3642,6 +3651,22 @@ Each field was proven by the decode checker, `scratch/check_s3_decode.py`. It co
|
||||
decode with Blastware's `_XML.XML` report for every DL2 event: 70,042 events, 2016–2026, local
|
||||
copy in `~/dl2-archive`. Counts below are from that archive unless stated otherwise.
|
||||
|
||||
> 🔑 **Reading a mismatch: 256, 4,096 and 65,536 mean a number outgrew its box** (Brian,
|
||||
> 2026-11-05). These are 2⁸, 2¹² and 2¹⁶: how many values an 8-, 12- or 16-bit field can hold.
|
||||
> When a value is off by exactly one of them, or stops at one, suspect the storage, not the
|
||||
> physics. Every case so far:
|
||||
>
|
||||
> | Seen as | Box | Cause |
|
||||
> |---|---|---|
|
||||
> | O117I1NK's samples off by 65,536 counts at the trigger, the mic's by 4,096 (D.6.12) | 16-bit sample (12-bit mic) | the unit wrote a value beyond the range; it rolled over |
|
||||
> | the unit's largest step stored × 65,536 (D.6.12) | 16.16 fixed point | whole part in the top 16 bits, fraction in the bottom 16 |
|
||||
> | histogram PVS² high word non-zero above 1.28 in/s (D.6.5) | 16-bit half of a uint32 | 1.28 in/s = 256 units, and 256² = 65,536 |
|
||||
> | histogram peaks clipped at 1.275 in/s until 2026-08-25 | one byte read where the value is 16-bit | 255 units is the most a byte holds |
|
||||
> | the 5A walk failing past 64 KB until 2026-10-26 (§7.8) | 16-bit address | addresses roll over every 65,536 bytes |
|
||||
>
|
||||
> The geophone's full scale is 32,000 counts, deliberately short of the 16-bit limit (32,767):
|
||||
> that one is a design margin, not an overflow.
|
||||
|
||||
#### D.6.1 Record type — `STRT[18]` ✅
|
||||
|
||||
| `STRT[18]` | Type | DL2 |
|
||||
@@ -3935,12 +3960,17 @@ All four channels match every DL2 histogram.
|
||||
|
||||
#### D.6.11 Not read from the file yet
|
||||
|
||||
*Updated 2026-11-03. 47 of 88 report fields now match on every DL2 event.*
|
||||
*Updated 2026-11-05. 59 of 88 report fields now match on every DL2 event, up from 47
|
||||
before group D (run `20261105-140021`, 0 regressions).*
|
||||
- **Fields not read yet:**
|
||||
- extended notes
|
||||
- the values Blastware computes: ZC frequency, acceleration, displacement, time of peak
|
||||
- sensor check results
|
||||
- sensor check results (probably the records after the unit's summary, `0x3c` / `0x3d`;
|
||||
inferred, D.6.12)
|
||||
- monitor log
|
||||
- ~~the values Blastware computes: ZC frequency, acceleration, displacement, time of peak~~
|
||||
**Read, 2026-11-04 → 05 (D.6.12).** Blastware prints the unit's own ZC frequency,
|
||||
displacement and time of peak, all stored in the file. Acceleration is the exception:
|
||||
the unit stores its own, but Blastware prints its own computation from the samples.
|
||||
- **Open cases:**
|
||||
- about 20 one-minute histograms with a mic peak an interval or two off
|
||||
- Blastware prints `OORANGE` when an event's vector sum alone exceeds the range, with no
|
||||
@@ -3955,6 +3985,69 @@ All four channels match every DL2 histogram.
|
||||
- histogram interval detail: frequencies (#50), vector sums, interval size, stop (D.6.9)
|
||||
- histogram start, stop, interval and peak times (#51, D.6.10)
|
||||
|
||||
#### D.6.12 Peak detail — the unit's own event summary ✅ 2026-11-05
|
||||
|
||||
**The embedded event record (§7.8.9, D.6.10) is the first of a chain** of
|
||||
`[length uint16 BE][id][payload]` records: the next one starts `length + 2` bytes after a
|
||||
record's lead. `00 28 05` is length 40 and id `0x05`. Measured on the 6,493 DL2 waveforms and
|
||||
63,500 histograms that have a Blastware report.
|
||||
|
||||
**The event record**, offsets from its marker `M` as in §7.8.9:
|
||||
|
||||
| bytes | content |
|
||||
|---|---|
|
||||
| `[M+22:M+26]` | the vector-sum peak's sample, uint32 BE: SFM's own vector-sum peak on 6,492 / 6,493 (the other is O117I1NK, below) |
|
||||
| `[M+18:M+22]`, `[M+26:M+36]` | not identified ❓ |
|
||||
|
||||
**Then one record per channel**, length 22: ids `0x32` Tran, `0x33` Vert, `0x34` Long,
|
||||
`0x35` MicL. A unit without a mic has no `0x35` (6 DL2 files).
|
||||
|
||||
| payload | content |
|
||||
|---|---|
|
||||
| `[0]` | `00` on all 25,966 waveform channels |
|
||||
| `[1:3]` | min, int16 BE: geophones in decoder units of 16 counts (0.005 in/s at Normal), the mic in counts |
|
||||
| `[3:5]` | max, the same |
|
||||
| `[5:9]` | the peak's sample, uint32 BE |
|
||||
| `[9:11]` | **half-period**, samples, uint16 BE |
|
||||
| `[11:15]` | **displacement integral**, uint32 BE, in units × samples |
|
||||
| `[15:21]` | 🔶 **the unit's own largest sample-to-sample step**, × 65,536 (16.16 fixed point, units), read as one 48-bit BE integer. It is the stored samples' largest step plus 0 to 1 unit (median +0.5) on 19,479 geophone channels, so probably the same step at full resolution (inferred). Blastware does not print it: see peak acceleration below |
|
||||
|
||||
On a waveform, min, max and peak sample are the decoded samples' own on 25,962 / 25,966
|
||||
channels. The 4 others are O117I1NK (below).
|
||||
|
||||
**Then records `0x3c` (and on a histogram `0x3d`)**, length 202–212. Not read yet. Probably
|
||||
the sensor check, before and after (inferred, not measured).
|
||||
|
||||
**What Blastware prints from them.** It prints the unit's values; it does not recompute them:
|
||||
|
||||
| Field | Rule | DL2 |
|
||||
|---|---|---|
|
||||
| ZC frequency, every record type | (rate / 2) / half-period. "N/A" at 0; `>100` (`>200` at 2048 sps, `>400` at 4096) at 5 samples or fewer; `<1.0` when the half-period exceeds rate / 2. The histogram interval rule (D.6.9) | waveforms 25,966 / 25,966 channel values (15,844 numbers); histograms 253,958 / 253,958 (104,000 numbers) |
|
||||
| Peak displacement (waveform) | half the integral: integral × 16 counts × in/s per count (the range's, D.6.4) ÷ rate ÷ 2, in inches | 19,479 / 19,479 |
|
||||
| Time of peak (waveform) | (peak sample − pre-trigger samples) ÷ rate | as the samples' own, except O117I1NK, where Blastware prints the summary's |
|
||||
| Vector-sum time (waveform) | the same, from the event record's sample | 6,492 / 6,493 from the samples; O117I1NK prints the record's |
|
||||
| Peak acceleration (waveform) | **Blastware's own**, from the stored samples: the largest \|v[i+1] − v[i]\| × rate ÷ g, with its g fitted to [386.2236, 386.2240] in/s² by every DL2 value (9.81 m/s² is 386.2205; the standard 9.80665 fits 17,806). The unit's own step (`[15:21]`) would match only 879 | 19,475 / 19,479 |
|
||||
|
||||
**Why recomputing failed.** ZC frequency recomputed from the samples matched 46% (the
|
||||
half-cycle at the peak), and 80% with each crossing interpolated at ±16 counts. Displacement
|
||||
matched 84% (half the largest half-cycle integral, the manuals' method). The unit works at
|
||||
full resolution: a stored sample of ±16 counts hides anything from 1 to 31.
|
||||
|
||||
**O117I1NK.R70W (2019): clipped, and its samples wrap.**
|
||||
- **The wrap:** at the trigger (sample 254), every stored sample is off by exactly 65,536
|
||||
counts (4,096 on the mic). Tran reads +26,832 where the summary's min is −38,704 (−12.1 in/s).
|
||||
- **Blastware decodes the same:** its own sample table has the same wrapped values (Tran
|
||||
8.385 in/s).
|
||||
- **It prints the summary:** `OORANGE`, and time of peak 0.000 on all four channels and on
|
||||
the vector sum.
|
||||
- **Its accelerations** equal the summary's max − min in one sample step: 48.28, 46.93 and
|
||||
49.12 g, all exact. One file. Inferred: Blastware's acceleration sees the summary's extreme
|
||||
at its peak sample. SFM does not do this.
|
||||
|
||||
**S353I5PZ.EP0W Vert (open).** Blastware's acceleration (0.027 g) skips one 80-count step,
|
||||
from sample 4,096 to 4,097, which its own sample table shows. Not explained. Skipping every
|
||||
4,096-sample boundary fixes this file but breaks another.
|
||||
|
||||
---
|
||||
|
||||
*All findings reverse-engineered from live RS-232 bridge captures.*
|
||||
|
||||
@@ -104,17 +104,11 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture):
|
||||
DLE strip rule (applied AFTER slicing):
|
||||
Strip any 0x10 byte that is immediately followed by 0x02, 0x03, or 0x04.
|
||||
This undoes the DLE-escape that S3FrameParser preserves as literal pairs.
|
||||
Applied to frame.data[skip:] + bytes([frame.chk_byte]) together, then
|
||||
conditionally exclude the trailing chk_byte from the output.
|
||||
|
||||
chk_byte absorption:
|
||||
When frame.data[-1] == 0x10 AND frame.chk_byte ∈ {0x02, 0x03, 0x04},
|
||||
the last byte of frame.data is the DLE prefix of a split DLE+chk pair.
|
||||
Including chk_byte in the strip buffer allows the pair to be stripped as
|
||||
a unit. After stripping, the trailing chk_byte is ALWAYS removed — because
|
||||
_strip_inner_frame_dles keeps the byte after the DLE (the chk_byte value),
|
||||
and that value is the checksum, never payload. This applies to all three
|
||||
cases (chk ∈ {0x02, 0x03, 0x04}) identically.
|
||||
chk_byte absorption (retired 2026-11-06, #58):
|
||||
The escape 0x10 of a checksum sent as `10 02/03/04` used to stay at the end
|
||||
of frame.data, and this builder dropped it here. The parser now drops it,
|
||||
so a 0x10 ending frame.data is real data (one A5 chunk in ten ends in one).
|
||||
|
||||
MLG CRC:
|
||||
The algorithm that produces the 2-byte CRC at the start of each MLG record
|
||||
@@ -297,29 +291,16 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes:
|
||||
Extract the waveform body contribution from one A5 S3Frame.
|
||||
|
||||
The contribution is frame.data[skip:] with inner-frame DLE pairs stripped
|
||||
per _strip_inner_frame_dles(). The chk_byte is temporarily appended before
|
||||
stripping to handle the split-pair edge case where a DLE at the end of
|
||||
frame.data is paired with chk_byte.
|
||||
per _strip_inner_frame_dles().
|
||||
|
||||
Split-pair edge case (confirmed for A5[8] of M529LIY6 (example event), 2026-04-21):
|
||||
|
||||
S3FrameParser appends DLE+XX pairs as two literal bytes when XX ∉ {DLE, ETX}.
|
||||
When the LAST occurrence of such a pair straddles the payload/checksum boundary
|
||||
(i.e., DLE is the last byte of raw_payload and XX is the checksum), the parser
|
||||
splits them:
|
||||
- DLE ends up as the last byte of frame.data (frame.data[-1] == 0x10)
|
||||
- XX is stored as frame.chk_byte
|
||||
|
||||
To strip the pair correctly, we reunite the bytes before calling the strip
|
||||
function. Since chk_byte is the checksum (not payload data), it is excluded
|
||||
from the final output regardless of whether it was part of a pair.
|
||||
|
||||
Post-strip chk_byte removal (ALL cases):
|
||||
_strip_inner_frame_dles strips the 0x10 and KEEPS chk_byte in all cases.
|
||||
Chk_byte is always the checksum (not payload), so always strip it off.
|
||||
Until #58 (2026-11-06) an escaped checksum (`10 02/03/04`) left its 0x10 as
|
||||
the last byte of frame.data, and this function dropped it by pairing it with
|
||||
chk_byte (first seen on A5[8] of M529LIY6, 2026-04-21). The parser drops it
|
||||
now, so a 0x10 here is data and is kept.
|
||||
|
||||
Args:
|
||||
frame: S3Frame with frame.data and frame.chk_byte populated.
|
||||
frame: S3Frame from S3FrameParser (or a store pickle loaded by
|
||||
WaveformStore.load_a5, which converts pre-#58 frames).
|
||||
skip: Number of leading bytes in frame.data to exclude (frame header).
|
||||
|
||||
Returns:
|
||||
@@ -327,28 +308,7 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes:
|
||||
"""
|
||||
if skip >= len(frame.data):
|
||||
return b""
|
||||
|
||||
relevant = frame.data[skip:]
|
||||
|
||||
# Detect split DLE+chk pair at the frame boundary.
|
||||
has_split_pair = (
|
||||
len(relevant) > 0
|
||||
and relevant[-1] == 0x10
|
||||
and frame.chk_byte in {0x02, 0x03, 0x04}
|
||||
)
|
||||
|
||||
if has_split_pair:
|
||||
# Reunite the split pair so the strip function sees both bytes together.
|
||||
buf = relevant + bytes([frame.chk_byte])
|
||||
stripped = _strip_inner_frame_dles(buf)
|
||||
# _strip_inner_frame_dles strips the DLE (0x10) and KEEPS chk_byte.
|
||||
# chk_byte is the received checksum — never payload — so remove it.
|
||||
# This is correct for all values in {0x02, 0x03, 0x04}.
|
||||
if stripped:
|
||||
stripped = stripped[:-1]
|
||||
return stripped
|
||||
else:
|
||||
return _strip_inner_frame_dles(relevant)
|
||||
return _strip_inner_frame_dles(frame.data[skip:])
|
||||
|
||||
|
||||
# ── Filename helper ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -2354,8 +2354,9 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
|
||||
header, so field offsets below are relative to data[11]).
|
||||
|
||||
NOTE: frame.data has the checksum byte already stripped by S3FrameParser
|
||||
(_finalise returns raw_payload[5:] where raw_payload = body[:-1]).
|
||||
There is NO trailing checksum byte in section.
|
||||
(_finalise returns raw_payload[5:], the checksum and, since #58, the 10 of
|
||||
an escaped checksum removed). There is NO trailing checksum byte in section;
|
||||
before #58 one status reply in 63 kept that 10 and read 419.84 V.
|
||||
|
||||
Monitoring flag (confirmed 4-8-26/2ndtry, byte diff of all 144 data frames):
|
||||
section[1] == 0x00 → idle
|
||||
|
||||
@@ -145,9 +145,18 @@ def sfm_side(raw: bytes) -> SfmSide:
|
||||
("PeakVectorSumTimeSum", pv.pvs_time),
|
||||
("TranPeakAcceleration", pv.tran_peak_accel_g),
|
||||
("VertPeakAcceleration", pv.vert_peak_accel_g),
|
||||
("LongPeakAcceleration", pv.long_peak_accel_g)):
|
||||
("LongPeakAcceleration", pv.long_peak_accel_g),
|
||||
("TranPeakDisplacement", pv.tran_peak_disp_in),
|
||||
("VertPeakDisplacement", pv.vert_peak_disp_in),
|
||||
("LongPeakDisplacement", pv.long_peak_disp_in)):
|
||||
if value is not None:
|
||||
values[tag] = value
|
||||
# The unit's ZC frequency, every record type. Above range it is judged
|
||||
# by its flag (_compare_scalar); below 1 Hz Blastware prints a word.
|
||||
for tag, hz in (("TranZCFreq", pv.tran_zc_freq), ("VertZCFreq", pv.vert_zc_freq),
|
||||
("LongZCFreq", pv.long_zc_freq), ("MicLZCFreq", pv.mic_zc_freq)):
|
||||
if hz is not None:
|
||||
values[tag] = "<1.0" if hz < 1.0 else hz
|
||||
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
|
||||
@@ -264,7 +273,8 @@ def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> Fie
|
||||
return FieldResult(tag, "sfm_blank", printed, None)
|
||||
if printed.startswith(">"):
|
||||
# ZC frequency above range: SFM agrees only by setting its flag.
|
||||
flag = getattr(sfm.event.peak_values, tag[:-len("ZCFreq")].lower() + "_zc_above_range", False)
|
||||
ch = tag[:-len("ZCFreq")].lower()
|
||||
flag = getattr(sfm.event.peak_values, ("mic" if ch == "micl" else ch) + "_zc_above_range", False)
|
||||
return FieldResult(tag, "match" if flag else "mismatch", printed, str(value))
|
||||
if printed == "OORANGE":
|
||||
return FieldResult(tag, "mismatch", printed, str(value))
|
||||
|
||||
+114
-20
@@ -31,7 +31,8 @@ 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 channels_from_records, decode_histogram_body, decode_histogram_body_full
|
||||
from .histogram_codec import (channels_from_records, decode_histogram_body, decode_histogram_body_full,
|
||||
half_period_to_hz)
|
||||
|
||||
# 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
|
||||
@@ -833,6 +834,47 @@ def _waveform_peak_detail(pv: PeakValues, samples: dict[str, list[int]], geo_fs_
|
||||
pv.pvs_time = (j - pretrig) / sample_rate
|
||||
|
||||
|
||||
def _zc_from_half_period(halfp: int, sample_rate: int) -> tuple[Optional[float], bool]:
|
||||
"""(ZC frequency, above range) as Blastware reports it: None for a
|
||||
half-period of 0 ("N/A"); Blastware's threshold, flagged, at 5 samples or
|
||||
fewer (">100", ">200" at 2048 sps); else (rate / 2) / half-period, which
|
||||
Blastware prints as "<1.0" below 1 Hz."""
|
||||
if halfp == 0:
|
||||
return None, False
|
||||
hz = half_period_to_hz(halfp, sample_rate)
|
||||
if hz is None:
|
||||
return 100.0 * sample_rate / 1024, True
|
||||
return hz, False
|
||||
|
||||
|
||||
def _apply_unit_summary(pv: PeakValues, summary: dict, geo_fs_ins: float, sample_rate: int,
|
||||
pretrig: Optional[int]) -> None:
|
||||
"""The unit's own values from its event summary, on `pv`. Blastware prints
|
||||
them as they are (DL2, 2026-11-05):
|
||||
* ZC frequency, every record type: 15,844 / 15,844 waveform and
|
||||
104,000 / 104,000 histogram values, and every word
|
||||
* a waveform's peak displacement = half its integral: 19,479 / 19,479
|
||||
* a waveform's times of peak and vector-sum time, from the unit's peak
|
||||
samples (`pretrig` given): they replace the samples' own, which differ
|
||||
only where the stored samples wrap (O117I1NK.R70W)."""
|
||||
# The summary's geophone values are decoder units, as a histogram's are.
|
||||
unit_ins = _HIST_GEO_COUNTS_PER_UNIT * geo_fs_ins / _GEO_INT16_FS
|
||||
for ch, attr in (("Tran", "tran"), ("Vert", "vert"), ("Long", "long"), ("MicL", "mic")):
|
||||
c = summary.get(ch)
|
||||
if c is None:
|
||||
continue
|
||||
hz, above = _zc_from_half_period(c["half_period"], sample_rate)
|
||||
setattr(pv, f"{attr}_zc_freq", hz)
|
||||
setattr(pv, f"{attr}_zc_above_range", above)
|
||||
if pretrig is None:
|
||||
continue
|
||||
setattr(pv, f"{ch.lower()}_time_of_peak", (c["peak_sample"] - pretrig) / sample_rate)
|
||||
if ch != "MicL":
|
||||
setattr(pv, f"{attr}_peak_disp_in", c["disp_integral"] * unit_ins / sample_rate / 2)
|
||||
if pretrig is not None and all(ch in summary for ch in ("Tran", "Vert", "Long")):
|
||||
pv.pvs_time = (summary["pvs_sample"] - 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
|
||||
@@ -936,9 +978,10 @@ 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, Optional[int]]:
|
||||
"""The trigger time and trigger source from the instrument's embedded event
|
||||
record, or (None, why, None).
|
||||
) -> tuple[Optional[datetime.datetime], str, Optional[int], Optional[int]]:
|
||||
"""The trigger time, the trigger source and the offset of the record's
|
||||
`fe 80` from the instrument's embedded event record, or (None, why, None,
|
||||
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
|
||||
@@ -951,7 +994,7 @@ def _embedded_event_record(
|
||||
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", None
|
||||
return None, "the footer has no start and stop to check one against", None, None
|
||||
found, rejected = [], 0
|
||||
i = raw.find(_EVENT_RECORD_MARKER, 6)
|
||||
while 0 <= i and i + 18 <= end:
|
||||
@@ -967,15 +1010,15 @@ def _embedded_event_record(
|
||||
<= _EVENT_RECORD_SLACK_S[1])
|
||||
)
|
||||
if valid:
|
||||
found.append((trig, int.from_bytes(raw[i - 2:i], "big")))
|
||||
found.append((trig, int.from_bytes(raw[i - 2:i], "big"), i))
|
||||
else:
|
||||
rejected += 1
|
||||
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
|
||||
if len(found) == 1:
|
||||
return found[0][0], "", found[0][1]
|
||||
return found[0][0], "", found[0][1], found[0][2]
|
||||
if found:
|
||||
return None, f"{len(found)} candidates validate", None
|
||||
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None
|
||||
return None, f"{len(found)} candidates validate", None, None
|
||||
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None, None
|
||||
|
||||
|
||||
# A histogram's event record: the same lead, the source 0x0400, marker fe f5,
|
||||
@@ -1001,11 +1044,12 @@ def interval_times(start: datetime.datetime, interval_sec: int,
|
||||
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."""
|
||||
) -> tuple[Optional[datetime.datetime], Optional[datetime.datetime], str, Optional[int]]:
|
||||
"""(start, stop, "", offset of its `fe f5`) from a histogram's own event
|
||||
record, or (None, None, why, None). 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"
|
||||
return None, None, "the footer has no start and stop to check one against", None
|
||||
found, rejected = [], 0
|
||||
i = raw.find(_HISTOGRAM_RECORD_MARKER, 6)
|
||||
while 0 <= i and i + 18 <= end:
|
||||
@@ -1014,15 +1058,59 @@ def _histogram_event_record(
|
||||
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))
|
||||
found.append((a, b, i))
|
||||
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], ""
|
||||
return found[0][0], found[0][1], "", found[0][2]
|
||||
if found:
|
||||
return None, None, f"{len(found)} candidates validate"
|
||||
return None, None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
|
||||
return None, None, f"{len(found)} candidates validate", None
|
||||
return None, None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None
|
||||
|
||||
|
||||
# The unit's own event summary (measured on DL2, 2026-11-05). The event record
|
||||
# is the first of a chain of [length uint16 BE][id][payload] records, so the
|
||||
# next record starts `length` + 2 bytes after its lead. Its payload holds the
|
||||
# vector-sum peak's sample at [22:26] past the marker. The four that follow,
|
||||
# 22 bytes each, are one per channel (ids 0x32 Tran .. 0x35 MicL; a unit
|
||||
# without a mic has no 0x35):
|
||||
# [0] 0 [1:3] min [3:5] max (int16 BE; geophones in units of 16 counts)
|
||||
# [5:9] peak sample [9:11] half-period, samples [11:15] displacement
|
||||
# integral, units x samples [15:21] probably the unit's own largest sample step
|
||||
# x 65,536 (inferred), which Blastware does not print: its acceleration is its own
|
||||
# computation from the samples (_waveform_peak_detail)
|
||||
# min, max and peak sample equal the samples' own on 25,962 / 25,966 DL2
|
||||
# channels (the 4 others: O117I1NK.R70W, whose samples wrap at the trigger).
|
||||
_SUMMARY_CHANNELS = {0x32: "Tran", 0x33: "Vert", 0x34: "Long", 0x35: "MicL"}
|
||||
_SUMMARY_CHANNEL_LEN = 22
|
||||
_RECORD_LEAD_TO_MARKER = 6 # the lead `00 28 05 00` and the source sit before the marker
|
||||
_SUMMARY_PVS_SAMPLE_AT = 22 # past the marker
|
||||
|
||||
|
||||
def _unit_summary(raw: bytes, marker_at: int) -> Optional[dict]:
|
||||
"""The unit's per-channel event summary after the validated event record
|
||||
whose marker is at `marker_at`: {"pvs_sample": int, "Tran": {...}, ...},
|
||||
each channel {"min", "max", "peak_sample", "half_period",
|
||||
"disp_integral"}. None when no channel record follows the event record."""
|
||||
lead = marker_at - _RECORD_LEAD_TO_MARKER
|
||||
off = lead + 2 + int.from_bytes(raw[lead:lead + 2], "big")
|
||||
out: dict = {"pvs_sample": int.from_bytes(
|
||||
raw[marker_at + _SUMMARY_PVS_SAMPLE_AT:marker_at + _SUMMARY_PVS_SAMPLE_AT + 4], "big")}
|
||||
while off + 2 + _SUMMARY_CHANNEL_LEN <= len(raw):
|
||||
ch = _SUMMARY_CHANNELS.get(raw[off + 2])
|
||||
if int.from_bytes(raw[off:off + 2], "big") != _SUMMARY_CHANNEL_LEN or ch is None or ch in out:
|
||||
break
|
||||
p = raw[off + 3:off + 2 + _SUMMARY_CHANNEL_LEN]
|
||||
out[ch] = {
|
||||
"min": struct.unpack(">h", p[1:3])[0],
|
||||
"max": struct.unpack(">h", p[3:5])[0],
|
||||
"peak_sample": int.from_bytes(p[5:9], "big"),
|
||||
"half_period": int.from_bytes(p[9:11], "big"),
|
||||
"disp_integral": int.from_bytes(p[11:15], "big"),
|
||||
}
|
||||
off += 2 + _SUMMARY_CHANNEL_LEN
|
||||
return out if len(out) > 1 else None
|
||||
|
||||
|
||||
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
||||
@@ -1450,13 +1538,15 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
# 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).
|
||||
_record_at = None # the validated event record, which the unit's summary follows
|
||||
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, ev.triggered_by = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
|
||||
_trig, _why, ev.triggered_by, _record_at = _embedded_event_record(
|
||||
raw, footer_pos, _start, _stop, _rt)
|
||||
if _trig is not None:
|
||||
ev.timestamp_source = "event_record"
|
||||
else:
|
||||
@@ -1478,8 +1568,8 @@ 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, ""))
|
||||
_start, _hstop, _why, _record_at = (_histogram_event_record(raw, footer_pos, ts1, ts2)
|
||||
if record_type == "Histogram" else (None, None, "", None))
|
||||
if _start is not None:
|
||||
ev.timestamp_source = "event_record"
|
||||
ev.stop_time = _hstop
|
||||
@@ -1522,6 +1612,10 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
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)
|
||||
_summary = _unit_summary(raw, _record_at) if _record_at is not None else None
|
||||
if _summary is not None and ev.peak_values is not None and ev.sample_rate:
|
||||
_apply_unit_summary(ev.peak_values, _summary, geo_fs, ev.sample_rate,
|
||||
ev.pretrig_samples if is_waveform_body else None)
|
||||
if ev.stop_time is None: # a histogram's record stop, else the footer's
|
||||
ev.stop_time = ts2
|
||||
if hist_records:
|
||||
|
||||
+17
-12
@@ -534,11 +534,13 @@ STRT_MARKER = b"STRT"
|
||||
def unescape_reply(data: bytes) -> bytes:
|
||||
"""A reply's data with each kept escape removed: `10 02/03/04` → `02/03/04`.
|
||||
|
||||
The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do
|
||||
(748/748 replies, 2026-10-26). S3FrameParser collapses `10 10` but keeps the
|
||||
`10` of `10 02/03/04` (inner-frame markers to it), so its `.data` carries an
|
||||
extra byte before each 02/03/04 value -- harmless for fields read before the
|
||||
escape, one byte off for any read after it, or counted from the end."""
|
||||
The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do,
|
||||
the checksum included (748/748 replies, 2026-10-26; 7,747 / 7,747 across every
|
||||
recording, March to October 2026, #58). S3FrameParser collapses `10 10` but
|
||||
keeps the `10` of `10 02/03/04` (inner-frame markers to it) everywhere but the
|
||||
checksum, so its `.data` carries an extra byte before each 02/03/04 value --
|
||||
harmless for fields read before the escape, one byte off for any read after it,
|
||||
or counted from the end."""
|
||||
out, i = bytearray(), 0
|
||||
while i < len(data):
|
||||
if data[i] == DLE and i + 1 < len(data) and data[i + 1] in (STX, ETX, 0x04):
|
||||
@@ -632,11 +634,8 @@ class S3Frame:
|
||||
page_lo: int # PAGE_LO from header
|
||||
data: bytes # payload data section (payload[5:], checksum already stripped)
|
||||
checksum_valid: bool
|
||||
chk_byte: int = 0 # actual checksum byte received from wire (body[-1])
|
||||
# needed for waveform file reconstruction: when the last data byte
|
||||
# is 0x10 and chk_byte ∈ {0x02, 0x03, 0x04}, the DLE+chk pair
|
||||
# must be included in the DLE-strip operation to correctly
|
||||
# reconstruct the Blastware binary body.
|
||||
chk_byte: int = 0 # actual checksum byte received from wire (body[-1]); an
|
||||
# escaped one (`10 02/03/04`) leaves no 10 in `data` (#58)
|
||||
|
||||
@property
|
||||
def page_key(self) -> int:
|
||||
@@ -759,9 +758,15 @@ class S3FrameParser:
|
||||
if len(body) < 6:
|
||||
return None
|
||||
|
||||
raw_payload = body[:-1] # everything except the trailing checksum byte
|
||||
# A checksum of 02, 03 or 04 arrives escaped, `10 X`, and _step keeps both
|
||||
# bytes; that 10 is the escape, never data (#58: 272 of 7,747 recorded
|
||||
# replies, every one an escape pair). Any other checksum is one byte.
|
||||
n_chk = 2 if body[-2] == DLE and body[-1] in (STX, ETX, 0x04) else 1
|
||||
raw_payload = body[:-n_chk] # everything except the checksum
|
||||
chk_received = body[-1]
|
||||
chk_computed = checksum(raw_payload)
|
||||
# SUM8 of the payload unescaped: the kept `10` of a `10 02/03/04` is not
|
||||
# summed (7,747 of 7,747 recorded replies check this way).
|
||||
chk_computed = checksum(unescape_reply(raw_payload))
|
||||
|
||||
if len(raw_payload) < 5:
|
||||
return None
|
||||
|
||||
@@ -356,6 +356,9 @@ class PeakValues:
|
||||
long: Optional[float] = None # Longitudinal PPV (in/s) ✅
|
||||
micl: Optional[float] = None # Air overpressure (psi) 🔶 (units uncertain)
|
||||
peak_vector_sum: Optional[float] = None # Scalar geo PVS (in/s) ✅
|
||||
# ZC frequency (Hz), from the unit's own summary in the file (2026-11-05) or
|
||||
# a report. Above range, the value is Blastware's threshold (100 Hz at
|
||||
# 1024 sps) and the flag is set; None is Blastware's "N/A".
|
||||
tran_zc_freq: Optional[float] = None
|
||||
vert_zc_freq: Optional[float] = None
|
||||
long_zc_freq: Optional[float] = None
|
||||
@@ -364,7 +367,8 @@ 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.
|
||||
# A waveform's peak detail (2026-11-04); None for a histogram. Times of peak
|
||||
# are the unit's own peak samples, acceleration comes from the samples.
|
||||
tran_time_of_peak: Optional[float] = None # s from the trigger; negative = pre-trigger
|
||||
vert_time_of_peak: Optional[float] = None
|
||||
long_time_of_peak: Optional[float] = None
|
||||
@@ -373,6 +377,10 @@ class PeakValues:
|
||||
tran_peak_accel_g: Optional[float] = None
|
||||
vert_peak_accel_g: Optional[float] = None
|
||||
long_peak_accel_g: Optional[float] = None
|
||||
# Peak displacement (in), from the unit's own summary (2026-11-05).
|
||||
tran_peak_disp_in: Optional[float] = None
|
||||
vert_peak_disp_in: Optional[float] = None
|
||||
long_peak_disp_in: Optional[float] = None
|
||||
|
||||
|
||||
# ── Project / operator metadata ───────────────────────────────────────────────
|
||||
|
||||
@@ -196,10 +196,11 @@ def assemble_compliance_content(frames: "list[bytes]", lengths: "Optional[tuple]
|
||||
|
||||
`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."""
|
||||
when a frame's checksum byte was itself escaped (02 / 03 / 04), the parser kept
|
||||
the escape's 0x10, so the frame arrived one byte long, ending in a lone 0x10.
|
||||
The parser drops it since #58; this trim stays as a guard. That one byte is
|
||||
dropped; any other leftover is kept, and the block then fails
|
||||
is_compliance_content."""
|
||||
parts = [unescape_reply(bytes(f))[11:] for f in frames]
|
||||
parts = [p[1:] for p in parts[:-1]] + parts[-1:]
|
||||
if lengths is not None and len(lengths) == len(parts):
|
||||
@@ -633,8 +634,9 @@ 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.
|
||||
# An escaped checksum byte left its 0x10 behind until #58 (bench 2026-11-04;
|
||||
# see assemble_compliance_content): kept as a guard, one stray byte beyond
|
||||
# what was asked is dropped.
|
||||
if len(raw) == length + 1 and raw[-1:] == b"\x10":
|
||||
raw = raw[:-1]
|
||||
log.debug("read_waveform_data_raw: got %d bytes", len(raw))
|
||||
|
||||
+19
-3
@@ -46,7 +46,19 @@ from sfm.shape_metrics import shape_from_h5, offset_from_h5
|
||||
|
||||
log = logging.getLogger("sfm.waveform_store")
|
||||
|
||||
A5_PICKLE_VERSION = 1
|
||||
# 2 (2026-11-06, #58): frames as the parser gives them since an escaped checksum
|
||||
# stopped leaving its 0x10 in `data`. A version-1 frame with a checksum of 02, 03
|
||||
# or 04 still ends in that 0x10; load_a5 drops it (_frame_from_v1).
|
||||
A5_PICKLE_VERSION = 2
|
||||
|
||||
|
||||
def _frame_from_v1(f: S3Frame) -> S3Frame:
|
||||
"""A frame pickled before #58, as the parser reads its reply now. Its 02/03/04
|
||||
checksum arrived as `10 X` (every recorded one did), and the 10 ended `data`."""
|
||||
if f.chk_byte in (0x02, 0x03, 0x04) and f.data[-1:] == b"\x10":
|
||||
return S3Frame(sub=f.sub, page_hi=f.page_hi, page_lo=f.page_lo, data=f.data[:-1],
|
||||
checksum_valid=f.checksum_valid, chk_byte=f.chk_byte)
|
||||
return f
|
||||
|
||||
|
||||
def _frame_to_dict(f: S3Frame) -> dict:
|
||||
@@ -801,7 +813,8 @@ class WaveformStore:
|
||||
|
||||
def load_a5(self, serial: str, filename: str) -> Optional[list[S3Frame]]:
|
||||
"""
|
||||
Re-hydrate the pickled A5 frame stream for a stored event.
|
||||
Re-hydrate the pickled A5 frame stream for a stored event, as the parser
|
||||
reads it now (a version-1 pickle's frames are converted).
|
||||
Returns None if the sidecar is missing.
|
||||
"""
|
||||
_, a5_path = self.paths_for(serial, filename)
|
||||
@@ -812,7 +825,10 @@ class WaveformStore:
|
||||
if not isinstance(payload, dict) or "frames" not in payload:
|
||||
log.warning("WaveformStore.load_a5: malformed sidecar at %s", a5_path)
|
||||
return None
|
||||
return [_dict_to_frame(d) for d in payload["frames"]]
|
||||
frames = [_dict_to_frame(d) for d in payload["frames"]]
|
||||
if payload.get("version", 1) < 2:
|
||||
frames = [_frame_from_v1(f) for f in frames]
|
||||
return frames
|
||||
|
||||
# ── modern .sfm.json sidecar accessors ──────────────────────────────────────
|
||||
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+7046
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+7044
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -522,3 +522,83 @@ def test_waveform_peak_detail_comes_from_the_samples(rel, times, pvs_time, accel
|
||||
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)
|
||||
|
||||
|
||||
# ── Group D, part 2: the unit's own event summary ───────────────────────────
|
||||
# After its embedded event record a file carries the unit's per-channel summary,
|
||||
# one 24-byte record each (ids 0x32 Tran .. 0x35 MicL): min, max, peak sample,
|
||||
# half-period and a displacement integral (measured on DL2, 2026-11-05):
|
||||
# ZC frequency = (rate / 2) / half-period: 15,844 / 15,844 waveform values and
|
||||
# 104,000 / 104,000 histogram values; every word too (">100" at <= 5 samples,
|
||||
# "N/A" at 0, "<1.0" beyond rate / 2)
|
||||
# displacement = integral x 16 counts x in/s per count / rate / 2: 19,479 / 19,479
|
||||
# Every expected value below is Blastware's own, from the file's _XML.XML report.
|
||||
|
||||
_US = "unit-summary-11-05-26"
|
||||
|
||||
|
||||
def _prints_as(value, printed):
|
||||
d = len(printed.split(".")[1]) if "." in printed else 0
|
||||
return abs(value - float(printed)) <= 0.5 * 10 ** -d + 1e-9
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,printed", [
|
||||
# (Tran, Vert, Long, MicL) ZC Freq as Blastware prints it; None = no channel
|
||||
(f"{_US}/I145L6UJ.3Y0W", ("43", "37", "39", "43")), # 1024 sps
|
||||
(f"{_US}/K557L7FX.SC0W", (">200", "171", ">200", "26")), # 2048 sps
|
||||
(f"{_US}/R349KMF7.9O0W", ("17.4", "66", "12.6", "19.5")), # 4096 sps
|
||||
(f"{_US}/K558IKSJ.P20W", ("N/A", "<1.0", "N/A", "N/A")),
|
||||
(f"{_US}/O117I1NK.R70W", (">100", ">100", ">100", ">100")),
|
||||
(f"{_US}/R352HFZ7.5D0W", ("73", "30", "24", None)), # a unit without a mic
|
||||
(f"{_US}/T193HLJ3.X80H", (">100", ">100", "73", "57")), # a histogram
|
||||
])
|
||||
def test_zc_frequency_is_the_units_own(rel, printed):
|
||||
pv = read_blastware_file(_FIX / rel).peak_values
|
||||
for ch, want in zip(("tran", "vert", "long", "mic"), printed):
|
||||
got, above = getattr(pv, f"{ch}_zc_freq"), getattr(pv, f"{ch}_zc_above_range")
|
||||
if want in (None, "N/A"):
|
||||
assert (got, above) == (None, False), ch
|
||||
elif want.startswith(">"):
|
||||
assert (got, above) == (float(want[1:]), True), ch # Blastware's threshold, flagged
|
||||
elif want == "<1.0":
|
||||
assert 0 < got < 1.0 and not above, (ch, got)
|
||||
else:
|
||||
assert _prints_as(got, want) and not above, (ch, got, want)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,printed", [
|
||||
(f"{_US}/I145L6UJ.3Y0W", ("0.000", "0.000", "0.000")),
|
||||
(f"{_US}/K558IKSJ.P20W", ("0.000", "0.046", "0.000")),
|
||||
(f"{_US}/R349KMF7.9O0W", ("0.004", "0.001", "0.012")), # 4096 sps
|
||||
(f"{_US}/R352HFZ7.5D0W", ("0.003", "0.010", "0.006")),
|
||||
(f"{_US}/O117I1NK.R70W", ("1.480", "1.483", "2.616")), # clipped: beyond the samples
|
||||
])
|
||||
def test_peak_displacement_is_the_units_own(rel, printed):
|
||||
pv = read_blastware_file(_FIX / rel).peak_values
|
||||
for ch, want in zip(("tran", "vert", "long"), printed):
|
||||
got = getattr(pv, f"{ch}_peak_disp_in")
|
||||
assert got is not None and _prints_as(got, want), (ch, got, want)
|
||||
|
||||
|
||||
def test_a_histogram_has_no_peak_displacement():
|
||||
pv = read_blastware_file(_FIX / f"{_US}/T193HLJ3.X80H").peak_values
|
||||
assert (pv.tran_peak_disp_in, pv.vert_peak_disp_in, pv.long_peak_disp_in) == (None, None, None)
|
||||
|
||||
|
||||
def test_time_of_peak_is_the_units_own_peak_sample():
|
||||
# O117I1NK clips: its stored samples wrap at the trigger, so their largest
|
||||
# lands elsewhere, but the unit's summary has every peak at the trigger --
|
||||
# Blastware prints 0.000 on all four channels and the vector sum.
|
||||
pv = read_blastware_file(_FIX / f"{_US}/O117I1NK.R70W").peak_values
|
||||
for ch in ("tran", "vert", "long", "micl"):
|
||||
assert getattr(pv, f"{ch}_time_of_peak") == 0.0, ch
|
||||
assert pv.pvs_time == 0.0
|
||||
|
||||
|
||||
def test_without_the_units_summary_nothing_is_guessed():
|
||||
raw = bytearray((_FIX / f"{_US}/I145L6UJ.3Y0W").read_bytes())
|
||||
i = raw.find(b"\x00\x16\x32")
|
||||
raw[i + 2] = 0x00 # break the Tran record's id
|
||||
pv = decode_blastware_bytes(bytes(raw), name=None).peak_values
|
||||
assert (pv.tran_zc_freq, pv.mic_zc_freq, pv.tran_peak_disp_in) == (None, None, None)
|
||||
assert abs(pv.tran_time_of_peak - 2.281) <= 0.0005 # the samples' peak, as before
|
||||
@@ -40,8 +40,10 @@ def test_event_type_comes_from_the_bytes():
|
||||
def test_report_fields_stay_blank():
|
||||
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
|
||||
# (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"):
|
||||
# since 2026-11-04, ZC frequency and displacement since 2026-11-05:
|
||||
# test_the_setup_fields_match_blastware, test_waveform_peak_detail_*,
|
||||
# test_zc_frequency_and_displacement_match_blastware. Its Tran ZC is N/A.)
|
||||
for tag in ("TranZCFreq", "TranTestResults"):
|
||||
assert s.values.get(tag) is None
|
||||
|
||||
|
||||
@@ -67,7 +69,7 @@ def test_full_waveform_row_verdicts():
|
||||
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["TranZCFreq"].verdict == "match" # ">100", the unit's own (2026-11-05)
|
||||
assert res["BatteryLevel"].verdict == "match" # 6.72 V, printed "6.7 Volts"
|
||||
assert "FileName" not in res
|
||||
|
||||
@@ -91,7 +93,7 @@ def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
def test_zc_frequency_na_and_above_range():
|
||||
res = _results("T1905KDW.5F0W") # its JobNumber: test_the_job_number_matches_blastware
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
assert res["VertZCFreq"].verdict == "match" # >100: the unit's half-period
|
||||
|
||||
|
||||
def test_mic_units_pick_the_conversion():
|
||||
@@ -355,3 +357,39 @@ def test_waveform_peak_detail_matches_blastware(path):
|
||||
"PeakVectorSumTimeSum", "TranPeakAcceleration", "VertPeakAcceleration",
|
||||
"LongPeakAcceleration"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
|
||||
|
||||
# ── Group D, part 2: the unit's own summary (2026-11-05) ────────────────────
|
||||
_US = FIX.parent / "unit-summary-11-05-26"
|
||||
_ZC_AND_DISP = ([f"{ch}ZCFreq" for ch in ("Tran", "Vert", "Long", "MicL")]
|
||||
+ [f"{ch}PeakDisplacement" for ch in ("Tran", "Vert", "Long")])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [
|
||||
FIX / "R352HIUI.F40W", FIX / "T1905KDW.5F0W",
|
||||
FIX.parent / "setup-fields-11-03-26" / "T189HUD6.QE0W",
|
||||
FIX / "T004JTRF.ME0H", FIX / "M529L4XQ.R30H", # histograms
|
||||
_US / "K558IKSJ.P20W", # "<1.0" and N/A
|
||||
_US / "O117I1NK.R70W", # the mic's ">100"; clipped
|
||||
])
|
||||
def test_zc_frequency_and_displacement_match_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)}
|
||||
checked = 0
|
||||
for f in _ZC_AND_DISP:
|
||||
printed = ref.scalars.get(f)
|
||||
if printed is None:
|
||||
continue
|
||||
want = "no_reference" if printed == "N/A" else "match"
|
||||
assert res[f].verdict == want, (f, res[f])
|
||||
checked += want == "match"
|
||||
assert checked >= 3
|
||||
|
||||
|
||||
def test_a_clipped_events_peak_times_match_blastware():
|
||||
path = _US / "O117I1NK.R70W"
|
||||
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"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
@@ -0,0 +1,175 @@
|
||||
"""#58: a reply whose checksum byte is 02, 03 or 04 arrives as `10 X`.
|
||||
|
||||
The unit escapes 02, 03, 04 and 10 in a reply, the checksum included. The
|
||||
parser kept the `10` of an escaped checksum as the frame's last data byte, so
|
||||
the data came out one byte long, ending in a lone 0x10 (measured on BE9441's
|
||||
1A read at the bench, 2026-11-04).
|
||||
|
||||
Across every recorded reply (60 captures, March to October 2026), SUM8 of the
|
||||
unescaped payload is the checksum on 7,747 of 7,747. 272 checksums arrived
|
||||
escaped, and every one checks as an escape pair: the `10` is never data.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pickle
|
||||
import sys
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import minimateplus.protocol as mp # noqa: E402
|
||||
from minimate_replay import fast_clock # noqa: E402
|
||||
from minimateplus.blastware_file import _frame_body_bytes, write_blastware_file # noqa: E402
|
||||
from minimateplus.client import _decode_monitor_status # noqa: E402
|
||||
from minimateplus.framing import S3FrameParser, unescape_reply # noqa: E402
|
||||
from minimateplus.models import Event # noqa: E402
|
||||
from minimateplus.protocol import is_call_home_block # noqa: E402
|
||||
from sfm.waveform_store import A5_PICKLE_VERSION, WaveformStore, _frame_to_dict # noqa: E402
|
||||
from test_5a_blastware_walk import ByAddress # noqa: E402
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
def _escape(b: bytes) -> bytes:
|
||||
"""The unit's encoding: 10 before 02, 03, 04 and 10."""
|
||||
return b"".join(bytes([0x10, x]) if x in (0x02, 0x03, 0x04, 0x10) else bytes([x]) for x in b)
|
||||
|
||||
|
||||
def reply(sub: int, data: bytes, page: bytes = b"\x00\x00") -> bytes:
|
||||
"""A reply as the unit sends it: header, data and SUM8 checksum, escaped."""
|
||||
payload = bytes([0x00, 0x10, sub]) + page + data
|
||||
return b"\x10\x02" + _escape(payload + bytes([sum(payload) & 0xFF])) + b"\x03"
|
||||
|
||||
|
||||
def data_for(chk: int, last: int, sub: int = 0xE3) -> bytes:
|
||||
"""Data ending in `last` whose reply checksum comes out as `chk`."""
|
||||
base = bytes(11) + b"#58"
|
||||
fill = (chk - (0x10 + sub + sum(base) + last)) & 0xFF
|
||||
return base + bytes([fill, last])
|
||||
|
||||
|
||||
def one(wire: bytes):
|
||||
frames = S3FrameParser().feed(wire)
|
||||
assert len(frames) == 1
|
||||
return frames[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04])
|
||||
def test_an_escaped_checksum_leaves_nothing_in_the_data(chk):
|
||||
data = data_for(chk, last=0x55)
|
||||
f = one(reply(0xE3, data))
|
||||
assert (unescape_reply(f.data), f.chk_byte) == (data, chk)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04])
|
||||
def test_a_last_data_byte_of_0x10_survives_an_escaped_checksum(chk):
|
||||
# Wire `10 10 10 0X`: a real 0x10, then the escaped checksum. Not in any
|
||||
# recording; one A5 chunk in ten ends in a real 0x10.
|
||||
data = data_for(chk, last=0x10)
|
||||
f = one(reply(0xE3, data))
|
||||
assert (unescape_reply(f.data), f.chk_byte) == (data, chk)
|
||||
|
||||
|
||||
REPLY_RECORDINGS = ["minimate-bench-10-25-26/BE9441_event0_01110000_rx.bin",
|
||||
"minimate-bench-10-25-26/BE9441_event1_0111646a_rx.bin",
|
||||
"minimate-bench-10-26-26-blastware/unit_replies.bin",
|
||||
"minimate-bench-10-26-26-histogram/unit_replies.bin"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", REPLY_RECORDINGS)
|
||||
def test_every_recorded_reply_checks(name):
|
||||
# BE9441, October 2026: 2,509 replies, 62 with an escaped checksum.
|
||||
frames = S3FrameParser().feed((FIX / name).read_bytes())
|
||||
assert frames
|
||||
assert [i for i, f in enumerate(frames) if not f.checksum_valid] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chk", [0x10, 0x00, 0x55])
|
||||
def test_any_other_checksum_reads_as_before(chk):
|
||||
data = data_for(chk, last=0x10)
|
||||
f = one(reply(0xE3, data))
|
||||
assert (unescape_reply(f.data), f.chk_byte) == (data, chk)
|
||||
|
||||
|
||||
# Two 1C replies recorded from BE11529 on 2026-04-08, checksums 03 and 02 escaped.
|
||||
# The battery and memory are counted from the end, so the stray byte read them as
|
||||
# 430.08 V / 251,654,656 bytes total.
|
||||
STATUS_REPLIES = [
|
||||
("4-8-26/mid-monitor/raw_s3_20260408_181417",
|
||||
"1002001010e300002c0000000000000000000000100408100407ea00120e2c000000000000010107cb"
|
||||
"00060000010107cb0015000000001002a8000efff2000e9d80100303", 6.80, 983026, 957824),
|
||||
("4-8-26/raw_s3_20260408_013431",
|
||||
"1002001010e300002c0000000000000000000000100408100407ea00012312000000000000010107cb"
|
||||
"00060000010107cb0015000000001002a4000efff2000e9e98100203", 6.76, 983026, 958104),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("capture,wire,volts,total,free", STATUS_REPLIES)
|
||||
def test_a_recorded_status_reply_with_an_escaped_checksum_reads_whole(capture, wire, volts, total, free):
|
||||
st = _decode_monitor_status(one(bytes.fromhex(wire)).data)
|
||||
assert (st.battery_v, st.memory_total, st.memory_free) == (volts, total, free)
|
||||
|
||||
|
||||
def test_a_call_home_read_with_an_escaped_checksum_is_a_call_home_block():
|
||||
# BE11529's 2C reply (2026-04-20), its block untouched; one header pad byte is
|
||||
# set so the checksum comes out 02. The stray byte made it 125 bytes, and SFM
|
||||
# refused the unit as monitoring.
|
||||
recorded = S3FrameParser().feed(
|
||||
(FIX / "s3-call-home-bw" / "raw_s3_20260420_162148_pull_call_home_options.bin").read_bytes())
|
||||
data = bytearray(unescape_reply(next(f for f in recorded if f.sub == 0xD3 and len(f.data) > 11).data))
|
||||
data[10] = (0x02 - (0x10 + 0xD3 + sum(data) - data[10])) & 0xFF
|
||||
f = one(reply(0xD3, bytes(data)))
|
||||
assert f.chk_byte == 0x02
|
||||
assert is_call_home_block(f.data[11:])
|
||||
assert unescape_reply(f.data[11:]) == bytes(data[11:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04])
|
||||
def test_the_file_builder_keeps_a_real_0x10_before_an_escaped_checksum(chk):
|
||||
# An A5 chunk reply: 12 header bytes, then the body bytes it carries.
|
||||
data = data_for(chk, last=0x10, sub=0xA5)
|
||||
f = one(reply(0xA5, data))
|
||||
assert _frame_body_bytes(f, 12) == data[12:]
|
||||
|
||||
|
||||
# -- the waveform store's .a5.pkl frames, saved by the parser as it was ---------------
|
||||
|
||||
def _write_pickle(store: WaveformStore, name: str, version: int, frames: list) -> None:
|
||||
_bw, a5_path = store.paths_for("BE9441", name)
|
||||
a5_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with a5_path.open("wb") as fp:
|
||||
pickle.dump({"version": version, "frames": [_frame_to_dict(f) for f in frames]}, fp)
|
||||
|
||||
|
||||
def test_a_pickle_saved_before_58_still_builds_blastwares_file(tmp_path, monkeypatch):
|
||||
# BE9441's K441LTOG.000 (10-26 recording): two of its chunk replies have an
|
||||
# escaped checksum. A pickle from before #58 holds their stray 0x10s.
|
||||
fast_clock(monkeypatch)
|
||||
frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream(
|
||||
bytes.fromhex("0112a0b6"), stop_after_metadata=False, include_terminator=True, strict=True)
|
||||
old = [replace(f, data=f.data + b"\x10") if f.chk_byte in (0x02, 0x03, 0x04) else f
|
||||
for f in frames]
|
||||
assert sum(o.data != f.data for o, f in zip(old, frames)) == 2
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
_write_pickle(store, "K441LTOG.000", 1, old)
|
||||
|
||||
loaded = store.load_a5("BE9441", "K441LTOG.000")
|
||||
assert [f.data for f in loaded] == [f.data for f in frames]
|
||||
ev = Event(index=0)
|
||||
ev.timestamp = None
|
||||
write_blastware_file(ev, loaded, tmp_path / "K441LTOG.000")
|
||||
bw = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOG.000"
|
||||
assert (tmp_path / "K441LTOG.000").read_bytes() == bw.read_bytes()
|
||||
|
||||
|
||||
def test_a_pickle_saved_now_loads_as_saved(tmp_path):
|
||||
# A real 0x10 before an escaped checksum: the conversion is for old pickles only.
|
||||
f = one(reply(0xA5, data_for(0x02, last=0x10, sub=0xA5)))
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
_write_pickle(store, "K441LTOG.000", A5_PICKLE_VERSION, [f])
|
||||
assert store.load_a5("BE9441", "K441LTOG.000")[0].data == f.data
|
||||
Reference in new issue
Block a user