26 Commits
Author SHA1 Message Date
serversdown eec88a62b8 Merge pull request 'Release v0.35.0 — 80 of 88 report fields from the file, and monitor logs (.MLG)' (#60) from dev into main
Reviewed-on: #60
2026-11-16 15:49:03 -05:00
serversdownandClaude Opus 5.5 c2b8e76774 chore(release): v0.35.0 — 80 of 88 report fields from the file, and monitor logs (.MLG)
CHANGELOG: Unreleased -> v0.35.0 (2026-11-16), with the release's theme
and its Migration.  pyproject, README, CLAUDE.md -> 0.35.0.
TOOL_VERSION -> 0.35.0: the codec changed (groups D2, E, F, over range,
the mic's range), which gates the backfill's regeneration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-16 12:46:58 -05:00
serversdownandClaude Opus 5.5 ed4f3d2213 docs(changelog): Unreleased -- monitor logs (.MLG) and each unit's timeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-16 11:08:30 -05:00
serversdownandClaude Opus 5.5 03c272316f merge: monitor logs (.MLG) and each unit's monitoring timeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-16 11:06:39 -05:00
serversdownandClaude Opus 5.5 ba826dfac6 fix(mlg): final-review fixes
A fresh whole-branch review found four Important issues; three of its
Minors and one item it set aside were re-graded up.  Each has a test that
failed first.

- A windowed timeline 500'd when a file came without its modified time
  (Python 3.10 rejects the 'Z' of received_at).  received_at is now
  +00:00 and timeline times parse 'Z' too.
- On the clock-step day an event-triggered call-in moved the event into
  the next session and lost the step.  An event now joins the 'monitoring
  started' record of its own file.
- A call-in whose records came first in another file (a cable download)
  read 'nothing_new'.  Each file now keeps its own call summary
  (last_stop, no_file_stops) from when it arrived.
- Sessions and call-ins now carry record_ids / file_ids / file_id, the
  shot report's proof (spec 5).
- A non-'started' record with no stop made the unit's timeline 500 for
  good; it now opens a session whose end is unknown.
- A serial from a file's bytes (or a hint) could write outside the store;
  only plain serials are used, and records with no serial are refused, not
  dropped.
- Times with a UTC offset, an empty 'at', or a bad mtimes value gave 500s
  (or stored half a request); they are now 400s, checked first.
- A missing call-in file made the gap after its Modem Exit read 'not
  monitoring' for days.  Files are numbered <serial><counter>; a gap
  across a missing number is now 'records missing' (unknown).  A long gap
  after a call-in with no number missing is 'no restart after a call-in':
  real outages on the DL2 data (BE6907 14 days from 2026-10-07; BE8081
  over Labor Day 2019).  Real fixtures BE6907 #899-#902 added.
- Docs: BE8081 did write one empty file (BE80811.MLG).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 14:17:08 -05:00
serversdownandClaude Opus 5.5 35bac40dd5 docs: the .MLG format measured (reference D.4), and the new /db routes
Reference D.4 rewritten from the measurements: the 18-byte prefix,
length-led 292-byte records, the CRC-16/AUG-CCITT (3,329 / 3,329), the
fields, how Blastware writes the files and how a session appears, and
the cross-check against DL2's event files.  The old D.4.1-D.4.3 stay,
marked retracted.  CLAUDE.md gains the five routes and a Where things
stand entry; the spec's footer-CRC note points at dev's 8544e9c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:56:10 -05:00
serversdownandClaude Opus 5.5 4bc669df4d feat(mlg): bulk import, and a cross-check against the event files
scripts/import_mlg_dir.py imports every .MLG under a directory (files
with records first, then the empty ones, so each unit's serial is known
first; dry run writes nothing).  scratch/check_mlg_vs_events.py matches
each Event Recorded record to an event file's footer (stop, flag word,
trigger source) in both directions, inside each unit's .MLG period.

Run on the dev box against DL2's 1,273 sample files (2026-11-13):
  import: 1273 ok, 0 errors, 231 empty, 0 unresolved, 2180 records, 13 s
  BE8081:  785 matched, 0 record-only, 0 file-only
  BE6907:    6 matched, 5 record-only, 0 file-only
  BE12844:  19 matched, 37 record-only, 0 file-only
  every record-only one stops after 2026-08-25, where the DL2 copy ends;
  the 4,303 footers of those three units' event files all pass their CRC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:54:50 -05:00
serversdownandClaude Opus 5.5 c0cdf58527 feat(mlg): /db routes: import .MLG, a unit's timeline, monitoring at T
POST /db/import/mlg_file (per-file status; good files stored even when
another in the request is refused; each file's modified time as a JSON
form field), GET /db/units/{serial}/timeline (optionally windowed),
GET /db/units/{serial}/monitoring_at, GET /db/mlg_records, and
GET /db/mlg_files/{id} (the original, byte for byte, for printing).

Tested by calling the route functions directly: httpx is not in this
venv, so TestClient tests would skip silently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:50:59 -05:00
serversdownandClaude Opus 5.5 faa371a73b feat(mlg): each unit's monitoring timeline, and was it monitoring at T
sfm/mlg_timeline.py builds, from a unit's stored records: sessions (with
how each ended, its events and its trigger level as logged), the gaps
between them and what each means (call-in, scheduled off, lost power,
stopped by a person, memory full), clock steps (a session starting
before the previous one stopped, as at the end of daylight saving), and
call-ins: delivered, no_file (a Modem Exit that left no file) and
nothing_new (an empty file).  monitoring_at() answers monitoring /
not_monitoring / unknown, never claiming more than the records show.
Tested on real files, including BE8081's weekend: Battery Low Exit
Saturday 10:47, back Monday 12:47, two calls that left no file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:48:13 -05:00
serversdownandClaude Opus 5.5 f41e4be382 feat(mlg): ingest one .MLG: verify, resolve the serial, keep the original
sfm/mlg_ingest.ingest_mlg() is shared by the import route and the bulk
script.  A file that is not whole, or with any record failing its
checksum, stores nothing.  The serial comes from the file; for an empty
file (no serial inside) from the caller's hint, else the longest known
serial its <serial><counter> name starts with, else unresolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:45:21 -05:00
serversdownandClaude Opus 5.5 84d6cd05c3 feat(mlg): store .MLG files and records, each record once
Two new tables, created on first start (no migration):
mlg_files (one row per file received, deduped by name + sha256) and
mlg_records (one row per log record, unique on serial, start, stop,
flag word and trigger source; COALESCE on the stop, since an open
record's NULL stop is distinct to a UNIQUE constraint).  The text is not
part of a record's identity: Blastware writes it, and two copies of the
same records differ there.  WaveformStore.save_mlg keeps the original
file byte for byte under <serial>/mlg/.

Operational consequence: two new tables on first start; no migration,
no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:43:47 -05:00
serversdownandClaude Opus 5.5 a8adb03d23 feat(mlg): write .MLG files as Blastware does; retire the old writer
mlg_bytes()/write_mlg() rebuild all 12 fixture files byte for byte:
little-endian times, length-led records, each record's checksum.  The old
blastware_file writer (big-endian times, a zero CRC at the wrong end, 308-
byte header) and the read_mlg stub are removed; nothing called them.  No
re-export: event_file_io imports blastware_file, and mlg_file imports
event_file_io.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:41:38 -05:00
serversdownandClaude Opus 5.5 3cd95db405 feat(mlg): read Blastware .MLG files, every record's checksum verified
minimateplus/mlg_file.py parses the measured format: an 18-byte prefix,
then length-led 292-byte records, each with a CRC-16/AUG-CCITT over
[0:288] stored little-endian.  A record that fails its checksum is
returned flagged, never silently dropped.  One shared CRC function
(minimateplus/crc.py) replaces micromate/setup_block's copy.

Fixtures: 12 real .MLG files (DL2's ACH folder + 3 bench files) in
tests/fixtures/mlg-11-9-26/, force-added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:39:44 -05:00
serversdown 30bfdd6eff Merge pull request 'Release v0.34.0 — Series-4 parity, and most of Blastware's report from the event file alone' (#59) from dev into main
Reviewed-on: #59
2026-11-04 18:19:22 -05:00
serversdown fb14a8f7bb Merge pull request 'Release v0.33.0 — SFM reads Series-3 events from the file alone' (#56) from dev into main
Reviewed-on: #56
2026-11-01 14:33:00 -05:00
serversdown e9c01ce8d4 Merge pull request 'Release v0.32.0 — event times you can trust, and Series 4 mapped' (#54) from dev into main
Reviewed-on: #54
2026-10-27 11:00:59 -04:00
serversdown d2258dad4e Merge pull request 'Release v0.31.0 — report parity + the inverted rescue (0.29.0 → 0.31.0)' (#40) from dev into main
Reviewed-on: #40
2026-09-18 16:46:41 -04:00
serversdown e050e602c2 Merge pull request 'Release v0.29.0 — offset detector + false_trigger_reason + BlastMate serials (0.27.0→0.29.0)' (#36) from dev into main
Reviewed-on: #36
2026-09-07 15:57:37 -04:00
serversdown fc1c7c7936 Merge pull request 'Docs/claude.md corrections' (#35) from dev into main
Reviewed-on: #35
2026-08-29 15:48:33 -04:00
serversdown 7d0d12079b Merge pull request 'v0.27.0 Decoder fixes, offset exploration and testing.' (#34) from dev into main
Reviewed-on: #34
2026-08-28 22:40:34 -04:00
serversdown 5203aab849 Merge pull request 'update to 0.26.0. Big chonking update including 0.23, 0.24, and 0.25 as well.' (#33) from dev into main
Reviewed-on: #33
2026-08-27 13:43:00 -04:00
serversdown 5b65718b72 Merge pull request 'v0.23.0 - ZC freq in events store' (#31) from dev into main
Reviewed-on: #31
2026-08-06 12:12:19 -04:00
serversdown 483762607e Merge pull request 'Update to v0.22.0' (#30) from dev into main
Reviewed-on: #30
2026-07-03 15:35:20 -04:00
serversdown d0b66368d5 Merge pull request 'update to v0.21.1, thor data import successful' (#29) from dev into main
Reviewed-on: #29
2026-06-01 16:54:23 -04:00
serversdown 2eb1d25028 Merge pull request 'v0.20.0 -- Full s3 event parse and PDF creation.' (#28) from dev into main
Reviewed-on: #28
2026-05-28 17:54:31 -04:00
claude cc821f9ee3 hotfix: fix dockerfile on main to fix import bug on prod 2026-05-21 20:42:15 +00:00
41 changed files with 2391 additions and 256 deletions

No files matched your search

+145 -1
View File
@@ -4,7 +4,42 @@ All notable changes to seismo-relay are documented here.
---
## Unreleased
## v0.35.0 — 2026-11-16
**The file-only decode reaches 80 of Blastware's 88 report fields, and SFM
reads monitor logs (.MLG).**
Three lines of work ship together.
**The file-only decode, groups D (part 2), E and F.** 80 of Blastware's 88
report fields now match on every DL2 event, 47 at v0.34.0. The last 16 values,
in two causes, are left as they are by decision (Brian, 2026-11-11).
- **New, from the unit's own records in the file:**
- ZC frequency, peak displacement and times of peak
- the sensor check results
- the Monitor Log line
- over range (Blastware's `OORANGE`)
- **Fixed:**
- a range-1 mic read 8× high (7 DL2 events)
- the mic dB offset
- a unit without a mic lost its sensor-check traces
**Monitor logs (.MLG).** SFM reads Blastware's monitor logs and keeps each
unit's monitoring timeline: sessions, gaps and what each means, and call-ins,
including calls that left no file. It answers "was unit X monitoring at T",
which is what a shot report needs for a unit that did not trigger. Nothing flows
in until the watcher forwards `.MLG`s or they are bulk-imported.
**An escaped checksum is the checksum, not data (#58).** SFM's live reads no
longer carry a stray byte, which had corrupted the battery and memory status and
the call-home read.
Prod still overlays a paired ASCII report onto the decode. Retiring that overlay
is the plan's step 3 and is not part of this release.
⚠ **This release owes a backfill, about 8 hours on the NAS, and creates two
empty tables on first start.** There is no migration, and no stored event time
moves. See *Migration*.
### Added
- **ZC frequency, peak displacement and times of peak come from the unit's own
@@ -135,6 +170,68 @@ All notable changes to seismo-relay are documented here.
- No schema change.
- The over-range flags are on the decoded event only: not stored in the
DB, sidecar or `.h5` yet.
- **Monitor logs (.MLG): SFM reads them and keeps each unit's monitoring
timeline** (`feat/mlg-import`, merged 2026-11-16). Spec
`docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`.
- **Why (Brian, 2026-11-09):** every unit sends an `.MLG` at every call-in,
whatever its mode. A continuous-mode unit sends no event file on a quiet
day, so its `.MLG` is the only proof it was monitoring. That proof is what
a shot report attaches for a unit that did not trigger. Outage history is
the second use.
- **The format, measured** (reference D.4, rewritten):
- an 18-byte prefix, then length-led 292-byte records
- each record ends in a CRC-16/AUG-CCITT over `[0:288]`, little-endian:
3,329 / 3,329 records
- `minimateplus/mlg_file.py` reads it, checking every record's checksum,
and writes it: 16 / 16 real files rebuilt byte for byte
- the old unused writer in `blastware_file.py` (big-endian, a zero CRC
at the wrong end) is removed
- `minimateplus/crc.py` is the one CRC, now used by
`micromate/setup_block.py` too
- **Storage:** new tables `mlg_files` (one row per file received) and
`mlg_records` (one row per record, stored once). The original file is kept
under `<store>/<serial>/mlg/`.
- An empty file has no serial inside. It takes the longest known serial
its `<serial><counter>` name starts with, or is stored as unresolved,
never guessed.
- Only plain serials become directories.
- **The timeline** (`sfm/mlg_timeline.py`):
- **sessions:** how each ended, its events, and its trigger level as
logged
- **gaps and what each means:** call-in, scheduled off, lost power,
stopped by a person, memory full, no restart after a call-in, records
missing
- **clock steps:** the unit's clock steps back an hour at its first
call-in after daylight saving ends
- **call-ins:** delivered, no_file (a Modem Exit that left no file) and
nothing_new (an empty file)
- **"Was it monitoring at T"** answers monitoring / not_monitoring / unknown,
naming the records and file behind the answer. It never claims more than
the records show: a gap across a missing call-in number (files are
numbered) reads unknown.
- **Routes:** `POST /db/import/mlg_file`; `GET /db/units/{serial}/timeline`,
`/db/units/{serial}/monitoring_at`, `/db/mlg_records` and
`/db/mlg_files/{id}` (the original, for printing).
- **Tools:** `scripts/import_mlg_dir.py` (bulk import, with a dry run) and
`scratch/check_mlg_vs_events.py` (cross-check against the event files'
footers).
- **Measured on DL2's 1,273-file sample** (BE6907 and BE12844 from 2026,
BE8081 from 2018–19):
- 0 errors, 0 unresolved
- BE8081's 785 Event Recorded records match its 785 event files, both ways
- every recorded event falls inside a session
- two real outages: BE6907 recorded nothing for 14 days from 2026-10-07,
and BE8081 didn't restart after a failed call over Labor Day 2019
- ⚠ **Operational:**
- Two new tables are created on first start: no migration, no backfill,
no `TOOL_VERSION` bump (the event decode and the `.h5` files are
unchanged).
- Nothing arrives until `.MLG`s are imported. The watcher does not forward
them yet (`../series3-watcher`, Brian's call).
- DL2's full set (~86,000 files) loads with `scripts/import_mlg_dir.py`.
Load it from a robocopy copy: a Windows zip shifts summer file dates by
an hour.
- Terra-View shows none of it yet.
### Fixed
- **The mic's own range: a range-1 mic reads an eighth.**
@@ -236,6 +333,53 @@ All notable changes to seismo-relay are documented here.
- **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).
- **Reference D.4, rewritten:** the `.MLG` format, measured.
- Its framing, CRC and fields.
- How Blastware writes the files: one per call-in, no record repeated, and
a Modem Exit that is not a file's last record was a call that left no file.
- How a session appears, and the cross-check against the event files.
- The old D.4.1–D.4.3 (a 308-byte header, a CRC at each record's start) are
kept, marked retracted.
### Migration
⚠ **A backfill, no schema migration.** Not rehearsed on a prod snapshot.
**Before you start:**
- `TOOL_VERSION` is bumped to **0.35.0**, which gates the regeneration, so no
`--force` is needed.
- **Back up `seismo_relay.db` first.**
**Then:**
1. **Deploy.** On first start SFM creates `mlg_files` and `mlg_records`, both
empty. No other table changes, and no event row or id moves.
2. **In the `sfm` container, run `python scripts/backfill_sidecars.py`.** It
re-decodes every event file. ⚠ **Plan about 8 hours**: v0.34.0's run took
13:13 → 21:16 on 2026-11-05.
- **Report-less events gain a ZC frequency** in the existing `*_zc_freq` /
`*_zc_above_range` columns. Terra-View shows a frequency where it showed
"—".
- **The range-1 mic events' `mic_ppv` and `.h5` mic samples drop 8×** (7
in DL2; e.g. K557J1XQ.GF0W reads 79.4 dB(L), not 97.5). Report-paired
events keep the report's value.
- **A unit without a mic gets its geophone sensor-check traces** in its
`.h5` (BE16352's 8 DL2 events).
- **On the decoded event only, not stored in the DB or `.h5` yet:** the
sensor-check results, the Monitor Log line, over range, displacement and
times of peak.
- No stored event time moves.
3. **Run `python scripts/backfill_event_shape.py --db-path
bridges/captures/seismo_relay.db --store-root bridges/captures/waveforms`.**
It recomputes the shape and offset metrics.
4. **Optional, any time after: load DL2's `.MLG`s.**
- Copy `C:\Blastware 10\Event\autocall home` with robocopy, not a zip: a
Windows zip shifts summer file dates by an hour.
- Run `python scripts/import_mlg_dir.py <dir> --db-path ... --store-root
...`, with `--dry-run` first.
- On the dev box, a 1,273-file sample loaded in 13 s with 0 errors.
**Terra-View** needs no change: it reads rows by id. ZC frequencies appear,
and the range-1 mic values drop.
## v0.34.0 — 2026-11-04
+23 -6
View File
@@ -2,7 +2,7 @@
Ground-up Python replacement for **Blastware**, Instantel's Windows-only software for
managing MiniMate Plus seismographs. Connects over direct RS-232 or cellular modem
(Sierra Wireless RV50 / RV55). Current version: **v0.34.0**.
(Sierra Wireless RV50 / RV55). Current version: **v0.35.0**.
Stack-level context — which repo owns what, and how the three project versions
pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
@@ -10,7 +10,7 @@ pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
---
## Where things stand (updated 2026-11-05)
## Where things stand (updated 2026-11-16)
Read this first when picking the project back up.
@@ -31,6 +31,17 @@ Read this first when picking the project back up.
3. switch ingest so reports are kept only for checking (retire the overlay)
4. stop the watchers forwarding reports
- Until step 3, prod keeps the report as truth wherever one exists.
- **🔑 Monitor logs (.MLG) and each unit's timeline (v0.35.0, 2026-11-16).**
- **What:** every unit sends an `.MLG` at every call-in, in every mode. SFM reads it
(`minimateplus/mlg_file.py`, reference D.4) and keeps each unit's monitoring timeline:
sessions, gaps and what they mean, clock steps, and the call-ins, including calls that
left no file.
- **Why (Brian, 2026-11-09):** shot reports need proof that a unit which did not trigger was
monitoring. Continuous-mode units send no file on a quiet day. Outage history is the
second use.
- **Spec:** `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`.
- **Not yet:** the watcher still does not forward `.MLG`s (its repo, Brian's call), and
Terra-View shows none of it.
- **🔑 The Series-3 decode checker (2026-10-29; v0.33.0).**
- **Goal:** SFM produces everything Blastware reports, from the event file
alone (spec and plan in `docs/superpowers/`).
@@ -45,14 +56,14 @@ 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-09, run `20261109-144544`):
**Where the decoder stands** (v0.35.0; run `20261109-144544`):
**80 of 88 fields match on every event**, up from about 6 before v0.33.0,
47 before group D and 59 after it. Every other field matches or is accepted
under a carve-out with its evidence.
- Groups A, B, C and D part 1 shipped in v0.34.0 (#50, #51).
- D part 2 (the unit's own summary), E (the sensor check), F (the monitor
log), over range and the mic fixes are on `dev` and owe the next release
a backfill.
log), over range and the mic fixes shipped in v0.35.0, with its backfill
(`TOOL_VERSION` 0.35.0).
- Left: 16 values in two causes -- the vector sum's last digit on 4
waveform/histogram twins, and 4 accelerations (reference D.6.11). Brian
decided 2026-11-11 to leave both as they are, documented.
@@ -1859,10 +1870,16 @@ GET /db/monitor_log?serial=BE11529&from_dt=&to_dt= ← monitoring intervals
GET /db/sessions?serial=BE11529&limit=50 ← ACH call-home sessions, newest first
PATCH /db/events/{id}/false_trigger?value=true ← flag/unflag false triggers
GET /db/device_commands?serial=UM20147&limit=100 ← start/stop audit trail (sent, states), newest first
POST /db/import/mlg_file?serial=&call_in=true ← Blastware .MLG upload (form field mtimes = JSON {name: unix s UTC})
GET /db/units/{serial}/timeline?from_dt=&to_dt= ← sessions, gaps (+ meaning), clock steps, call-ins, from .MLGs
GET /db/units/{serial}/monitoring_at?at= ← monitoring / not_monitoring / unknown at a unit-clock time
GET /db/mlg_records?serial=BE8081&from_dt=&to_dt= ← raw .MLG records, oldest first
GET /db/mlg_files/{id} ← the original .MLG, byte for byte
```
DB file: `bridges/captures/seismo_relay.db` (default; override with `--db-path` at startup).
All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger`.
All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger` and the
`/db/import/*` uploads.
---
+25 -4
View File
@@ -1,4 +1,4 @@
# seismo-relay `v0.34.0`
# seismo-relay `v0.35.0`
A ground-up replacement for **Blastware** — Instantel's aging Windows-only
software for managing seismographs. Supports both the **MiniMate Plus
@@ -114,6 +114,19 @@ over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
> ⚠ 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*.
>
> **v0.35.0 (2026-11-16)** reaches 80 of Blastware's 88 report fields from the
> event file alone, and reads monitor logs.
> - **The file-only decode, groups D–F:** ZC frequency, displacement, times of
> peak, the sensor check, the Monitor Log line and over range, all from the
> unit's own records. A range-1 mic no longer reads 8× high.
> - **Monitor logs (.MLG):** SFM reads Blastware's `.MLG` files and keeps each
> unit's monitoring timeline, so it can answer "was unit X monitoring at T"
> for a shot report. See the `.MLG` endpoints below.
> - **An escaped checksum is the checksum, not data (#58).**
>
> ⚠ The deploy owes a backfill (about 8 hours on the NAS) and creates two
> empty tables. See the changelog's *Migration*.
> See [CHANGELOG.md](CHANGELOG.md) for full version history.
---
@@ -272,6 +285,10 @@ Query the SQLite database written by `ach_server.py`. All read-only except
| `GET` | `/db/monitor_log` | Monitoring intervals |
| `GET` | `/db/sessions` | ACH call-home session history |
| `PATCH` | `/db/events/{id}/false_trigger?value=true` | Flag / unflag false triggers |
| `GET` | `/db/units/{serial}/timeline?from_dt=&to_dt=` | A unit's monitoring timeline from its `.MLG`s: sessions (how each ended, events, trigger level), gaps and what each means, clock steps, call-ins (delivered / no_file / nothing_new). Times are the unit's own clock. |
| `GET` | `/db/units/{serial}/monitoring_at?at=` | Was the unit monitoring at `at`: `monitoring` / `not_monitoring` / `unknown`, with the session or gap that says so and the records and file behind it. |
| `GET` | `/db/mlg_records?serial=&from_dt=&to_dt=` | A unit's raw `.MLG` records, oldest first |
| `GET` | `/db/mlg_files/{id}` | The original `.MLG`, byte for byte (for printing or opening in Blastware) |
### File ingest endpoints
@@ -286,6 +303,7 @@ its Blastware filename and moved in place (see *Database* below).
|--------|-----|-------------|
| `POST` | `/db/import/blastware_file` | Series III: `.AB0*` / `.N00` binaries + paired `_ASCII.TXT`. Source: `series3-watcher`. |
| `POST` | `/db/import/idf_file` | Series IV: `.IDFH` / `.IDFW` binaries + paired `.IDFW.txt` / `.IDFH.txt`. Source: `thor-watcher`. |
| `POST` | `/db/import/mlg_file` | Series III monitor logs (`.MLG`), with each file's modified time as a JSON form field `mtimes`. Each file stored once; a damaged file stores nothing. Source: `scripts/import_mlg_dir.py` today; `series3-watcher` does not forward `.MLG`s yet. |
### DB snapshot / restore endpoints
@@ -402,13 +420,15 @@ reverse-engineering plan. The `micromate/idf_file.py` stub is where
`ach_server.py` and the file-ingest endpoints write to
`bridges/captures/seismo_relay.db` (SQLite, WAL mode) via the `SeismoDb`
persistence layer. Three tables, all unit-keyed by serial number:
persistence layer. The main tables, all unit-keyed by serial number:
| Table | Key | Contents |
|-------|-----|----------|
| `ach_sessions` | UUID | Per-call-home audit record: serial, timestamp, peer IP, events_downloaded, monitor_entries, duration_seconds |
| `events` | UUID, UNIQUE(serial, timestamp) | Triggered events: timestamp, Tran/Vert/Long/VectorSum/Mic PPV, project/client/operator/sensor_location strings, sample_rate, record_type, false_trigger flag, **`device_family`** ("series3" / "series4"), `blastware_filename` (binary at-rest in `waveforms/`), sidecar references |
| `monitor_log` | UUID, UNIQUE(serial, start_time) | Monitoring intervals: serial, waveform_key, start_time, stop_time, duration_seconds, geo_threshold_ips |
| `monitor_log` | UUID, UNIQUE(serial, start_time) | Monitoring intervals from live 0x0A reads (`ach_server.py` only): serial, waveform_key, start_time, stop_time, duration_seconds, geo_threshold_ips |
| `mlg_files` | UUID, UNIQUE(file_name, sha256) | One row per Blastware `.MLG` received (v0.35.0): serial, size, record count, empty flag, call-in flag, the file's modified time, where the original is kept, and the call it came from (`last_stop`, `no_file_stops`) |
| `mlg_records` | UUID, UNIQUE(serial, start, stop, flag word, trigger source) | One row per `.MLG` log record, stored once: start, stop (NULL = monitoring started), flag word, trigger source, Blastware's text and trigger level |
**Deduplication is by `(serial, timestamp)`** — the device clock is the
stable natural key. Repeat call-homes or re-runs UPSERT the row in place,
@@ -533,6 +553,7 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
- [x] Monitor control (start/stop, status polling, battery/memory)
- [x] Monitor log entries (continuous monitoring intervals without full waveform download)
- [x] Blastware file ingest at `/db/import/blastware_file` (paired with `series3-watcher`)
- [x] Blastware monitor logs (`.MLG`) at `/db/import/mlg_file`, and each unit's monitoring timeline (`/db/units/{serial}/timeline`, `/monitoring_at`) (v0.35.0)
**Series IV (Micromate / Thor) device support:**
- [x] Thor IDF file ingest at `/db/import/idf_file` (paired with `thor-watcher`, v0.18.0+)
@@ -542,7 +563,7 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
- [ ] Live-device protocol — pending codec
**Data persistence:**
- [x] SQLite database (`seismo_relay.db`) with `events`, `monitor_log`, `ach_sessions` tables
- [x] SQLite database (`seismo_relay.db`) with `events`, `monitor_log`, `ach_sessions`, `device_commands`, `mlg_files` and `mlg_records` tables
- [x] Per-row `device_family` column ("series3" / "series4") for clean UI / unit-of-measurement dispatch (v0.19.0+)
- [x] Deduplication by `(serial, timestamp)` — natural key handles post-erase counter resets
- [x] UPSERT on re-import refreshes every device-authoritative field (peaks, project, sample_rate); preserves operator review state (`false_trigger`)
+132 -5
View File
@@ -11,6 +11,7 @@
| Date | Section | Change |
|---|---|---|
| 2026-11-13 | Appendix D.4 (rewritten), D.4.1–D.4.4 | ✅ **The `.MLG` format, measured.** An 18-byte prefix, then 292-byte records `[length 290 LE][id 0e a0 header / 0e 80 log][…][00 00][CRC]`. The CRC is **CRC-16/AUG-CCITT over `[0:288]`, little-endian** (3,329 / 3,329 records, 1,282 files). Fields: times with the year LE, the monitor-log flag word and trigger source LE, the serial, Blastware's text. Also: one file per call-in, how sessions appear, and a Modem Exit that is not a file's last record was a call that left no file. Cross-checked against DL2 event footers: 785 / 785 for BE8081. The old D.4.1–D.4.3 (308-byte header, CRC at the start) are kept, marked retracted. Reader/writer `minimateplus/mlg_file.py`. |
| 2026-11-11 | Appendix D.3.3 | ✅ **The footer's last two bytes are a CRC-16/AUG-CCITT** (init `0x1D0F`), big-endian, over the footer record from its length prefix `00 1a` through footer `[0:22]`: 70,041 / 70,041 DL2 files. Found by the `.MLG` session, verified here. Retracts 2026-11-08's "no common CRC-16 fits": every attempt had started at the footer itself. Same CRC family as the Series IV `0x1A` block's and the `.MLG` record's. |
| 2026-11-09 | Appendix D.6.15 (NEW), D.6.6, D.6.11 | ✅ **Over range and the mic.** **D.6.15:** a peak past full scale (2,000 units = 32,000 counts; the mic in counts) is Blastware's `OORANGE`, per channel and per histogram interval, from the unit's own summary peaks. The vector sum is `OORANGE` exactly when a geophone is (43 / 43); never on its own (38 / 38 numeric), which retracts D.6.11's open "vector sum alone" case. The `<OORANGE>` line marks the mic over (18 / 18). **D.6.6:** the mic has its own range byte (label + 29): at 1 a count is an eighth, 7 DL2 events SFM read 8× high. The dB offset is **81.938216**: [81.9383, 81.9385] was too high, and every count Blastware printed leaves [81.9382058, 81.9382266]. Blastware's mic unit labels do not hold on every report; some mix dB and psi in one column. **80 of 88 report fields now match on every DL2 event.** |
| 2026-11-08 | Appendix D.6.14 (NEW), D.3.3, D.6.11 | ✅ **The monitor log is in the footer.** Every DL2 report prints one Monitor Log line: the footer's ts1 and ts2, then words for the footer's flag word `[18:20]` (`0x0001` Event Recorded, `0x0002` Keyboard Exit, `0x0004` Remote Exit, `0x0008` Selfcheck Passed, `0x0010` Timer Stop, `0x0020` Modem Exit, `0x0200` Battery Low Exit, `0x0800` Memory Full Exit; the higher session-end bit wins, from one file). Rebuilt, it equals Blastware's character for character on 69,983 / 69,983. **D.3.3:** footer `[20:22]` is the trigger source again, `[22:24]` is zero; `[24:26]` still unknown, and no common CRC-16 or sum fits. **72 of 88 report fields now match on every DL2 event.** |
@@ -3504,11 +3505,134 @@ The footer terminates the N00 file. Its bytes come directly from the terminator
> the length prefix. It is the same CRC family as the Series IV `0x1A` block's and the `.MLG`
> record's (D.4).
### D.4 MLG File Format — Monitor Log
### D.4 MLG File Format — Monitor Log ✅ 2026-11-13
**File layout:** `[308B header] [N × 292B records]`
Measured on **1,273 DL2 files** from Blastware's ACH folder (`C:\Blastware 10\Event\autocall
home`: BE6907 and BE12844 from 2026, BE8081 from 2018–19; local copy `~/dl2-archive/mlg/`) and
**9 bench files** (`example-events/`). Reader and writer: `minimateplus/mlg_file.py`. SFM's
storage and each unit's timeline: `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`.
#### D.4.1 MLG Header (308 bytes)
**File layout:** an 18-byte prefix, then whole 292-byte records. The size is always
`18 + 292·n` (1,282 / 1,282 files) ✅.
#### D.4.1 The prefix and the records ✅
| Offset | Bytes | Field |
|---|---|---|
| 0 | 18 | prefix `10 00 01 80 00 00 "Instantel\0" 07 2c` (the event file's first 18 bytes) |
| 18 | 292 | the header record (absent in an empty file) |
| 310 | 292 × n | log records |
Every record, header and log alike:
| Offset | Bytes | Field |
|---|---|---|
| 0 | 2 | length, uint16 **LE** = `0x0122` (290): the bytes after it |
| 2 | 2 | id: `0e a0` the header record (always first), `0e 80` a log record |
| 4 | 284 | content (D.4.2) |
| 288 | 2 | `00 00`, not covered by the CRC |
| 290 | 2 | CRC (D.4.3), **LE** |
- **The header record** holds only the serial, at `[24:34]` (NUL-padded ASCII). Every other
byte of it is zero on all 1,273 DL2 files.
- **An empty file** is the 18-byte prefix alone: no header record, no serial. 231 of the 1,273
DL2 files are empty.
This is the same `[length][id][payload]` shape as the event file's record chain (D.6.13); the
log record's id `0e` is the footer's. The old reading below (a 308-byte header, a CRC at each
record's start) cut every record two bytes early: the "CRC" it saw at `record[0:2]` was the
previous record's tail.
#### D.4.2 A log record's fields ✅
Offsets from the record's length field:
| Offset | Bytes | Field |
|---|---|---|
| 4 | 8 | start: day, month, year **LE**, 0, hour, minute, second (D.2) |
| 12 | 8 | stop, same format; all zeros = no stop |
| 20 | 2 | monitor-log flag word, uint16 LE: the event footer's (D.3.3, D.6.14); `0xFFFF` = monitoring started |
| 22 | 2 | trigger source, uint16 LE: `0x0001`–`0x0008` a channel, `0x0400` a histogram, 0 none |
| 24 | 10 | serial, NUL-padded ASCII |
| 34 | 254 | text, NUL-padded |
**The text** (Blastware's, not the unit's: see below):
- **"monitoring started":** `Trigger Level : Geo: 0.0500 in/s Mic: 125.0 dB(L)`, or
`Trigger Level : Histogram`
- **an event:** `08`, then the event's time in 8 bytes (year LE), then
`Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s`
- **a histogram:** `08`, its time, `Histogram\r`
- **a closed session:** `Geo: 0.0500 in/s Mic: 125.0 dB(L)`
⚠ **The text is written by Blastware.** Two bench copies of the same three records
(`ach-vs-manual/BE11529.MLG`, `BE115292.MLG`) differ only in `Trigger Level: Histogram` vs
`Trigger Level : Histogram`, and so in their CRCs. A record's identity is its times, flag word
and trigger source, never its text.
#### D.4.3 The CRC ✅ solved 2026-11-09
**CRC-16/AUG-CCITT** (poly `0x1021`, init `0x1D0F`, no reflection), over `record[0:288]` (from
the length field), stored **little-endian** at `[290:292]`. It matches **3,329 / 3,329** records
(1,282 files, header records included).
It is the same rule as the Series IV setup blocks (`content[0:2]` = N, CRC over `[0:N-2]`, stored
at `[N:N+2]`) and the event footer (D.3.3), which store it big-endian.
`minimateplus/crc.py` computes it for all three.
#### D.4.4 How Blastware writes them, and how a session appears
Measured on the three DL2 units unless marked:
- **One file per call-in**, named `<serial><counter>.MLG` with nothing between, e.g.
`BE11010304.MLG`. DL2's first file has no counter (`BE8081.MLG`). The name cannot be split by
reading it; the serial inside the file is authoritative.
- **No log record appears in two call-in files.** Each holds what happened since the previous
call-in. A cable or direct download is cumulative: the bench `4-3-26-multi/BE11529.MLG`
repeats the 4-1 records.
- **A file is written 1–2 minutes after the unit stops for its call-in** ("Modem Exit"), so the
unit's clock and the PC's agree to within those minutes.
- ⚠ Through a Windows zip, file dates read an hour early from March to October (Windows
converts with the offset in force at zip time). robocopy keeps true times.
- **A Modem Exit that is not a file's last record was a call that left no file.** Example:
`BE8081321.MLG` holds Modem Exits on 2019-04-12 18:33, 04-13 07:00 and 04-15 17:15, and only
the last produced a file.
- 38 files of the 1,273 hold more than one Modem Exit.
- 🔶 Inferred: the call failed, or the PC did not take it.
- **Empty files:** BE6907 writes one or two 2–3 minutes after nearly every real call-in (230 of
its 369 files). BE12844 never does; BE8081 did once in 707 (`BE80811.MLG`, 2018-02-19). So the
231 empty DL2 files are BE6907's 230 and that one. 🔶 Inferred: the unit calls back and has
nothing new.
- **The unit's clock steps back an hour at the first call-in after daylight saving ends.** On
2026-11-01 BE12844 ran `06:00:13 → 18:45:00` (still EDT), called in at 17:46 EST, and its next
session is `17:47:25 → 18:45:00`; BE6907 likewise. 🔶 Inferred: Blastware sets the unit's clock
at the call-in.
**How a session appears:**
- **No events:** one closed record (start, stop, flag word = why it stopped).
- **With events:** a "monitoring started" record (`0xFFFF`, no stop), then one record per event
(`0x0001` + the channel).
- The unit calls in minutes after each event, and monitoring resumes as a *new* session.
- The first session's end is written nowhere; it lies between its last event's stop and the
next start.
- **A histogram:** a "monitoring started" record at T, then a histogram record from T+1 s to
the stop, carrying the stop reason (`0x0021` = Event Recorded + Modem Exit, source `0x0400`).
Waveform event records whose start falls inside it belong to that histogram session.
**Cross-check (2026-11-13, `scratch/check_mlg_vs_events.py`):** each Event Recorded record was
matched to a DL2 event file by stop time + flag word + trigger source.
- **BE8081:** 785 / 785 records match a file, and every one of its 785 event files in that period
has its record.
- **BE6907 and BE12844:** all 25 event files have a record. The 42 records with no file all stop
after 2026-08-25, where the DL2 copy ends.
- **The footer CRCs:** all 4,303 of those three units' event files pass (D.3.3).
> ⚠ **RETRACTED 2026-11-13: D.4.1–D.4.3 below (the old reading).** The 308-byte header, the CRC
> at `record[0:2]`, the big-endian times, the 4-byte "record flags" table and the unknown CRC are
> all superseded by the sections above. They are kept as history, per this document's convention.
> The 2026-11-09 note inside them (little-endian, the flag word) was the first step of the new
> reading.
#### D.4.1 (retracted) MLG Header (308 bytes)
| Offset | Length | Field | Notes |
|---|---|---|---|
@@ -3517,7 +3641,7 @@ The footer terminates the N00 file. Its bytes come directly from the terminator
| 0x2A | 8 | serial number | null-padded ASCII (e.g. `"BE11529"`) |
| 0x32 | remainder | zero pad | pads to 308 bytes total |
#### D.4.2 MLG Record (292 bytes each)
#### D.4.2 (retracted) MLG Record (292 bytes each)
| Offset | Length | Field | Notes |
|---|---|---|---|
@@ -3564,7 +3688,10 @@ The footer terminates the N00 file. Its bytes come directly from the terminator
| 1–8 | ts1 copy (8B big-endian) |
| 9+ | `"Geo: X.XXX in/s\x00"` ASCII geo threshold |
#### D.4.3 MLG CRC
#### D.4.3 (retracted) MLG CRC
> ⚠ **Solved 2026-11-09:** CRC-16/AUG-CCITT over the record from its length field, at the record's
> end (the new D.4.3 above). Every attempt below looked for it at the record's start.
The 2-byte CRC at record[0:2] uses an unconfirmed algorithm. Tested against CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), word sums, XOR variants, and 40+ polynomial/init combinations — none matched. The writer emits `00 00`. Blastware may reject files with incorrect CRCs (impact on import unknown — TODO: test).
@@ -112,7 +112,8 @@ not part of the build.
Windows converts with the offset in force at zip time, not the one at the file's date. A
robocopy copy keeps the true time.
- **BE6907 writes two empty files 2–3 minutes after nearly every real one** (230 of its 369).
BE12844 and BE8081 never do. Inferred: the unit calls back in and has nothing new.
BE12844 never does; BE8081 did once in 707 (`BE80811.MLG`, 2018-02-19; corrected 2026-11-13
by the final review). Inferred: the unit calls back in and has nothing new.
- **Some files hold more than one Modem Exit:** 38 files (BE8081 33, BE6907 3, BE12844 2). A
file is written just after its *last* Modem Exit. The earlier ones are calls that left no file.
Example: `BE8081321` holds Modem Exits on 2019-04-12 18:33, 04-13 07:00 and 04-15 17:15.
@@ -289,10 +290,10 @@ An empty file holds no serial. Take, in order:
- Rewrite the reference's D.4 (`docs/instantel_protocol_reference.md`) with the measured framing,
checksum, fields and file behaviour, keeping the old text as a retraction. Mark D.4.3 solved.
The file is CRLF: edit it with the Edit tool.
- 🔑 **For Brian to pass to the decoder session, not edited here:** the event-file footer's
checksum (D.3.3, open since April) is the same rule. AUG-CCITT over the footer record from its
length `00 1a` through byte 24, stored big-endian. It matches **70,041 / 70,041** DL2 files.
Inferred: every record in the event file's tail chain (D.6.13) carries one.
- 🔑 **The event-file footer's checksum** (D.3.3, open since April) is the same rule:
AUG-CCITT over the footer record from its length `00 1a` through byte 24, stored big-endian,
**70,041 / 70,041** DL2 files. Recorded on `dev` by the decoder session (`8544e9c`,
2026-11-11). Inferred: every record in the event file's tail chain (D.6.13) carries one.
## Testing
+2 -10
View File
@@ -15,6 +15,8 @@ from __future__ import annotations
import struct
from minimateplus.crc import crc16_aug_ccitt as _crc16_aug_ccitt
from .models import MicromateSetup
from .protocol import ProtocolError
@@ -23,8 +25,6 @@ class SetupChecksumError(ProtocolError):
"""A config block's trailing CRC does not match its contents."""
_CRC_POLY = 0x1021
_CRC_INIT = 0x1D0F # CRC-16/AUG-CCITT
_CONTENT_SIZE = 2092 # = content[0:2] (2090) + the 2-byte CRC
# ── Head of the block ─────────────────────────────────────────────────────────
@@ -60,14 +60,6 @@ _ACTIVE_MIC = 3 # block index (0-based)
_MIC_TYPES = {2: "linear", 9: "sound_level"}
def _crc16_aug_ccitt(data: bytes) -> int:
c = _CRC_INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _CRC_POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def crc_ok(content: bytes) -> bool:
"""True if a config block's trailing checksum matches its contents.
+5 -219
View File
@@ -3,7 +3,8 @@ blastware_file.py — Blastware binary file codec for bidirectional interoperabi
Reads and writes the proprietary Instantel/Blastware file formats:
Waveform events (.CE0W, .VM0H, .440, .7M0, etc.) (extension encoding UNKNOWN — see below)
.MLG — Monitor log (monitoring session history)
Monitor logs (.MLG) live in minimateplus/mlg_file.py (reader and writer, 2026-11-13).
All waveform formats share a common 22-byte file header prefix and identical
internal binary structure (same type tag 00 12 03 00, same STRT record layout).
@@ -61,27 +62,6 @@ Waveform file structure (confirmed from example-events/4-3-26-multi/M529LIY6 (ex
Timestamp format (big-endian, 8 bytes):
[day] [month] [year_HI] [year_LO] [0x00] [hour] [min] [sec]
MLG (monitor log, confirmed from example-events/4-3-26-multi/BE11529.MLG):
[308B header] [N × 292B records]
Header (308 bytes):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 — fixed (16B)
Offset 0x10: ... (unknown structure, written as zeros + serial)
Offset 0x2A: serial number (8 bytes, null-padded ASCII, e.g. "BE11529")
... zero-padded to 308 bytes total
Record (292 bytes each):
[2B CRC] — unknown algorithm; written as 0x00 0x00
22 01 0e 80 — record marker
[ts1: 8B big-endian timestamp] — start time
[ts2: 8B big-endian timestamp] — stop time (zeros if no stop)
[4B flags] — see MLG_FLAGS_* constants below
[10B serial] — null-padded serial number ASCII
[text] — for trigger records: [0x08][8B ts1_copy] then ASCII "Geo: X.XXX in/s"
for monitoring records: b'' (or minimal separator)
[zero-padded to 292 bytes]
─── Critical implementation notes ──────────────────────────────────────────────
Waveform body reconstruction algorithm (confirmed 2026-04-21 from verification against
@@ -110,14 +90,6 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture):
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
is unknown. All examined records use non-zero values that do not match
CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), word sums, XOR variants, or
any of the 40+ polynomial/init combinations tested. The writer emits 0x0000.
This produces files that Blastware may reject or display without the CRC check —
the exact impact on BW import is unknown (TODO: test).
─── Public API ──────────────────────────────────────────────────────────────────
blastware_filename(event, serial)
@@ -133,13 +105,6 @@ MLG CRC:
read_blastware_file(path) → Event
Parse a Blastware waveform file into an Event object with waveform data populated.
(Not yet implemented — placeholder raises NotImplementedError.)
write_mlg(entries, serial, path)
Create a .MLG file from a list of MonitorLogEntry objects.
read_mlg(path) → list[MonitorLogEntry]
Parse a .MLG file into MonitorLogEntry objects.
(Not yet implemented — placeholder raises NotImplementedError.)
"""
from __future__ import annotations
@@ -152,7 +117,7 @@ from pathlib import Path
from typing import Optional, Union
from .framing import S3Frame
from .models import Event, MonitorLogEntry, Timestamp
from .models import Event, Timestamp
log = logging.getLogger(__name__)
@@ -169,9 +134,6 @@ _FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 17 byt
# Waveform file type tag (4 bytes after common prefix) — shared by ALL waveform extensions
_WAVEFORM_TYPE_TAG = b"\x00\x12\x03\x00" # confirmed from M529LIY6 (example event) — same tag for .CE0W, .VM0H, etc.
# MLG type tag (4 bytes after common prefix)
_MLG_TYPE_TAG = b"\x22\x01\x0e\xa0" # confirmed from BE11529.MLG offset 0x11..0x14
# Total header sizes
_WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# From binary: first 22 bytes = header, then STRT at byte 22.
@@ -180,17 +142,6 @@ _WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# Re-count: b"\x10\x00\x01\x80\x00\x00" = 6B + b"Instantel\x00" = 10B + b"\x07\x2c" = 2B = 18B prefix.
_FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 18 bytes
_WAVEFORM_HEADER_SIZE = 22 # 18 + 4 = 22 bytes ✅
_MLG_HEADER_SIZE = 308 # confirmed from BE11529.MLG
# MLG record marker (4 bytes after 2-byte CRC at start of each record)
_MLG_RECORD_MARKER = b"\x22\x01\x0e\x80"
_MLG_RECORD_SIZE = 292 # bytes per record (confirmed from BE11529.MLG)
# MLG record flags (4 bytes at record[22:26])
# Confirmed from BE11529.MLG binary inspection:
MLG_FLAGS_START_ONLY = b"\xff\xff\x00\x00" # monitoring start with no stop
MLG_FLAGS_TRIGGER = b"\x01\x00\x02\x00" # triggered event (has ts1 + ts2)
MLG_FLAGS_INTERVAL = b"\x02\x00\x00\x00" # monitoring interval (has ts1 + ts2)
# ── Timestamp helpers ─────────────────────────────────────────────────────────
@@ -199,7 +150,8 @@ def _encode_ts_be(ts: Optional[datetime.datetime]) -> bytes:
"""
Encode a datetime as an 8-byte big-endian Blastware timestamp.
Format (waveform file and MLG record timestamps):
Format (event file timestamps; an .MLG stores the year little-endian,
see minimateplus/mlg_file.py):
[day][month][year_HI][year_LO][0x00][hour][min][sec]
Big-endian year confirmed from M529LIY6 (example event) footer:
@@ -936,169 +888,3 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_blastware_file() is not yet implemented")
# ── MLG file writer ───────────────────────────────────────────────────────────
def _build_mlg_header(serial: str) -> bytes:
"""
Build the 308-byte MLG file header.
Header structure (confirmed from BE11529.MLG binary inspection):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 (22B)
Offset 0x16: ... (16B unknown — observed as zeros in BE11529.MLG)
Offset 0x2A: serial number (8 bytes, null-padded ASCII)
... rest zero-padded to 308 bytes
The serial string "BE11529" appears at offset 0x2A (42 decimal).
"""
buf = bytearray(_MLG_HEADER_SIZE)
# Common prefix + MLG type tag
prefix = _FILE_HEADER_PREFIX + _MLG_TYPE_TAG # 22 bytes
buf[0:len(prefix)] = prefix
# Serial number at offset 0x2A
serial_bytes = serial.encode("ascii", errors="replace")[:8]
serial_padded = serial_bytes.ljust(8, b"\x00")
buf[0x2A : 0x2A + 8] = serial_padded
return bytes(buf)
def _build_mlg_record(
entry: MonitorLogEntry,
serial: str,
) -> bytes:
"""
Build one 292-byte MLG record from a MonitorLogEntry.
Record layout (confirmed from BE11529.MLG binary inspection):
[0:2] CRC — 2-byte CRC (algorithm unknown; written as 0x0000)
[2:6] marker — 22 01 0e 80
[6:14] ts1 — 8B big-endian start timestamp
[14:22] ts2 — 8B big-endian stop timestamp
[22:26] flags — 4B record flags (see MLG_FLAGS_* constants)
[26:36] serial — 10B null-padded serial number
[36:] text — for triggered events: [0x08][8B ts1_copy]["Geo: X.XXX in/s"]
for monitoring intervals: b"" or minimal separator
[... zero-padded to 292 bytes]
Flags based on entry type:
- MonitorLogEntry with start_time only (no stop_time): MLG_FLAGS_START_ONLY
- MonitorLogEntry with both times and geo_threshold_ips set: MLG_FLAGS_TRIGGER
- MonitorLogEntry with both times (monitoring interval): MLG_FLAGS_INTERVAL
The triggered-event text block (flags = MLG_FLAGS_TRIGGER):
[0x08] [ts1: 8B] [ASCII "Geo: X.XXX in/s\x00"]
Confirmed from BE11529.MLG records at offset 0x0134 and 0x0258.
"""
buf = bytearray(_MLG_RECORD_SIZE)
start_dt = (
datetime.datetime(
entry.start_time.year, entry.start_time.month, entry.start_time.day,
entry.start_time.hour, entry.start_time.minute, entry.start_time.second,
)
if entry.start_time else None
)
stop_dt = (
datetime.datetime(
entry.stop_time.year, entry.stop_time.month, entry.stop_time.day,
entry.stop_time.hour, entry.stop_time.minute, entry.stop_time.second,
)
if entry.stop_time else None
)
# [0:2] CRC placeholder
buf[0:2] = b"\x00\x00"
# [2:6] Record marker
buf[2:6] = _MLG_RECORD_MARKER
# [6:14] ts1
buf[6:14] = _encode_ts_be(start_dt)
# [14:22] ts2
buf[14:22] = _encode_ts_be(stop_dt)
# [22:26] flags
if stop_dt is None:
flags = MLG_FLAGS_START_ONLY
elif entry.geo_threshold_ips is not None:
flags = MLG_FLAGS_TRIGGER
else:
flags = MLG_FLAGS_INTERVAL
buf[22:26] = flags
# [26:36] serial (10B null-padded)
serial_bytes = serial.encode("ascii", errors="replace")[:10]
buf[26 : 26 + len(serial_bytes)] = serial_bytes
# [36:] text content
pos = 36
if flags == MLG_FLAGS_TRIGGER:
# Extra ts1 copy: [0x08][ts1: 8B]
buf[pos] = 0x08
pos += 1
buf[pos : pos + 8] = _encode_ts_be(start_dt)
pos += 8
if entry.geo_threshold_ips is not None:
geo_text = f"Geo: {entry.geo_threshold_ips:.3f} in/s\x00".encode("ascii")
buf[pos : pos + len(geo_text)] = geo_text
pos += len(geo_text)
return bytes(buf)
def write_mlg(
entries: list[MonitorLogEntry],
serial: str,
path: Union[str, Path],
) -> None:
"""
Write a Blastware .MLG monitor log file.
Args:
entries: List of MonitorLogEntry objects (from get_monitor_log_entries()).
Each entry produces one 292-byte record in the file.
serial: Device serial number string (e.g. "BE11529").
Written to the file header and each record.
path: Destination file path. Extension is not enforced — use ".MLG".
File layout:
[308B header] [N × 292B records]
Note: The 2-byte CRC at the start of each record is written as 0x0000.
The CRC algorithm is unknown (see module docstring).
Raises:
OSError: if the file cannot be written.
"""
path = Path(path)
header = _build_mlg_header(serial)
with open(path, "wb") as f:
f.write(header)
for entry in entries:
record = _build_mlg_record(entry, serial)
f.write(record)
def read_mlg(path: Union[str, Path]) -> list[MonitorLogEntry]:
"""
Parse a Blastware .MLG file into a list of MonitorLogEntry objects.
NOT YET IMPLEMENTED.
Args:
path: Path to the .MLG file.
Returns:
List of MonitorLogEntry objects.
Raises:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_mlg() is not yet implemented")
+23
View File
@@ -0,0 +1,23 @@
"""
minimateplus/crc.py — Instantel's record checksum, shared by every reader that checks one.
CRC-16/AUG-CCITT: poly 0x1021, init 0x1D0F, no reflection, no final XOR. The
same rule covers a Micromate's setup blocks (0x1A, 0x08, 0x2E; stored big-endian),
a Blastware event file's footer (big-endian) and every .MLG record (little-endian).
Each block says where its checksum sits; this module only computes it.
"""
from __future__ import annotations
_POLY = 0x1021
_INIT = 0x1D0F
def crc16_aug_ccitt(data: bytes) -> int:
"""CRC-16/AUG-CCITT of `data` (check value: b"123456789" -> 0xE5CC)."""
c = _INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
+1 -1
View File
@@ -54,7 +54,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.34.0" # file-only decode groups A-D, histogram times (#51); gates the backfill regen
TOOL_VERSION = "0.35.0" # file-only decode groups D2, E, F, over range, mic range; gates the backfill regen
try:
# Best-effort: prefer the installed metadata when it's NEWER than the
+185
View File
@@ -0,0 +1,185 @@
"""
minimateplus/mlg_file.py — Blastware's monitor log (.MLG): reader and writer.
Blastware writes one .MLG per call-in, named <serial><counter>.MLG, holding what
the unit logged since the previous call-in: each time monitoring started, each
event, and each time it stopped and why. Measured on 1,273 DL2 files and 9
bench files (2026-11-09; reference D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md):
[18-byte prefix 10 00 01 80 00 00 "Instantel\\0" 07 2c]
[292-byte records ...] size is always 18 + 292*n
Every record:
[0:2] length, uint16 LE = 290
[2:4] id: 0e a0 the header record (first, carries the serial), 0e 80 a log record
[4:12] start: day, month, year LE, 0, hour, minute, second
[12:20] stop, same format; all zeros = no stop
[20:22] monitor-log flag word, uint16 LE (the event footer's, D.6.14); 0xFFFF = started
[22:24] trigger source, uint16 LE: 0x0001-0x0008 a channel, 0x0400 a histogram
[24:34] serial, NUL-padded ASCII
[34:288] text, NUL-padded; an event's starts 0x08 + its 8-byte time
[288:290] 00 00
[290:292] CRC-16/AUG-CCITT over [0:288], little-endian
An empty file is the prefix alone: no header record, no serial. Pure: no I/O
beyond reading the path it is given.
"""
from __future__ import annotations
import datetime
import struct
from pathlib import Path
from typing import Optional, Union
from .crc import crc16_aug_ccitt
from .event_file_io import monitor_log_description
from .models import MlgFile, MlgRecord
MLG_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c"
RECORD_SIZE = 292
_RECORD_LENGTH = 290
_HEADER_ID = b"\x0e\xa0"
_LOG_ID = b"\x0e\x80"
_EVENT_TIME_MARK = 0x08
_TRIGGER_LEVEL_PREFIXES = ("Trigger Level :", "Trigger Level:")
class MlgFormatError(ValueError):
"""The bytes are not a whole .MLG file."""
def _ts(raw: bytes) -> Optional[datetime.datetime]:
"""8-byte MLG time (year little-endian); all zeros = None. Raises ValueError."""
if raw == bytes(8):
return None
year = struct.unpack_from("<H", raw, 2)[0]
return datetime.datetime(year, raw[1], raw[0], raw[5], raw[6], raw[7])
def _crc_ok(record: bytes) -> bool:
return crc16_aug_ccitt(record[:288]) == struct.unpack_from("<H", record, 290)[0]
def _trigger_level(text: str) -> Optional[str]:
line = text.split("\r", 1)[0]
for prefix in _TRIGGER_LEVEL_PREFIXES:
if line.startswith(prefix):
line = line[len(prefix):]
break
line = line.strip()
return line or None
def _log_record(index: int, rec: bytes) -> MlgRecord:
try:
start = _ts(rec[4:12])
stop = _ts(rec[12:20])
except ValueError as exc:
raise MlgFormatError(f"record {index}: a time cannot be decoded ({exc})") from None
if start is None:
raise MlgFormatError(f"record {index}: no start time")
flags, source = struct.unpack_from("<HH", rec, 20)
text_raw = rec[34:288]
body, event_time = text_raw, None
if text_raw[0] == _EVENT_TIME_MARK:
try:
event_time = _ts(text_raw[1:9])
except ValueError as exc:
raise MlgFormatError(f"record {index}: the event time cannot be decoded ({exc})") from None
body = text_raw[9:]
text = body.split(b"\x00", 1)[0].decode("latin-1")
is_start = flags == 0xFFFF
return MlgRecord(
index=index,
start=start,
stop=stop,
flags=flags,
trigger_source=source,
serial=rec[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
text_raw=text_raw,
event_time=event_time,
text=text,
trigger_level=_trigger_level(text),
description="Monitoring started" if is_start else monitor_log_description(flags).strip(),
crc_ok=_crc_ok(rec),
)
def parse_mlg(data: bytes) -> MlgFile:
"""Parse the bytes of a .MLG file.
Raises MlgFormatError when the bytes are not a whole .MLG. A record whose
checksum fails is returned with crc_ok=False (MlgFile.crc_failures lists
them); the caller decides what to do with it."""
if len(data) < len(MLG_PREFIX) or not data.startswith(MLG_PREFIX):
raise MlgFormatError("not an MLG: the 18-byte Instantel prefix is missing")
body = data[len(MLG_PREFIX):]
if len(body) % RECORD_SIZE:
raise MlgFormatError(f"not an MLG: size {len(data)} is not 18 + 292*n")
records = [body[i:i + RECORD_SIZE] for i in range(0, len(body), RECORD_SIZE)]
if not records:
return MlgFile(serial=None)
for index, rec in enumerate(records):
length = struct.unpack_from("<H", rec, 0)[0]
if length != _RECORD_LENGTH:
raise MlgFormatError(f"record {index}: length field {length}, expected 290")
expected = _HEADER_ID if index == 0 else _LOG_ID
if rec[2:4] != expected:
raise MlgFormatError(f"record {index}: id {rec[2:4].hex()}, expected {expected.hex()}")
header = records[0]
return MlgFile(
serial=header[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
records=[_log_record(i, rec) for i, rec in enumerate(records) if i > 0],
header_crc_ok=_crc_ok(header),
)
def read_mlg(path: Union[str, Path]) -> MlgFile:
"""Read and parse a .MLG file."""
return parse_mlg(Path(path).read_bytes())
# ── Writer ────────────────────────────────────────────────────────────────────
def _ts_bytes(ts: Optional[datetime.datetime]) -> bytes:
if ts is None:
return bytes(8)
return bytes([ts.day, ts.month]) + struct.pack("<H", ts.year) + bytes([0, ts.hour, ts.minute, ts.second])
def _serial_field(serial: str) -> bytes:
return serial.encode("ascii", errors="replace")[:10].ljust(10, b"\x00")
def _sealed(body: bytes) -> bytes:
"""`body` is record[0:288]; append the two zero bytes and the LE checksum."""
return body + b"\x00\x00" + struct.pack("<H", crc16_aug_ccitt(body))
def _header_record(serial: str) -> bytes:
# Every byte but the serial is zero on all 1,273 DL2 files (measured 2026-11-13).
body = struct.pack("<H", _RECORD_LENGTH) + _HEADER_ID + bytes(20) + _serial_field(serial)
return _sealed(body.ljust(288, b"\x00"))
def _log_record_bytes(r: MlgRecord) -> bytes:
body = (struct.pack("<H", _RECORD_LENGTH) + _LOG_ID + _ts_bytes(r.start) + _ts_bytes(r.stop)
+ struct.pack("<HH", r.flags, r.trigger_source) + _serial_field(r.serial)
+ r.text_raw.ljust(254, b"\x00")[:254])
return _sealed(body)
def mlg_bytes(mlg: MlgFile) -> bytes:
"""The bytes of a .MLG file, as Blastware writes them: little-endian times,
length-led records, each record's checksum computed. An empty MlgFile is
the prefix alone."""
if mlg.empty:
return MLG_PREFIX
return MLG_PREFIX + _header_record(mlg.serial or "") + b"".join(_log_record_bytes(r) for r in mlg.records)
def write_mlg(mlg: MlgFile, path: Union[str, Path]) -> None:
"""Write `mlg` to `path` (see mlg_bytes)."""
Path(path).write_bytes(mlg_bytes(mlg))
+46
View File
@@ -729,6 +729,52 @@ class MonitorLogEntry:
return f"MonitorLog#{self.index} key={self.key} {start}→{stop}{dur}"
# ── Blastware monitor log (.MLG) ──────────────────────────────────────────────
@dataclass
class MlgRecord:
"""One log record of a Blastware .MLG file (minimateplus/mlg_file.py).
Times are the unit's own local clock. `flags` is the monitor-log flag word
(the event footer's, reference D.6.14); 0xFFFF means monitoring started
and has no stop yet."""
index: int # position in the file; 0 is the header record
start: datetime.datetime
stop: Optional[datetime.datetime]
flags: int
trigger_source: int # 0x0001-0x0008 a channel, 0x0400 a histogram, 0 none
serial: str
text_raw: bytes = field(repr=False) # record[34:288] exactly, for write_mlg
event_time: Optional[datetime.datetime] = None
text: str = "" # Blastware's text, after any event time
trigger_level: Optional[str] = None # e.g. "Geo: 0.0500 in/s Mic: 125.0 dB(L)", "Histogram"
description: str = "" # "Monitoring started", or Blastware's words
crc_ok: bool = True
@property
def is_start(self) -> bool:
return self.flags == 0xFFFF
@dataclass
class MlgFile:
"""A whole .MLG file: the serial from its header record and its log records,
in file order. An empty file (the 18-byte prefix alone) has neither."""
serial: Optional[str]
records: list[MlgRecord] = field(default_factory=list)
header_crc_ok: bool = True
@property
def empty(self) -> bool:
return self.serial is None and not self.records
@property
def crc_failures(self) -> list[int]:
"""Indexes of the records whose checksum fails (0 is the header record)."""
head = [] if self.header_crc_ok else [0]
return head + [r.index for r in self.records if not r.crc_ok]
# ── MonitorStatus ─────────────────────────────────────────────────────────────
@dataclass
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "seismo-relay"
version = "0.34.0"
version = "0.35.0"
description = "Python client and REST server for MiniMate Plus seismographs"
requires-python = ">=3.10"
dependencies = [
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Cross-check .MLG records against Blastware event files, in both directions.
check_mlg_vs_events.py <mlg dir> <event dir>
Every .MLG record with the Event Recorded bit (not a "monitoring started" one)
should have an event file whose footer has the same stop time, flag word and
trigger source; and every event file inside a unit's .MLG period (its first
record's start to its last record's stop) should have such a record. The
footer is read straight from each event file's last 28 bytes, independently of
the event decoder, and its CRC-16/AUG-CCITT is checked on the way.
Spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §7. Read-only.
"""
from __future__ import annotations
import collections
import datetime
import os
import struct
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.crc import crc16_aug_ccitt
from minimateplus.mlg_file import MlgFormatError, read_mlg
from sfm.waveform_store import _serial_number_from_bw_filename
_FOOTER_HEAD = b"\x00\x1a\x0e\x08"
def _ts_be(raw: bytes):
try:
return datetime.datetime(struct.unpack(">H", raw[2:4])[0], raw[1], raw[0], raw[5], raw[6], raw[7])
except ValueError:
return None
def _serial_number(serial: str):
digits = "".join(ch for ch in serial if ch.isdigit())
return int(digits) if digits else None
def mlg_side(mlg_dir: Path):
"""{unit number: (serial, [(stop, flags, source)], first start, last stop)}"""
units = {}
for path in sorted(p for p in mlg_dir.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"):
try:
mlg = read_mlg(path)
except MlgFormatError as exc:
print(f" skipped {path}: {exc}")
continue
if not mlg.serial or not mlg.records:
continue
n = _serial_number(mlg.serial)
serial, keys, lo, hi = units.get(n, (mlg.serial, [], None, None))
for r in mlg.records:
lo = min(lo, r.start) if lo else r.start
if r.stop:
hi = max(hi, r.stop) if hi else r.stop
if not r.is_start and r.flags & 0x0001:
keys.append((r.stop, r.flags, r.trigger_source))
units[n] = (serial, keys, lo, hi)
return units
def event_side(event_dir: Path, wanted: set):
"""{unit number: [(stop, flags, source, file name)]}, plus footer CRC failures."""
files = collections.defaultdict(list)
crc_bad = 0
for entry in os.scandir(event_dir):
if not entry.is_file():
continue
n = _serial_number_from_bw_filename(entry.name)
if n not in wanted:
continue
with open(entry.path, "rb") as f:
f.seek(0, 2)
if f.tell() < 28:
continue
f.seek(-28, 2)
tail = f.read(28)
if not tail.startswith(_FOOTER_HEAD):
continue
if crc16_aug_ccitt(tail[0:24]) != struct.unpack(">H", tail[26:28])[0]:
crc_bad += 1
flags, source = struct.unpack(">HH", tail[20:24])
files[n].append((_ts_be(tail[12:20]), flags, source, entry.name))
return files, crc_bad
def main(argv=None) -> int:
argv = argv if argv is not None else sys.argv[1:]
if len(argv) != 2:
print(__doc__)
return 2
units = mlg_side(Path(argv[0]))
files, crc_bad = event_side(Path(argv[1]), set(units))
checked = sum(len(v) for v in files.values())
print(f"event-file footers checked (units with .MLGs only): {checked}, failing their CRC: {crc_bad}")
for n, (serial, keys, lo, hi) in sorted(units.items(), key=lambda kv: kv[1][0]):
in_period = [f for f in files.get(n, []) if f[0] and lo <= f[0] <= hi]
file_keys = {f[:3] for f in in_period}
rec_keys = set(keys)
matched = [k for k in keys if k in file_keys]
record_only = [k for k in keys if k not in file_keys]
file_only = [f for f in in_period if f[:3] not in rec_keys]
print(f"\n{serial}: .MLG period {lo} -> {hi}")
print(f" matched {len(matched)}, record-only {len(record_only)}, file-only {len(file_only)}")
for k in record_only[:5]:
print(f" record-only: stop {k[0]} flags {k[1]:#06x} source {k[2]:#06x}")
if record_only:
print(f" record-only stops run {min(k[0] for k in record_only)} -> {max(k[0] for k in record_only)}")
for f in file_only[:5]:
print(f" file-only: {f[3]} stop {f[0]} flags {f[1]:#06x} source {f[2]:#06x}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Import every Blastware .MLG under a directory into SFM's DB and waveform store.
import_mlg_dir.py <dir> --db-path P --store-root S [--dry-run] [--not-call-in]
For a copy of an ACH folder (DL2 holds ~86,000). Idempotent: a file already
stored (same name, same bytes) counts as a duplicate. Files with records go
first, then the empty ones, so every unit's serial is known before its empty
files arrive whatever the folder order. Each file's modified time is stored
as its call-in time: copy with robocopy, not a Windows zip, whose dates read
an hour early from March to October.
Operational consequence: writes rows to mlg_files / mlg_records and copies each
original into <store>/<serial>/mlg/. The dry run writes nothing.
"""
from __future__ import annotations
import argparse
import datetime
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.mlg_file import MLG_PREFIX, MlgFormatError, parse_mlg
from sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg
from sfm.waveform_store import WaveformStore
log = logging.getLogger("import_mlg_dir")
_COUNTS = ("files", "ok", "duplicate", "error", "empty", "unresolved", "inserted", "skipped")
def _mlg_files(root: Path) -> list[Path]:
"""Files with records first, then empty ones; each group oldest first."""
found = [p for p in root.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"]
key = lambda p: (p.stat().st_size <= len(MLG_PREFIX), p.stat().st_mtime, p.name)
return sorted(found, key=key)
def import_dir(root: Path, db_path: str, store_root: str, *, dry_run: bool = False,
call_in: bool = True) -> dict:
counts = dict.fromkeys(_COUNTS, 0)
db = store = None
if not dry_run:
db, store = SeismoDb(db_path), WaveformStore(store_root)
for path in _mlg_files(root):
counts["files"] += 1
data = path.read_bytes()
if dry_run:
try:
mlg = parse_mlg(data)
except MlgFormatError as exc:
counts["error"] += 1
log.warning("%s: %s", path, exc)
continue
counts["error" if mlg.crc_failures else "ok"] += 1
counts["empty"] += mlg.empty
continue
mtime = datetime.datetime.fromtimestamp(path.stat().st_mtime, datetime.timezone.utc)
res = ingest_mlg(db, store, path.name, data, file_mtime=mtime, call_in=call_in)
counts[res["status"]] += 1
if res["status"] == "error":
log.warning("%s: %s", path, res["detail"])
continue
counts["empty"] += res["empty"]
counts["unresolved"] += res["serial_unresolved"]
counts["inserted"] += res["inserted"]
counts["skipped"] += res["skipped"]
return counts
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("dir")
ap.add_argument("--db-path", required=True)
ap.add_argument("--store-root", required=True)
ap.add_argument("--dry-run", action="store_true", help="parse and check only; write nothing")
ap.add_argument("--not-call-in", action="store_true",
help="these are cable / direct downloads, not call-ins")
a = ap.parse_args(argv)
logging.basicConfig(level=logging.WARNING)
counts = import_dir(Path(a.dir), a.db_path, a.store_root, dry_run=a.dry_run,
call_in=not a.not_call_in)
for key in _COUNTS:
print(f"{key} {counts[key]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+159 -3
View File
@@ -1,11 +1,15 @@
"""
sfm/database.py — SQLite persistence layer for seismo-relay.
Three tables, all keyed by unit serial number:
Tables, all keyed by unit serial number:
ach_sessions — one row per inbound ACH call-home
events — one row per triggered waveform event (deduped by serial+timestamp)
monitor_log — one row per monitoring interval (deduped by serial+start_time)
monitor_log — one row per monitoring interval (deduped by serial+start_time);
live 0x0A reads by bridges/ach_server.py only
mlg_files — one row per Blastware .MLG received (deduped by file name+sha256)
mlg_records — one row per .MLG log record (deduped by serial, start, stop,
flag word, trigger source — never the text, which Blastware writes)
The DB file lives at:
<output_dir>/seismo_relay.db (default: bridges/captures/seismo_relay.db)
@@ -43,7 +47,7 @@ from pathlib import Path
from typing import Optional
from minimateplus.blastware_file import blastware_filename_time
from minimateplus.models import Event, MonitorLogEntry
from minimateplus.models import Event, MlgRecord, MonitorLogEntry
log = logging.getLogger("sfm.database")
@@ -150,6 +154,43 @@ CREATE TABLE IF NOT EXISTS device_commands (
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
-- Blastware monitor logs (.MLG): spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
-- Record times are the unit's own local clock (naive ISO); file_mtime is UTC (+00:00).
CREATE TABLE IF NOT EXISTS mlg_files (
id TEXT PRIMARY KEY,
serial TEXT, -- NULL: an empty file whose unit is not known yet
file_name TEXT NOT NULL,
sha256 TEXT NOT NULL,
size INTEGER NOT NULL,
record_count INTEGER NOT NULL, -- log records in the file (header excluded)
empty INTEGER NOT NULL, -- 1: the 18-byte prefix alone
call_in INTEGER NOT NULL DEFAULT 1, -- 0: a cable / direct download
file_mtime TEXT, -- the file's modified time, when the sender gave it
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%S+00:00', 'now')),
stored_path TEXT, -- the original file, relative to the waveform store
last_stop TEXT, -- the stop of the file's last record: the call that sent it
no_file_stops TEXT, -- JSON: earlier Modem Exit stops in it, calls that left no file
UNIQUE(file_name, sha256)
);
CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial);
CREATE TABLE IF NOT EXISTS mlg_records (
id TEXT PRIMARY KEY,
serial TEXT NOT NULL,
start_time TEXT NOT NULL,
stop_time TEXT, -- NULL: "monitoring started", no stop yet
flags INTEGER NOT NULL, -- monitor-log flag word; 65535 = started
trigger_source INTEGER NOT NULL, -- 1-8 a channel, 1024 a histogram, 0 none
text TEXT,
trigger_level TEXT,
event_time TEXT,
file_id TEXT NOT NULL REFERENCES mlg_files(id), -- the file it first came in
seq INTEGER NOT NULL -- its position in that file (1 = first log record)
);
-- NULL stops are distinct to a UNIQUE constraint, so the identity uses COALESCE.
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
"""
@@ -1259,6 +1300,121 @@ class SeismoDb:
).fetchall()
return [dict(r) for r in rows]
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────
def mlg_file_exists(self, file_name: str, sha256: str) -> bool:
with self._connect() as conn:
row = conn.execute(
"SELECT 1 FROM mlg_files WHERE file_name = ? AND sha256 = ?",
(file_name, sha256),
).fetchone()
return row is not None
def insert_mlg(
self,
*,
serial: Optional[str],
file_name: str,
sha256: str,
size: int,
empty: bool,
call_in: bool,
file_mtime: Optional[datetime.datetime],
stored_path: Optional[str],
records: list[MlgRecord],
last_stop: Optional[datetime.datetime] = None,
no_file_stops: Optional[list[datetime.datetime]] = None,
) -> tuple[Optional[str], int, int]:
"""Store one .MLG file and its log records, in one transaction.
Returns (file_id, inserted, skipped); (None, 0, 0) when this file name
with these bytes is already stored. A record already stored (from an
earlier file) is skipped and keeps pointing at that file; the file's own
call summary (last_stop, no_file_stops) is kept on its row either way."""
file_id = self._new_id()
inserted = skipped = 0
no_file_json = json.dumps([self._iso(t) for t in (no_file_stops or [])])
with self._connect() as conn:
try:
conn.execute(
"""
INSERT INTO mlg_files
(id, serial, file_name, sha256, size, record_count, empty,
call_in, file_mtime, stored_path, last_stop, no_file_stops)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(file_id, serial, file_name, sha256, size, len(records), int(empty),
int(call_in), self._iso(file_mtime), stored_path, self._iso(last_stop),
no_file_json),
)
except sqlite3.IntegrityError:
return None, 0, 0
for r in records:
cur = conn.execute(
"""
INSERT OR IGNORE INTO mlg_records
(id, serial, start_time, stop_time, flags, trigger_source,
text, trigger_level, event_time, file_id, seq)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(self._new_id(), serial, self._iso(r.start), self._iso(r.stop), r.flags,
r.trigger_source, r.text, r.trigger_level, self._iso(r.event_time),
file_id, r.index),
)
if cur.rowcount:
inserted += 1
else:
skipped += 1
log.debug("insert_mlg %s inserted=%d skipped=%d", file_name, inserted, skipped)
return file_id, inserted, skipped
def query_mlg_records(
self,
serial: str,
from_dt: Optional[datetime.datetime] = None,
to_dt: Optional[datetime.datetime] = None,
) -> list[dict]:
"""A unit's .MLG records, oldest first (start time, then position in file)."""
clauses, params = ["serial = ?"], [serial]
if from_dt:
clauses.append("start_time >= ?")
params.append(from_dt.isoformat())
if to_dt:
clauses.append("start_time <= ?")
params.append(to_dt.isoformat())
with self._connect() as conn:
rows = conn.execute(
f"SELECT * FROM mlg_records WHERE {' AND '.join(clauses)} "
f"ORDER BY start_time, seq",
params,
).fetchall()
return [dict(r) for r in rows]
def query_mlg_files(self, serial: str) -> list[dict]:
"""A unit's received .MLG files, oldest file time first."""
with self._connect() as conn:
rows = conn.execute(
"SELECT * FROM mlg_files WHERE serial = ? "
"ORDER BY COALESCE(file_mtime, received_at), file_name",
(serial,),
).fetchall()
return [dict(r) for r in rows]
def get_mlg_file(self, file_id: str) -> Optional[dict]:
with self._connect() as conn:
row = conn.execute("SELECT * FROM mlg_files WHERE id = ?", (file_id,)).fetchone()
return dict(row) if row else None
def known_serials(self) -> set[str]:
"""Every serial SFM holds data for: events, .MLG files and records."""
with self._connect() as conn:
rows = conn.execute(
"SELECT serial FROM events WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_files WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_records"
).fetchall()
return {r["serial"] for r in rows if r["serial"]}
# ── Fleet overview ────────────────────────────────────────────────────────
def query_units(self) -> list[dict]:
+130
View File
@@ -0,0 +1,130 @@
"""
sfm/mlg_ingest.py — take in one Blastware .MLG: verify it, work out its unit,
keep the original, store its records once.
Shared by POST /db/import/mlg_file and scripts/import_mlg_dir.py. Spec:
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3, §5, §6.
"""
from __future__ import annotations
import datetime
import hashlib
import logging
import re
from pathlib import Path
from typing import Optional
from minimateplus.mlg_file import MlgFormatError, parse_mlg
log = logging.getLogger("sfm.mlg_ingest")
_MODEM_EXIT = 0x0020
# A serial becomes a directory in the waveform store, and a header serial comes
# from the file's own bytes: only plain serials (BE6907, UM20147) are used.
_SERIAL_RE = re.compile(r"[A-Za-z0-9]{1,16}")
def usable_serial(serial: Optional[str]) -> bool:
return bool(serial) and _SERIAL_RE.fullmatch(serial) is not None
def resolve_serial(
file_name: str,
header_serial: Optional[str],
hint: Optional[str],
known: set[str],
) -> Optional[str]:
"""The unit a .MLG belongs to.
The serial inside the file wins; then the caller's hint. An empty file
carries none, and its name is <serial><counter> with nothing between, so
take the longest serial SFM already knows that the name starts with,
followed only by digits (or nothing: DL2's first file was BE8081.MLG).
None when nothing fits."""
if header_serial:
return header_serial
if hint:
return hint
stem = Path(file_name).name
if stem.upper().endswith(".MLG"):
stem = stem[:-4]
def fits(serial: str) -> bool:
counter = stem[len(serial):]
return stem.upper().startswith(serial.upper()) and (counter == "" or counter.isdigit())
candidates = [s for s in known if fits(s)]
return max(candidates, key=len) if candidates else None
def ingest_mlg(
db,
store,
file_name: str,
data: bytes,
*,
serial_hint: Optional[str] = None,
file_mtime: Optional[datetime.datetime] = None,
call_in: bool = True,
) -> dict:
"""Ingest one .MLG. Never raises for a bad file: the result says what happened.
status "error": not a whole .MLG, or any record fails its checksum — nothing
of it is stored. status "duplicate": this name with these bytes is already
stored. status "ok": the original is kept and its new records stored."""
result = {
"filename": file_name, "status": "error", "detail": None, "serial": None,
"serial_unresolved": False, "empty": False, "records": 0,
"inserted": 0, "skipped": 0, "file_id": None,
}
try:
mlg = parse_mlg(data)
except MlgFormatError as exc:
result["detail"] = str(exc)
return result
result["records"] = len(mlg.records)
result["empty"] = mlg.empty
if mlg.crc_failures:
result["detail"] = ", ".join(f"record {i}" for i in mlg.crc_failures) + " fails its checksum"
return result
header = mlg.serial or None
for label, value in (("the file's serial", header), ("the serial hint", serial_hint)):
if value is not None and not usable_serial(value):
result["detail"] = f"{label} {value!r} is not a plain serial"
return result
known = db.known_serials() if not (header or serial_hint) else set()
serial = resolve_serial(file_name, header, serial_hint, known)
if mlg.records and serial is None:
result["detail"] = "no serial: the file's header carries none and no hint was given"
return result
result["serial"] = serial
result["serial_unresolved"] = serial is None
# What this file says about calls, kept per file: a record stored once may
# have arrived first in another file (a cable download). The file was sent
# by the call that ended its last record; every earlier Modem Exit in it was
# a call that left no file.
last_stop = mlg.records[-1].stop if mlg.records else None
no_file_stops = [r.stop for r in mlg.records[:-1]
if not r.is_start and r.flags & _MODEM_EXIT and r.stop]
sha256 = hashlib.sha256(data).hexdigest()
if db.mlg_file_exists(file_name, sha256):
result["status"] = "duplicate"
result["detail"] = "this file is already stored"
return result
stored_path = store.save_mlg(serial, file_name, data)
file_id, inserted, skipped = db.insert_mlg(
serial=serial, file_name=file_name, sha256=sha256, size=len(data), empty=mlg.empty,
call_in=call_in, file_mtime=file_mtime, stored_path=stored_path, records=mlg.records,
last_stop=last_stop, no_file_stops=no_file_stops,
)
if file_id is None: # stored between the check and the insert
result["status"] = "duplicate"
result["detail"] = "this file is already stored"
return result
result.update(status="ok", file_id=file_id, inserted=inserted, skipped=skipped)
log.info("mlg %s serial=%s inserted=%d skipped=%d", file_name, serial, inserted, skipped)
return result
+359
View File
@@ -0,0 +1,359 @@
"""
sfm/mlg_timeline.py — a unit's monitoring timeline from its .MLG records.
Pure: takes the rows SeismoDb.query_mlg_records / query_mlg_files return and
gives back plain dicts (times as ISO strings). Spec §4,
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
How sessions appear in a .MLG (measured on BE6907, BE12844, BE8081):
* a session with no events is one closed record: start, stop and why it stopped
* a session with events is a "monitoring started" record (flags 0xFFFF, no
stop), then the events, in the same file; the unit calls in after each
event and monitoring resumes as a new session, so the first session's end
is not written anywhere -- it lies between its last event's stop and the
next start
* a histogram session is a "monitoring started" record at T, then a histogram
record from T+1 s to the stop, carrying the stop reason
Times are the unit's own clock. When it steps back an hour after daylight
saving ends, a session starts before the previous one stopped: that is a clock
step, never a negative gap. Sessions are built in start order, but an event
always joins the "monitoring started" record of its own file, so a call-in on
the step day cannot move an event into the wrong session.
Every session and call-in names the records and files it rests on, so a shot
report can attach the original .MLG (GET /db/mlg_files/{id}).
"""
from __future__ import annotations
import datetime
import json
from dataclasses import dataclass
from typing import Optional
from minimateplus.event_file_io import monitor_log_description
_STARTED = 0xFFFF
_RECORDED = 0x0001
_HISTOGRAM_SOURCE = 0x0400
_JOIN_SECONDS = 2 # a histogram record starts 1 s after its "started" record
_GAP_MEANING = {
"Modem Exit": "call-in",
"Timer Stop": "scheduled off",
"Battery Low Exit": "lost power",
"Keyboard Exit": "stopped by a person",
"Remote Exit": "stopped by a person",
"Memory Full Exit": "memory full",
}
# A call-in takes minutes (BE12844 2, BE8081 5, measured). A longer gap after a
# Modem Exit, with no call-in file missing, is a unit that did not restart (BE6907
# for 14 days from 2026-10-07; BE8081 over Labor Day 2019).
_LONG_CALL_IN_MINUTES = 60
NO_RESTART = "no restart after a call-in"
# Each call-in file holds everything since the previous one and is numbered
# <serial><counter>. Records can be missing only where a number is: then the
# gap cannot say the unit was not monitoring.
RECORDS_MISSING = "records missing"
_MISSING_LISTED = 20
@dataclass
class _Rec:
id: str
file_id: str
start: datetime.datetime
stop: Optional[datetime.datetime]
flags: int
source: int
trigger_level: Optional[str]
seq: int
def _dt(value: Optional[str]) -> Optional[datetime.datetime]:
if not value:
return None
if value.endswith("Z"): # Python 3.10's fromisoformat rejects "Z"
value = value[:-1] + "+00:00"
return datetime.datetime.fromisoformat(value)
def _iso(value: Optional[datetime.datetime]) -> Optional[str]:
return value.isoformat() if value else None
def _ended_by(flags: int) -> Optional[str]:
return monitor_log_description(flags & ~_RECORDED & 0xFFFF).strip() or None
def _kind(r: _Rec) -> str:
if r.flags == _STARTED or r.stop is None:
return "start" # no stop: monitoring began here, its end is not known
if r.flags & _RECORDED:
return "histogram" if r.source == _HISTOGRAM_SOURCE else "event"
return "closed"
def _session(start, *, stop=None, ended_by=None, kind="monitoring", trigger_level=None) -> dict:
return {"start": start, "stop": stop, "end_after": None, "end_before": None,
"ended_by": ended_by, "kind": kind, "trigger_level": trigger_level,
"running_at_last_report": False, "events": [], "record_ids": [], "file_ids": []}
def _note(s: dict, r: _Rec) -> None:
s["record_ids"].append(r.id)
if r.file_id not in s["file_ids"]:
s["file_ids"].append(r.file_id)
def _event(r: _Rec) -> dict:
return {"start": r.start, "stop": r.stop, "trigger_source": r.source,
"trigger_level": r.trigger_level, "record_id": r.id,
"description": monitor_log_description(r.flags).strip()}
def _last_running_point(s: dict) -> datetime.datetime:
if s["events"]:
return s["events"][-1]["stop"] or s["events"][-1]["start"]
return s["start"]
def _sessions(recs: list[_Rec]) -> list[dict]:
sessions: list[dict] = []
pending: Optional[dict] = None # a session whose stop is not known yet
started_in_file: dict[str, dict] = {} # file id -> the session its latest start record opened
def close_pending(before: datetime.datetime) -> None:
nonlocal pending
if pending is not None:
pending["end_after"] = _last_running_point(pending)
pending["end_before"] = before
pending = None
def own_file_session(r: _Rec) -> Optional[dict]:
s = started_in_file.get(r.file_id)
if s is None or r.start < s["start"]:
return None
if s["stop"] is not None and r.start > s["stop"]:
return None
return s
for r in recs:
kind = _kind(r)
if kind == "start":
close_pending(r.start)
pending = _session(r.start, trigger_level=r.trigger_level)
_note(pending, r)
started_in_file[r.file_id] = pending
sessions.append(pending)
elif kind == "histogram":
if pending is not None and (r.start - pending["start"]).total_seconds() <= _JOIN_SECONDS:
pending.update(stop=r.stop, kind="histogram", ended_by=_ended_by(r.flags))
pending["trigger_level"] = pending["trigger_level"] or r.trigger_level
_note(pending, r)
pending = None
else:
close_pending(r.start)
s = _session(r.start, stop=r.stop, kind="histogram",
ended_by=_ended_by(r.flags), trigger_level=r.trigger_level)
_note(s, r)
sessions.append(s)
elif kind == "event":
own = own_file_session(r)
last = sessions[-1] if sessions else None
if own is not None:
own["events"].append(_event(r))
_note(own, r)
if own is pending:
if _ended_by(r.flags):
own.update(stop=r.stop, ended_by=_ended_by(r.flags))
pending = None
elif own["stop"] is None:
# A later session (another file) closed its window first: the
# unit's clock stepped back at the call-in after this event.
own["end_after"] = _last_running_point(own)
if own["end_before"] is not None and own["end_after"] > own["end_before"]:
own["end_before"] = None
elif last is not None and last["stop"] is not None and last["start"] <= r.start <= last["stop"]:
last["events"].append(_event(r))
_note(last, r)
elif pending is not None:
pending["events"].append(_event(r))
_note(pending, r)
if _ended_by(r.flags):
pending.update(stop=r.stop, ended_by=_ended_by(r.flags))
pending = None
else:
s = _session(r.start, trigger_level=r.trigger_level)
s["events"].append(_event(r))
_note(s, r)
if _ended_by(r.flags):
s.update(stop=r.stop, ended_by=_ended_by(r.flags))
else:
pending = s
sessions.append(s)
else:
close_pending(r.start)
s = _session(r.start, stop=r.stop, ended_by=_ended_by(r.flags),
trigger_level=r.trigger_level)
_note(s, r)
sessions.append(s)
if pending is not None:
pending["running_at_last_report"] = True
pending["end_after"] = _last_running_point(pending)
return sessions
def _counter(file_name: str, serial: Optional[str]) -> Optional[int]:
"""The call-in number in <serial><counter>.MLG; a bare <serial>.MLG is 0."""
stem = file_name[:-4] if file_name.upper().endswith(".MLG") else file_name
if not serial or not stem.upper().startswith(serial.upper()):
return None
rest = stem[len(serial):]
if rest == "":
return 0
return int(rest) if rest.isdigit() else None
def _missing_between(a: Optional[int], b: Optional[int], received: set[int]) -> list[int]:
if a is None or b is None or b <= a + 1:
return []
return [c for c in range(a + 1, b) if c not in received][:_MISSING_LISTED]
def _gaps_and_steps(sessions: list[dict], counter_of: dict[str, Optional[int]],
received: set[int]) -> tuple[list[dict], list[dict]]:
gaps, steps = [], []
for prev, nxt in zip(sessions, sessions[1:]):
end = prev["stop"] or prev["end_after"]
minutes = (nxt["start"] - end).total_seconds() / 60
if nxt["start"] < end:
steps.append({"previous_stop": end, "next_start": nxt["start"], "minutes": minutes})
continue
missing = _missing_between(counter_of.get(prev["file_ids"][-1]),
counter_of.get(nxt["file_ids"][0]), received)
meaning = _GAP_MEANING.get(prev["ended_by"], "unknown")
if missing:
meaning = RECORDS_MISSING
elif meaning == "call-in" and minutes > _LONG_CALL_IN_MINUTES:
meaning = NO_RESTART
gaps.append({"start": end, "stop": nxt["start"], "minutes": minutes, "meaning": meaning,
"missing_files": missing})
return gaps, steps
def _call_ins(files: list[dict]) -> list[dict]:
"""From each file's own call summary, written when it arrived (a record
stored once may have come first in another file)."""
out = []
for f in files:
if not f["call_in"]:
continue
base = {"file_name": f["file_name"], "file_id": f["id"]}
file_time = _iso(_dt(f["file_mtime"] or f["received_at"]))
if not f["record_count"]:
out.append({"kind": "nothing_new", "unit_time": None, "file_time": file_time, **base})
continue
for stop in json.loads(f["no_file_stops"] or "[]"):
out.append({"kind": "no_file", "unit_time": stop, "file_time": None, **base})
out.append({"kind": "delivered", "unit_time": f["last_stop"], "file_time": file_time, **base})
return out
def build_timeline(records: list[dict], files: list[dict]) -> dict:
"""Sessions, gaps (with what each means), clock steps and call-ins."""
recs = sorted(
(_Rec(r["id"], r["file_id"], _dt(r["start_time"]), _dt(r["stop_time"]), r["flags"],
r["trigger_source"], r["trigger_level"], r["seq"]) for r in records),
key=lambda r: (r.start, 0 if r.flags == _STARTED else 1, r.seq),
)
sessions = _sessions(recs)
counter_of = {f["id"]: _counter(f["file_name"], f["serial"]) for f in files if f["call_in"]}
received = {c for c in counter_of.values() if c is not None}
gaps, steps = _gaps_and_steps(sessions, counter_of, received)
for s in sessions:
for key in ("start", "stop", "end_after", "end_before"):
s[key] = _iso(s[key])
for e in s["events"]:
e["start"], e["stop"] = _iso(e["start"]), _iso(e["stop"])
for g in gaps:
g["start"], g["stop"] = _iso(g["start"]), _iso(g["stop"])
for c in steps:
c["previous_stop"], c["next_start"] = _iso(c["previous_stop"]), _iso(c["next_start"])
return {"sessions": sessions, "gaps": gaps, "clock_steps": steps, "call_ins": _call_ins(files)}
def window(timeline: dict, from_dt: Optional[datetime.datetime],
to_dt: Optional[datetime.datetime]) -> dict:
"""The parts of a timeline that overlap [from_dt, to_dt] (the unit's clock).
Sessions, gaps and clock steps are on the unit's clock and filter exactly.
A call-in with a unit time filters by it. A nothing_new call-in has only
the PC's file time (UTC); it is kept when within a day of the window, since
the unit's local clock and UTC differ by hours and cannot be compared
exactly."""
lo = from_dt or datetime.datetime.min
hi = to_dt or datetime.datetime.max
def overlaps(start: Optional[str], end: Optional[str]) -> bool:
s = _dt(start) or datetime.datetime.min
e = _dt(end) or datetime.datetime.max
return s <= hi and e >= lo
def call_in_kept(c: dict) -> bool:
if c["unit_time"]:
return lo <= _dt(c["unit_time"]) <= hi
if not c["file_time"]:
return True
t = _dt(c["file_time"]).replace(tzinfo=None)
day = datetime.timedelta(days=1)
return (lo == datetime.datetime.min or t >= lo - day) and (hi == datetime.datetime.max or t <= hi + day)
return {
"sessions": [s for s in timeline["sessions"]
if overlaps(s["start"], None if s["running_at_last_report"]
else s["stop"] or s["end_before"])],
"gaps": [g for g in timeline["gaps"] if overlaps(g["start"], g["stop"])],
"clock_steps": [c for c in timeline["clock_steps"] if overlaps(c["next_start"], c["previous_stop"])],
"call_ins": [c for c in timeline["call_ins"] if call_in_kept(c)],
}
def monitoring_at(timeline: dict, at: datetime.datetime) -> dict:
"""Was the unit monitoring at `at` (its own clock)?
monitoring: inside a session (boundaries included); two sessions matching
(the repeated hour after a clock step back) set ambiguous. unknown: inside
a session's unrecorded end, after its last report, where a call-in file is
missing (records missing), or where no record reaches.
not_monitoring: inside a gap, with what the gap means."""
result = {"status": "unknown", "ambiguous": False, "sessions": [], "gap": None,
"trigger_level": None, "reason": "no record covers this time"}
matches = []
for s in timeline["sessions"]:
start, end = _dt(s["start"]), _dt(s["stop"]) or _dt(s["end_after"])
if start <= at <= end:
matches.append(s)
if matches:
result.update(status="monitoring", ambiguous=len(matches) > 1, sessions=matches,
trigger_level=matches[0]["trigger_level"], reason="inside a monitoring session")
return result
for s in timeline["sessions"]:
if s["stop"] is not None or _dt(s["end_after"]) >= at:
continue
if s["running_at_last_report"]:
result.update(sessions=[s], reason="after the unit's last report")
return result
if s["end_before"] is not None and at < _dt(s["end_before"]):
result.update(sessions=[s], reason="the session's end was not recorded")
return result
for g in timeline["gaps"]:
if _dt(g["start"]) < at < _dt(g["stop"]):
if g["meaning"] == RECORDS_MISSING:
result.update(gap=g, reason="call-in file(s) not received: "
+ ", ".join(f"#{c}" for c in g["missing_files"]))
else:
result.update(status="not_monitoring", gap=g, reason=g["meaning"])
return result
return result
+115 -1
View File
@@ -43,6 +43,7 @@ or:
from __future__ import annotations
import datetime
import json
import logging
import socket
import sys
@@ -54,7 +55,7 @@ from typing import Any, Dict, Mapping, Optional
# FastAPI / Pydantic
try:
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
from fastapi import Body, FastAPI, File, Form, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
@@ -84,6 +85,8 @@ from sfm.live_cache import LiveCache as _LiveCache
from sfm.waveform_store import WaveformStore
from sfm import db_snapshot
from sfm.event_ingest import backfill_series3_event, persist_download
from sfm.mlg_ingest import ingest_mlg
from sfm.mlg_timeline import build_timeline, monitoring_at as mlg_monitoring_at, window as mlg_window
import dataclasses
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
from sfm.device_access.errors import BadRequest, ChangeUnconfirmed
@@ -3067,6 +3070,117 @@ async def db_import_idf_file(
return {"count": len(results), "results": results}
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────────
# Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §5.
# Record and timeline times are the unit's own local clock; file times are UTC.
def _parse_unit_time(value: Optional[str], name: str, *, required: bool = False) -> Optional[datetime.datetime]:
"""A time on the unit's own clock: ISO-8601 with no UTC offset. 400 otherwise."""
if not value:
if required:
raise HTTPException(400, f"{name} is required (ISO-8601, the unit's clock)")
return None
try:
parsed = datetime.datetime.fromisoformat(value)
except ValueError:
raise HTTPException(400, f"{name} is not an ISO-8601 time: {value!r}")
if parsed.tzinfo is not None:
raise HTTPException(400, f"{name} is on the unit's own clock and carries no UTC offset: {value!r}")
return parsed
def _mlg_timeline(serial: str) -> dict:
db = _get_db()
return build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
@app.post("/db/import/mlg_file")
async def db_import_mlg_file(
files: list[UploadFile] = File(...),
serial: Optional[str] = Query(None, description="Serial hint, used only for a file with no serial inside (an empty one)"),
call_in: bool = Query(True, description="False for a cable / direct download: its records are kept, but it is not a call-in"),
mtimes: Optional[str] = Form(None, description='Each file\'s modified time: JSON {"<file name>": <unix seconds, UTC>}'),
) -> dict:
"""
Multipart upload of one or more Blastware .MLG monitor logs.
Each file gets its own status ("ok" / "duplicate" / "error"); good files
are stored even when another in the same request is not. A file that is
not whole, or any of whose records fails its checksum, stores nothing.
The original is kept byte for byte in the waveform store.
"""
try: # all of it checked before any file is stored
raw_times = json.loads(mtimes) if mtimes else {}
if not isinstance(raw_times, dict):
raise ValueError("not an object")
file_times = {name: datetime.datetime.fromtimestamp(float(stamp), datetime.timezone.utc)
for name, stamp in raw_times.items()}
except (ValueError, TypeError, OverflowError, OSError) as exc:
raise HTTPException(400, f"mtimes must be a JSON object of file name -> unix seconds: {exc}")
db, store = _get_db(), _get_store()
results: list[dict] = []
for upload in files:
name = upload.filename or "unnamed.MLG"
try:
data = await upload.read()
except Exception as exc:
results.append({"filename": name, "status": "error", "detail": f"read failed: {exc}"})
continue
results.append(ingest_mlg(db, store, name, data, serial_hint=serial,
file_mtime=file_times.get(name), call_in=call_in))
return {"count": len(results), "results": results}
@app.get("/db/units/{serial}/timeline")
def db_unit_timeline(
serial: str,
from_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
to_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
) -> dict:
"""A unit's monitoring timeline from its .MLGs: sessions (how each ended,
its events, its trigger level), gaps and what each means, clock steps, and
call-ins (delivered / no_file / nothing_new)."""
lo, hi = _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt")
timeline = _mlg_timeline(serial)
if lo or hi:
timeline = mlg_window(timeline, lo, hi)
return {"serial": serial, **timeline}
@app.get("/db/units/{serial}/monitoring_at")
def db_unit_monitoring_at(
serial: str,
at: str = Query(..., description="ISO-8601, the unit's clock"),
) -> dict:
"""Was the unit monitoring at `at`? monitoring / not_monitoring / unknown,
with the session or gap that says so and the trigger level as logged."""
when = _parse_unit_time(at, "at", required=True)
return {"serial": serial, "at": at, **mlg_monitoring_at(_mlg_timeline(serial), when)}
@app.get("/db/mlg_records")
def db_mlg_records(
serial: str = Query(..., description="Unit serial"),
from_dt: Optional[str] = Query(None, description="ISO-8601 start (record start, inclusive)"),
to_dt: Optional[str] = Query(None, description="ISO-8601 end (record start, inclusive)"),
) -> dict:
"""A unit's raw .MLG records, oldest first."""
rows = _get_db().query_mlg_records(
serial, _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt"))
return {"count": len(rows), "records": rows}
@app.get("/db/mlg_files/{file_id}")
def db_mlg_file(file_id: str):
"""The original .MLG, byte for byte, for printing or opening in Blastware."""
row = _get_db().get_mlg_file(file_id)
path = _get_store().root / row["stored_path"] if row and row["stored_path"] else None
if path is None or not path.is_file():
raise HTTPException(404, f"no stored .MLG with id {file_id}")
return FileResponse(path, filename=row["file_name"], media_type="application/octet-stream")
@app.get("/db/units/{serial}/waveforms.zip")
def db_unit_waveforms_zip(
serial: str,
+20
View File
@@ -30,6 +30,7 @@ Roles:
from __future__ import annotations
import datetime
import hashlib
import logging
import pickle
import re
@@ -105,6 +106,25 @@ class WaveformStore:
d.mkdir(parents=True, exist_ok=True)
return d
def save_mlg(self, serial: Optional[str], file_name: str, data: bytes) -> str:
"""Keep an original .MLG byte for byte, at <serial or _unresolved>/mlg/<file_name>.
Blastware reuses some names (a cable download is always <serial>.MLG), so
a name already holding different bytes gets the hash in its name instead.
Returns the path relative to the store root. Raises ValueError for a
serial that is not plain letters and digits (it becomes a directory)."""
if serial is not None and not re.fullmatch(r"[A-Za-z0-9]{1,16}", serial):
raise ValueError(f"not a plain serial: {serial!r}")
d = self.root / (serial or "_unresolved") / "mlg"
d.mkdir(parents=True, exist_ok=True)
path = d / Path(file_name).name
if path.exists() and path.read_bytes() != data:
digest = hashlib.sha256(data).hexdigest()[:8]
path = d / f"{path.stem}.{digest}{path.suffix}"
if not path.exists():
path.write_bytes(data)
return path.relative_to(self.root).as_posix()
def paths_for(self, serial: str, filename: str) -> tuple[Path, Path]:
"""Return (blastware_path, a5_pickle_path) for a given serial+filename.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+58
View File
@@ -0,0 +1,58 @@
"""
Tests for scripts/import_mlg_dir.py — bulk import of a directory of .MLGs (spec §7).
"""
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from scripts.import_mlg_dir import main
from sfm.database import SeismoDb
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
def _counts(text: str) -> dict:
return {k: int(v) for k, v in (line.split() for line in text.strip().splitlines())}
def test_import_dir_counts(tmp_path, capsys):
src = tmp_path / "in" / "nested"
shutil.copytree(FIX, src)
db_path, store = tmp_path / "t.db", tmp_path / "store"
args = [str(tmp_path / "in"), "--db-path", str(db_path), "--store-root", str(store)]
assert main(args + ["--dry-run"]) == 0
dry = _counts(capsys.readouterr().out)
assert (dry["files"], dry["error"], dry["empty"]) == (16, 0, 3)
assert not db_path.exists() and not store.exists()
assert main(args) == 0
first = _counts(capsys.readouterr().out)
assert (first["files"], first["ok"], first["error"], first["empty"], first["unresolved"]) == (16, 16, 0, 3, 0)
assert first["skipped"] == 3 # BE115292.MLG repeats BE11529.MLG's records
assert [f["file_name"] for f in SeismoDb(db_path).query_mlg_files("BE6907")] == [
"BE6907750.MLG", "BE6907751.MLG", "BE6907899.MLG", "BE6907900.MLG",
"BE6907901.MLG", "BE6907902.MLG"]
assert main(args) == 0
again = _counts(capsys.readouterr().out)
assert (again["duplicate"], again["ok"], again["inserted"]) == (16, 0, 0)
def test_empty_files_are_resolved_whatever_the_folder_order(tmp_path, capsys):
"""The empty file sorts first by name and by time here; the two-pass order still
gives it its unit."""
d = tmp_path / "in"
d.mkdir()
shutil.copy2(FIX / "BE6907751.MLG", d / "BE6907751.MLG")
shutil.copy2(FIX / "BE6907750.MLG", d / "BE6907750.MLG")
os.utime(d / "BE6907751.MLG", (1_700_000_000, 1_700_000_000)) # older than its real file
os.utime(d / "BE6907750.MLG", (1_800_000_000, 1_800_000_000))
assert main([str(d), "--db-path", str(tmp_path / "t.db"), "--store-root", str(tmp_path / "s")]) == 0
assert _counts(capsys.readouterr().out)["unresolved"] == 0
+130
View File
@@ -0,0 +1,130 @@
"""
Tests for minimateplus/mlg_file.py — Blastware's monitor log (.MLG) reader and writer.
Fixtures (tests/fixtures/mlg-11-9-26/) are real files: DL2's ACH folder
(BE12844, BE6907 from 2026; BE8081 from 2018-19) and three bench files.
Expected values come from an independent scratch parser that was checked
against DL2's event-file footers (785 / 785 BE8081 records matched by stop,
flag word and trigger source), never from the code under test. Format:
docs/instantel_protocol_reference.md D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
"""
from __future__ import annotations
import datetime
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.crc import crc16_aug_ccitt
from minimateplus.mlg_file import MlgFormatError, mlg_bytes, parse_mlg, read_mlg, write_mlg
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
dt = datetime.datetime
def test_crc_matches_the_micromate_rule():
from micromate.setup_block import _crc16_aug_ccitt
assert crc16_aug_ccitt(b"123456789") == _crc16_aug_ccitt(b"123456789") == 0xE5CC
def test_every_fixture_record_passes_its_checksum():
files = sorted(FIX.glob("*.MLG"))
assert len(files) == 16
for p in files:
assert parse_mlg(p.read_bytes()).crc_failures == [], p.name
def test_closed_records():
m = read_mlg(FIX / "BE128443065.MLG")
assert m.serial == "BE12844" and len(m.records) == 2
r1, r2 = m.records
assert (r1.index, r1.start, r1.stop, r1.flags, r1.trigger_source) == (
1, dt(2026, 9, 5, 18, 47, 26), dt(2026, 9, 5, 20, 0, 0), 0x0010, 0)
assert r1.description == "Timer Stop"
assert r1.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert r1.serial == "BE12844"
assert (r2.start, r2.stop, r2.description) == (
dt(2026, 9, 6, 6, 0, 13), dt(2026, 9, 6, 18, 45, 0), "Modem Exit")
def test_monitoring_started_and_an_event():
m = read_mlg(FIX / "BE128443067.MLG")
start, ev = m.records[1], m.records[2]
assert start.is_start and start.stop is None
assert start.description == "Monitoring started"
assert start.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (ev.flags, ev.trigger_source, ev.description) == (0x0001, 0x0001, "Event Recorded")
assert ev.event_time == dt(2026, 9, 8, 13, 38, 22)
assert ev.text == "Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s"
assert ev.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
def test_histogram_with_a_waveform_event():
r = read_mlg(FIX / "BE8081.MLG").records
assert (r[1].flags, r[1].trigger_source, r[1].description) == (
0x0021, 0x0400, "Event Recorded Modem Exit")
assert r[1].trigger_level == "Histogram"
assert (r[2].trigger_source, r[2].trigger_level) == (0x0002, "Geo: 0.300 in/s")
def test_trigger_level_with_or_without_a_space_before_the_colon():
a = read_mlg(FIX / "BE11529.MLG").records[0]
b = read_mlg(FIX / "BE115292.MLG").records[0]
assert a.text == "Trigger Level: Histogram" and b.text == "Trigger Level : Histogram"
assert a.trigger_level == b.trigger_level == "Histogram"
def test_empty_file():
m = read_mlg(FIX / "BE6907751.MLG")
assert m.serial is None and m.records == [] and m.empty
def test_a_flipped_byte_fails_only_its_record():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF # inside record 1's text
m = parse_mlg(bytes(data))
assert m.crc_failures == [1]
assert m.records[0].crc_ok is False and m.records[1].crc_ok is True
def test_a_flipped_byte_in_the_header_record_is_reported():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 100] ^= 0xFF # inside the header record's zero area
assert parse_mlg(bytes(data)).crc_failures == [0]
@pytest.mark.parametrize("mangle", [
lambda d: d[:-1], # not 18 + 292·n
lambda d: b"\x00" + d[1:], # wrong prefix
lambda d: d[:18] + b"\x23" + d[19:], # header length field not 290
lambda d: d[:6], # shorter than the prefix
], ids=["not-whole", "prefix", "length-field", "short"])
def test_structure_errors_raise(mangle):
with pytest.raises(MlgFormatError):
parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes()))
# ── Writer ────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("name", sorted(p.name for p in FIX.glob("*.MLG")))
def test_rebuilds_every_fixture_byte_for_byte(name):
raw = (FIX / name).read_bytes()
assert mlg_bytes(parse_mlg(raw)) == raw
def test_write_mlg_writes_the_same_bytes(tmp_path):
raw = (FIX / "BE8081321.MLG").read_bytes()
out = tmp_path / "BE8081321.MLG"
write_mlg(parse_mlg(raw), out)
assert out.read_bytes() == raw
def test_old_mlg_code_is_gone():
import minimateplus.blastware_file as bw
assert not hasattr(bw, "read_mlg") and not hasattr(bw, "MLG_FLAGS_TRIGGER")
+126
View File
@@ -0,0 +1,126 @@
"""
Tests for sfm/mlg_ingest.py — one .MLG in: verified, its serial resolved, the
original kept, its records stored once (spec §3, §5, §6).
"""
from __future__ import annotations
import datetime
import os
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg, resolve_serial
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
def _env(tmp_path):
return SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "waveforms")
def _ingest(db, store, name, data=None, **kw):
return ingest_mlg(db, store, name, data if data is not None else (FIX / name).read_bytes(), **kw)
def test_ingest_ok(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE128443067.MLG")
assert (res["status"], res["serial"], res["records"], res["inserted"], res["skipped"]) == (
"ok", "BE12844", 3, 3, 0)
assert res["empty"] is False and res["serial_unresolved"] is False and res["file_id"]
assert (store.root / "BE12844" / "mlg" / "BE128443067.MLG").read_bytes() == (
FIX / "BE128443067.MLG").read_bytes()
def test_ingest_twice_is_duplicate(tmp_path):
db, store = _env(tmp_path)
_ingest(db, store, "BE128443067.MLG")
res = _ingest(db, store, "BE128443067.MLG")
assert res["status"] == "duplicate" and res["inserted"] == 0
assert len(db.query_mlg_files("BE12844")) == 1
def test_corrupted_file_stores_nothing(tmp_path):
db, store = _env(tmp_path)
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF
res = _ingest(db, store, "BE128443065.MLG", bytes(data))
assert res["status"] == "error" and "record 1" in res["detail"]
assert db.query_mlg_files("BE12844") == [] and db.query_mlg_records("BE12844") == []
assert not list(store.root.rglob("mlg"))
def test_truncated_file_is_an_error(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE128443065.MLG", (FIX / "BE128443065.MLG").read_bytes()[:-5])
assert res["status"] == "error" and "not an MLG" in res["detail"]
assert not list(store.root.rglob("mlg"))
def test_empty_file_takes_known_serial(tmp_path):
db, store = _env(tmp_path)
_ingest(db, store, "BE6907750.MLG")
res = _ingest(db, store, "BE6907751.MLG")
assert (res["status"], res["serial"], res["empty"], res["serial_unresolved"]) == (
"ok", "BE6907", True, False)
assert (store.root / "BE6907" / "mlg" / "BE6907751.MLG").exists()
def test_empty_file_without_known_serial_is_unresolved(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE6907751.MLG")
assert (res["status"], res["serial"], res["serial_unresolved"]) == ("ok", None, True)
assert (store.root / "_unresolved" / "mlg" / "BE6907751.MLG").exists()
def test_empty_file_takes_the_serial_hint(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE6907751.MLG", serial_hint="BE6907")
assert (res["serial"], res["serial_unresolved"]) == ("BE6907", False)
def test_empty_file_takes_the_longest_known_serial():
assert resolve_serial("BE11010304.MLG", None, None, {"BE1101", "BE11010"}) == "BE11010"
assert resolve_serial("XY123.MLG", None, None, {"BE1101"}) is None
assert resolve_serial("BE6907751.MLG", "BE12844", "BE6907", {"BE6907"}) == "BE12844"
assert resolve_serial("be6907751.mlg", None, None, {"BE6907"}) == "BE6907"
assert resolve_serial("BE6907X51.MLG", None, None, {"BE6907"}) is None # not digits after
def test_file_mtime_and_call_in_are_stored(tmp_path):
db, store = _env(tmp_path)
mtime = datetime.datetime(2026, 9, 6, 22, 46, tzinfo=UTC)
res = _ingest(db, store, "BE128443065.MLG", file_mtime=mtime, call_in=False)
f = db.get_mlg_file(res["file_id"])
assert (f["file_mtime"], f["call_in"]) == ("2026-09-06T22:46:00+00:00", 0)
def test_a_serial_that_is_not_a_plain_serial_is_refused(tmp_path):
from minimateplus.mlg_file import mlg_bytes, parse_mlg
db, store = _env(tmp_path)
good = parse_mlg((FIX / "BE128443065.MLG").read_bytes())
for r in good.records:
r.serial = "../hdr"
bad = mlg_bytes(type(good)(serial="../hdr", records=good.records))
res = _ingest(db, store, "BE128443065.MLG", bad)
assert res["status"] == "error" and "serial" in res["detail"]
res = _ingest(db, store, "BE6907751.MLG", serial_hint="../escaped")
assert res["status"] == "error" and "serial" in res["detail"]
assert not (tmp_path / "hdr").exists() and not (tmp_path / "escaped").exists()
assert not list(tmp_path.rglob("*.MLG"))
def test_records_with_no_serial_are_refused_not_dropped(tmp_path):
from minimateplus.mlg_file import mlg_bytes, parse_mlg
db, store = _env(tmp_path)
m = parse_mlg((FIX / "BE128443065.MLG").read_bytes())
for r in m.records:
r.serial = ""
res = _ingest(db, store, "XX0001.MLG", mlg_bytes(type(m)(serial="", records=m.records)))
assert res["status"] == "error" and "serial" in res["detail"]
+131
View File
@@ -0,0 +1,131 @@
"""
Tests for the .MLG routes in sfm/server.py (spec §5).
httpx is not installed in this venv, so starlette's TestClient tests skip; these
call the route functions directly, passing every parameter (a FastAPI Query()
default is not a value).
"""
from __future__ import annotations
import asyncio
import io
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fastapi import HTTPException, UploadFile
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
def _env(tmp_path, monkeypatch):
import sfm.server as srv
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "waveforms")
monkeypatch.setattr(srv, "_db", db, raising=False)
monkeypatch.setattr(srv, "_store", store, raising=False)
return srv, db, store
def _import(srv, uploads, *, serial=None, call_in=True, mtimes=None):
files = [UploadFile(file=io.BytesIO(data), filename=name) for name, data in uploads]
return asyncio.run(srv.db_import_mlg_file(files=files, serial=serial, call_in=call_in, mtimes=mtimes))
def _fixture(name):
return name, (FIX / name).read_bytes()
def test_import_route_stores_good_file_and_refuses_bad_one(tmp_path, monkeypatch):
srv, db, store = _env(tmp_path, monkeypatch)
name, good = _fixture("BE128443065.MLG")
bad = bytearray(good)
bad[18 + 292 + 40] ^= 0xFF
out = _import(srv, [(name, good), ("BE128443099.MLG", bytes(bad))])
assert out["count"] == 2
assert [r["status"] for r in out["results"]] == ["ok", "error"]
assert "record 1" in out["results"][1]["detail"]
assert [f["file_name"] for f in db.query_mlg_files("BE12844")] == ["BE128443065.MLG"]
assert sorted(p.name for p in store.root.rglob("*.MLG")) == ["BE128443065.MLG"]
def test_import_route_reads_mtimes(tmp_path, monkeypatch):
srv, db, _ = _env(tmp_path, monkeypatch)
out = _import(srv, [_fixture("BE128443065.MLG")], mtimes='{"BE128443065.MLG": 1788734760}')
f = db.get_mlg_file(out["results"][0]["file_id"])
assert f["file_mtime"] == "2026-09-06T22:46:00+00:00"
def test_import_route_rejects_bad_mtimes(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
with pytest.raises(HTTPException) as exc:
_import(srv, [_fixture("BE128443065.MLG")], mtimes="not json")
assert exc.value.status_code == 400
def test_timeline_and_monitoring_at_routes(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
_import(srv, [_fixture("BE8081321.MLG")])
tl = srv.db_unit_timeline(serial="BE8081", from_dt=None, to_dt=None)
assert tl["serial"] == "BE8081" and len(tl["sessions"]) == 4
windowed = srv.db_unit_timeline(serial="BE8081", from_dt="2019-04-13T00:00:00", to_dt=None)
assert [s["start"] for s in windowed["sessions"]] == [
"2019-04-12T18:38:14", "2019-04-13T07:05:15", "2019-04-15T12:47:05"]
assert [g["meaning"] for g in windowed["gaps"]] == ["call-in", "lost power"]
m = srv.db_unit_monitoring_at(serial="BE8081", at="2019-04-14T12:00:00")
assert m["serial"] == "BE8081" and m["status"] == "not_monitoring"
with pytest.raises(HTTPException) as exc:
srv.db_unit_monitoring_at(serial="BE8081", at="yesterday")
assert exc.value.status_code == 400
def test_timeline_routes_for_unknown_serial(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
tl = srv.db_unit_timeline(serial="BE0000", from_dt=None, to_dt=None)
assert (tl["sessions"], tl["gaps"], tl["call_ins"], tl["clock_steps"]) == ([], [], [], [])
assert srv.db_unit_monitoring_at(serial="BE0000", at="2026-09-08T10:00:00")["status"] == "unknown"
def test_mlg_records_route(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
_import(srv, [_fixture("BE8081321.MLG")])
out = srv.db_mlg_records(serial="BE8081", from_dt=None, to_dt=None)
assert out["count"] == 6 and out["records"][0]["start_time"] == "2019-04-12T17:17:59"
def test_mlg_file_route_returns_original_bytes(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
name, data = _fixture("BE8081321.MLG")
file_id = _import(srv, [(name, data)])["results"][0]["file_id"]
resp = srv.db_mlg_file(file_id=file_id)
assert Path(resp.path).read_bytes() == data and resp.filename == name
with pytest.raises(HTTPException) as exc:
srv.db_mlg_file(file_id="no-such-id")
assert exc.value.status_code == 404
def test_times_with_an_offset_or_empty_are_400(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
for at in ("2019-04-14T12:00:00Z", "2019-04-14T12:00:00+00:00", ""):
with pytest.raises(HTTPException) as exc:
srv.db_unit_monitoring_at(serial="BE8081", at=at)
assert exc.value.status_code == 400, at
with pytest.raises(HTTPException) as exc:
srv.db_mlg_records(serial="BE8081", from_dt="2019-04-14T12:00:00Z", to_dt=None)
assert exc.value.status_code == 400
def test_bad_mtime_values_are_refused_before_anything_is_stored(tmp_path, monkeypatch):
srv, db, _ = _env(tmp_path, monkeypatch)
with pytest.raises(HTTPException) as exc:
_import(srv, [_fixture("BE128443065.MLG"), _fixture("BE128443067.MLG")],
mtimes='{"BE128443067.MLG": "noon"}')
assert exc.value.status_code == 400
assert db.query_mlg_files("BE12844") == []
+94
View File
@@ -0,0 +1,94 @@
"""
Tests for .MLG storage: SeismoDb's mlg_files / mlg_records tables and
WaveformStore.save_mlg (spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3).
"""
from __future__ import annotations
import datetime
import hashlib
import os
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.mlg_file import read_mlg
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
def _insert(db: SeismoDb, name: str, *, as_name: str | None = None, call_in: bool = True):
raw = (FIX / name).read_bytes()
mlg = read_mlg(FIX / name)
return db.insert_mlg(
serial=mlg.serial, file_name=as_name or name, sha256=hashlib.sha256(raw).hexdigest(),
size=len(raw), empty=mlg.empty, call_in=call_in,
file_mtime=datetime.datetime(2026, 9, 8, 17, 39, 52, tzinfo=UTC),
stored_path=f"{mlg.serial}/mlg/{as_name or name}", records=mlg.records,
)
def test_insert_and_query_round_trip(tmp_path):
db = SeismoDb(tmp_path / "t.db")
file_id, inserted, skipped = _insert(db, "BE128443067.MLG")
assert file_id and (inserted, skipped) == (3, 0)
rows = db.query_mlg_records("BE12844")
assert [r["start_time"] for r in rows] == [
"2026-09-07T18:47:27", "2026-09-08T06:00:13", "2026-09-08T13:38:22"]
assert rows[1]["stop_time"] is None and rows[1]["flags"] == 0xFFFF
assert (rows[2]["trigger_source"], rows[2]["event_time"], rows[2]["seq"]) == (
1, "2026-09-08T13:38:22", 3)
assert rows[2]["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert {r["file_id"] for r in rows} == {file_id}
f = db.get_mlg_file(file_id)
assert (f["file_name"], f["record_count"], f["empty"], f["call_in"]) == ("BE128443067.MLG", 3, 0, 1)
assert f["file_mtime"] == "2026-09-08T17:39:52+00:00"
assert [x["id"] for x in db.query_mlg_files("BE12844")] == [file_id]
def test_same_file_twice_is_a_duplicate(tmp_path):
db = SeismoDb(tmp_path / "t.db")
_insert(db, "BE128443067.MLG")
assert _insert(db, "BE128443067.MLG") == (None, 0, 0)
assert len(db.query_mlg_files("BE12844")) == 1
raw = (FIX / "BE128443067.MLG").read_bytes()
assert db.mlg_file_exists("BE128443067.MLG", hashlib.sha256(raw).hexdigest())
assert not db.mlg_file_exists("BE128443067.MLG", "0" * 64)
def test_open_record_is_stored_once(tmp_path):
db = SeismoDb(tmp_path / "t.db")
_insert(db, "BE128443067.MLG")
file_id, inserted, skipped = _insert(db, "BE128443067.MLG", as_name="BE12844.MLG", call_in=False)
assert file_id and (inserted, skipped) == (0, 3)
assert len(db.query_mlg_records("BE12844")) == 3
def test_records_differing_only_in_text_are_the_same_record(tmp_path):
db = SeismoDb(tmp_path / "t.db")
assert _insert(db, "BE11529.MLG")[1:] == (3, 0)
file_id, inserted, skipped = _insert(db, "BE115292.MLG")
assert file_id and (inserted, skipped) == (0, 3)
def test_known_serials(tmp_path):
db = SeismoDb(tmp_path / "t.db")
assert db.known_serials() == set()
_insert(db, "BE128443067.MLG")
_insert(db, "BE8081.MLG")
assert db.known_serials() == {"BE12844", "BE8081"}
def test_save_mlg_keeps_both_when_names_collide(tmp_path):
store = WaveformStore(tmp_path / "waveforms")
a = store.save_mlg("BE11529", "BE11529.MLG", b"one")
assert a == "BE11529/mlg/BE11529.MLG"
assert store.save_mlg("BE11529", "BE11529.MLG", b"one") == a # same bytes: reused
b = store.save_mlg("BE11529", "BE11529.MLG", b"two")
assert b != a and b.startswith("BE11529/mlg/BE11529.") and b.endswith(".MLG")
assert (store.root / a).read_bytes() == b"one" and (store.root / b).read_bytes() == b"two"
assert store.save_mlg(None, "BE6907751.MLG", b"x") == "_unresolved/mlg/BE6907751.MLG"
+261
View File
@@ -0,0 +1,261 @@
"""
Tests for sfm/mlg_timeline.py — a unit's monitoring timeline from its .MLG
records, and "was it monitoring at T" (spec §4).
Each case is a real file; the expected sessions were read off the records by
hand (docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md,
"How a session appears").
"""
from __future__ import annotations
import datetime
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg
from sfm.mlg_timeline import build_timeline, monitoring_at
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
dt = datetime.datetime
BASE = dt(2026, 1, 1, tzinfo=UTC)
def _timeline(tmp_path, serial, *names):
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "w")
for i, name in enumerate(names):
res = ingest_mlg(db, store, name, (FIX / name).read_bytes(),
file_mtime=BASE + datetime.timedelta(hours=i))
assert res["status"] == "ok", res
return build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
def test_sessions_gaps_and_an_event_session(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443067.MLG", "BE128443068.MLG")
s = tl["sessions"]
assert len(s) == 3
assert (s[0]["start"], s[0]["stop"], s[0]["ended_by"], s[0]["kind"]) == (
"2026-09-07T18:47:27", "2026-09-07T20:00:00", "Timer Stop", "monitoring")
assert s[0]["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (s[1]["start"], s[1]["stop"], s[1]["end_after"], s[1]["end_before"]) == (
"2026-09-08T06:00:13", None, "2026-09-08T13:38:25", "2026-09-08T13:41:16")
assert s[1]["running_at_last_report"] is False
assert [(e["start"], e["stop"], e["trigger_source"]) for e in s[1]["events"]] == [
("2026-09-08T13:38:22", "2026-09-08T13:38:25", 1)]
assert (s[2]["start"], s[2]["stop"], s[2]["ended_by"]) == (
"2026-09-08T13:41:16", "2026-09-08T18:45:00", "Modem Exit")
g = tl["gaps"]
assert [(x["start"], x["stop"], x["meaning"]) for x in g] == [
("2026-09-07T20:00:00", "2026-09-08T06:00:13", "scheduled off"),
("2026-09-08T13:38:25", "2026-09-08T13:41:16", "unknown")]
assert g[0]["minutes"] == pytest.approx(600.217, abs=0.01)
assert g[1]["minutes"] == pytest.approx(2.85, abs=0.01)
assert tl["clock_steps"] == []
def test_monitoring_at(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443067.MLG", "BE128443068.MLG")
m = monitoring_at(tl, dt(2026, 9, 8, 10, 0))
assert (m["status"], m["ambiguous"], len(m["sessions"])) == ("monitoring", False, 1)
assert m["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert monitoring_at(tl, dt(2026, 9, 8, 13, 38, 0))["status"] == "monitoring"
assert monitoring_at(tl, dt(2026, 9, 8, 13, 40, 0))["status"] == "unknown"
off = monitoring_at(tl, dt(2026, 9, 7, 23, 0))
assert off["status"] == "not_monitoring" and off["gap"]["meaning"] == "scheduled off"
assert monitoring_at(tl, dt(2027, 1, 1))["status"] == "unknown"
assert monitoring_at(tl, dt(2026, 1, 1))["status"] == "unknown"
def test_monitoring_at_boundaries_are_inclusive(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443067.MLG", "BE128443068.MLG")
for at in (dt(2026, 9, 7, 18, 47, 27), dt(2026, 9, 7, 20, 0, 0), dt(2026, 9, 8, 6, 0, 13)):
assert monitoring_at(tl, at)["status"] == "monitoring", at
def test_clock_step_back_is_not_a_negative_gap(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443155.MLG", "BE128443156.MLG")
assert [s["start"] for s in tl["sessions"]] == [
"2026-10-31T18:47:28", "2026-11-01T06:00:13", "2026-11-01T17:47:25"]
assert all(g["minutes"] >= 0 for g in tl["gaps"])
assert [g["meaning"] for g in tl["gaps"]] == ["scheduled off"]
(step,) = tl["clock_steps"]
assert (step["previous_stop"], step["next_start"]) == ("2026-11-01T18:45:00", "2026-11-01T17:47:25")
assert step["minutes"] == pytest.approx(-57.583, abs=0.01)
m = monitoring_at(tl, dt(2026, 11, 1, 18, 0))
assert (m["status"], m["ambiguous"], len(m["sessions"])) == ("monitoring", True, 2)
def test_weekend_battery_outage_and_missed_calls(tmp_path):
tl = _timeline(tmp_path, "BE8081", "BE8081321.MLG")
s = tl["sessions"]
assert [x["start"] for x in s] == [
"2019-04-12T17:17:59", "2019-04-12T18:38:14", "2019-04-13T07:05:15", "2019-04-15T12:47:05"]
assert [x["kind"] for x in s] == ["histogram"] * 4
assert [x["ended_by"] for x in s] == ["Modem Exit", "Modem Exit", "Battery Low Exit", "Modem Exit"]
assert s[0]["stop"] == "2019-04-12T18:33:00"
g = tl["gaps"]
assert [x["meaning"] for x in g] == ["call-in", "call-in", "lost power"]
assert [x["minutes"] for x in g] == pytest.approx([5.233, 5.233, 2999.833], abs=0.01)
assert [{k: v for k, v in c.items() if k != "file_id"} for c in tl["call_ins"]] == [
{"kind": "no_file", "unit_time": "2019-04-12T18:33:00", "file_time": None,
"file_name": "BE8081321.MLG"},
{"kind": "no_file", "unit_time": "2019-04-13T07:00:01", "file_time": None,
"file_name": "BE8081321.MLG"},
{"kind": "delivered", "unit_time": "2019-04-15T17:15:00",
"file_time": "2026-01-01T00:00:00+00:00", "file_name": "BE8081321.MLG"},
]
m = monitoring_at(tl, dt(2019, 4, 14, 12, 0))
assert m["status"] == "not_monitoring" and m["gap"]["meaning"] == "lost power"
def test_histogram_session_keeps_its_waveform_event(tmp_path):
tl = _timeline(tmp_path, "BE8081", "BE8081.MLG")
(s,) = tl["sessions"]
assert (s["start"], s["stop"], s["kind"], s["trigger_level"], s["ended_by"]) == (
"2018-02-16T15:15:31", "2018-02-16T15:15:49", "histogram", "Histogram", "Modem Exit")
(e,) = s["events"]
assert (e["start"], e["trigger_source"], e["trigger_level"]) == (
"2018-02-16T15:15:47", 2, "Geo: 0.300 in/s")
def test_event_with_an_end_bit_inside_a_histogram(tmp_path):
tl = _timeline(tmp_path, "BE9441", "BE94412.MLG")
s = tl["sessions"]
assert [(x["start"], x["stop"], x["ended_by"], x["kind"]) for x in s] == [
("2026-10-26T16:06:34", "2026-10-26T16:07:21", "Keyboard Exit", "histogram"),
("2026-10-26T17:00:36", "2026-10-26T18:53:53", "Remote Exit", "histogram")]
assert [e["description"] for e in s[0]["events"]] == ["Event Recorded Memory Full Exit"]
assert [g["meaning"] for g in tl["gaps"]] == ["stopped by a person"]
def test_call_in_kinds(tmp_path):
tl = _timeline(tmp_path, "BE6907", "BE6907750.MLG", "BE6907751.MLG")
assert [(c["kind"], c["unit_time"], c["file_name"]) for c in tl["call_ins"]] == [
("no_file", "2026-08-22T18:30:00", "BE6907750.MLG"),
("delivered", "2026-08-23T18:30:00", "BE6907750.MLG"),
("nothing_new", None, "BE6907751.MLG")]
def test_no_data_gives_an_empty_timeline():
tl = build_timeline([], [])
assert tl == {"sessions": [], "gaps": [], "clock_steps": [], "call_ins": []}
assert monitoring_at(tl, dt(2026, 9, 8))["status"] == "unknown"
def test_window_filters_call_ins_by_unit_time_and_empty_files_by_file_time(tmp_path):
from sfm.mlg_timeline import window
tl = _timeline(tmp_path, "BE6907", "BE6907750.MLG", "BE6907751.MLG") # files at BASE, BASE+1h (UTC)
late = window(tl, dt(2026, 8, 23), None)
assert [(c["kind"], c["unit_time"]) for c in late["call_ins"]] == [("delivered", "2026-08-23T18:30:00")]
around_file = window(tl, dt(2025, 12, 31), dt(2026, 1, 2))
assert [c["kind"] for c in around_file["call_ins"]] == ["nothing_new"]
assert window(tl, None, None)["call_ins"] == tl["call_ins"]
# ── Final-review fixes ────────────────────────────────────────────────────────
from minimateplus.mlg_file import mlg_bytes
from minimateplus.models import MlgFile, MlgRecord
def _rec(index, start, stop, flags, src=0, serial="BE12844"):
return MlgRecord(index=index, start=start, stop=stop, flags=flags, trigger_source=src,
serial=serial, text_raw=b"Geo: 0.0500 in/s".ljust(254, b"\x00"))
def _ingest_bytes(tmp_path, serial, files):
"""files: [(name, bytes, call_in)] in arrival order."""
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "w")
for i, (name, data, call_in) in enumerate(files):
res = ingest_mlg(db, store, name, data, call_in=call_in,
file_mtime=BASE + datetime.timedelta(hours=i))
assert res["status"] == "ok", res
return db, build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
def test_windowed_timeline_without_file_mtime(tmp_path):
from sfm.mlg_timeline import window
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "w")
for name in ("BE6907750.MLG", "BE6907751.MLG"):
ingest_mlg(db, store, name, (FIX / name).read_bytes()) # no file_mtime
tl = build_timeline(db.query_mlg_records("BE6907"), db.query_mlg_files("BE6907"))
assert all(c["file_time"] is None or c["file_time"].endswith("+00:00") for c in tl["call_ins"])
out = window(tl, dt(2026, 8, 1), None)
assert [c["kind"] for c in out["call_ins"]][:2] == ["no_file", "delivered"]
def test_event_triggered_call_on_the_clock_step_day(tmp_path):
a = mlg_bytes(MlgFile("BE12844", [_rec(1, dt(2026, 11, 1, 6, 0, 13), None, 0xFFFF),
_rec(2, dt(2026, 11, 1, 13, 38, 22), dt(2026, 11, 1, 13, 38, 25), 0x0001, 1)]))
b = mlg_bytes(MlgFile("BE12844", [_rec(1, dt(2026, 11, 1, 12, 41, 16), dt(2026, 11, 1, 18, 45), 0x0020)]))
_, tl = _ingest_bytes(tmp_path, "BE12844", [("BE128449001.MLG", a, True), ("BE128449002.MLG", b, True)])
first = tl["sessions"][0]
assert first["start"] == "2026-11-01T06:00:13" and len(first["events"]) == 1
assert tl["sessions"][1]["events"] == []
(step,) = tl["clock_steps"]
assert (step["previous_stop"], step["next_start"]) == ("2026-11-01T13:38:25", "2026-11-01T12:41:16")
assert tl["gaps"] == []
assert monitoring_at(tl, dt(2026, 11, 1, 10, 0))["status"] == "monitoring"
def test_call_in_whose_records_came_first_in_a_cable_download(tmp_path):
files = [("BE11529.MLG", (FIX / "BE11529.MLG").read_bytes(), False),
("BE115292.MLG", (FIX / "BE115292.MLG").read_bytes(), True)]
_, tl = _ingest_bytes(tmp_path, "BE11529", files)
assert [(c["kind"], c["unit_time"], c["file_name"]) for c in tl["call_ins"]] == [
("delivered", "2026-04-22T21:06:57", "BE115292.MLG")]
def test_sessions_and_call_ins_carry_their_records_and_files(tmp_path):
db, tl = _ingest_bytes(tmp_path, "BE8081", [
("BE8081321.MLG", (FIX / "BE8081321.MLG").read_bytes(), True)])
(f,) = db.query_mlg_files("BE8081")
ids = {r["id"] for r in db.query_mlg_records("BE8081")}
for s in tl["sessions"]:
assert s["file_ids"] == [f["id"]] and s["record_ids"] and set(s["record_ids"]) <= ids
assert sum(len(s["record_ids"]) for s in tl["sessions"]) == 6
assert {c["file_id"] for c in tl["call_ins"]} == {f["id"]}
m = monitoring_at(tl, dt(2019, 4, 12, 18, 0))
assert m["sessions"][0]["file_ids"] == [f["id"]]
def test_a_record_without_a_stop_does_not_break_the_timeline(tmp_path):
a = mlg_bytes(MlgFile("BE12844", [_rec(1, dt(2026, 9, 1, 6, 0), None, 0x0020)]))
_, tl = _ingest_bytes(tmp_path, "BE12844", [("BE128449003.MLG", a, True)])
assert monitoring_at(tl, dt(2026, 9, 1, 12, 0))["status"] == "unknown"
def test_a_missing_call_in_file_is_unknown_not_not_monitoring(tmp_path):
# #3066 and #3067 are not imported: the records of 09-06 18:47 to 09-08 13:38 are missing.
_, tl = _ingest_bytes(tmp_path, "BE12844", [
("BE128443065.MLG", (FIX / "BE128443065.MLG").read_bytes(), True),
("BE128443068.MLG", (FIX / "BE128443068.MLG").read_bytes(), True)])
(gap,) = tl["gaps"][-1:]
assert gap["start"] == "2026-09-06T18:45:00" and gap["meaning"] == "records missing"
assert gap["missing_files"] == [3066, 3067]
assert monitoring_at(tl, dt(2026, 9, 7, 12, 0))["status"] == "unknown"
# a real call-in gap (2 minutes) still reads as one
_, tl2 = _ingest_bytes(tmp_path / "b", "BE12844", [
("BE128443067.MLG", (FIX / "BE128443067.MLG").read_bytes(), True),
("BE128443068.MLG", (FIX / "BE128443068.MLG").read_bytes(), True)])
assert monitoring_at(tl2, dt(2026, 9, 8, 13, 40))["status"] == "unknown"
def test_a_unit_that_did_not_restart_after_a_call_in_was_not_monitoring(tmp_path):
# BE6907, real files #899-#902: no number is missing (#900, #901 are its usual empty
# call-ins), yet nothing was recorded from the 10-07 18:30 call-in until 10-21 11:42.
names = ["BE6907899.MLG", "BE6907900.MLG", "BE6907901.MLG", "BE6907902.MLG"]
_, tl = _ingest_bytes(tmp_path, "BE6907", [(n, (FIX / n).read_bytes(), True) for n in names])
gap = next(g for g in tl["gaps"] if g["start"] == "2026-10-07T18:30:00")
assert gap["stop"] == "2026-10-21T11:42:43" and gap["meaning"] == "no restart after a call-in"
assert gap["missing_files"] == []
m = monitoring_at(tl, dt(2026, 10, 14, 12, 0))
assert m["status"] == "not_monitoring" and m["gap"]["meaning"] == "no restart after a call-in"