Compare commits

...
10 Commits
98 changed files with 584666 additions and 752 deletions
+92 -15
View File
@@ -1,12 +1,14 @@
# Wireless M-Bus C1 Repeater — Heltec WiFi LoRa 32 V4.3 (RF feasibility experiment) # Wireless M-Bus C1/T1 Repeater — Heltec WiFi LoRa 32 V4.3 (RF feasibility experiment)
Experimental firmware and hardware-in-the-loop test rig answering one Experimental firmware and hardware-in-the-loop test rig answering one
question: **can the SX1262 + KCT8103L front-end on the Heltec V4.3 serve as question: **can the SX1262 + KCT8103L front-end on the Heltec V4.3 serve as
the basis for a Wireless M-Bus gateway/repeater?** the basis for a Wireless M-Bus gateway/repeater?**
Short answer: yes for RX and TX at the PHY level. It receives real C1 Short answer: yes for RX and TX at the PHY level, in both C1 and T1.
meter telegrams, retransmits them bit-exact after a configurable delay, and It receives C1/T1 meter telegrams and retransmits eligible OMS uplinks after
returns to RX reliably. Quantitative limits and caveats are below. a configurable delay, setting the standard hop bit and repairing the CRC
without decrypting the payload. T-mode frames are decoded (3-of-6 in software)
and re-aired in their native mode. Quantitative limits and caveats are below.
This is **not** a standards-compliant repeater. See This is **not** a standards-compliant repeater. See
[docs/STANDARDS_GAPS.md](docs/STANDARDS_GAPS.md). [docs/STANDARDS_GAPS.md](docs/STANDARDS_GAPS.md).
@@ -26,13 +28,28 @@ flake.nix ESP-IDF + rtl-sdr + rtl-wmbus + wmbusmeters + python env
## Quick start ## Quick start
### Flash firmware (Heltec only)
Connect the Heltec over USB and run from the repository root:
```bash
nix develop --command ./tools/flash.sh test
```
This builds the current local source and automatically discovers and flashes
the Heltec; no SDR is required. Use `debug` instead of `test` for verbose
diagnostics. Discovery refuses missing or ambiguous devices. If flashing
fails, the script rediscovers the USB port and retries once.
### Hardware-in-the-loop test (Heltec + SDR)
```bash ```bash
nix build .#hil-python -o result-py # once nix build .#hil-python -o result-py # once
nix develop --command ./hil/run.sh --duration 1200 nix develop --command ./hil/run.sh --duration 1200
``` ```
Exit code 0 = PASS. Artifacts land in `captures/<timestamp>-hil/` Exit code 0 = PASS. Artifacts land in `captures/<timestamp>-hil/`
(`report.txt`, `report.json`, `serial.log`, `rtlwmbus.log`, `iq_proof.txt`). (`report.txt`, `report.json`, `serial.log`, `rtlwmbus.log`, `rf_proof.json`).
Serial console (scriptable, JSON output): Serial console (scriptable, JSON output):
@@ -41,6 +58,59 @@ Serial console (scriptable, JSON output):
# full command list: docs/TESTING.md # full command list: docs/TESTING.md
``` ```
## Phone dashboard (2026-09-09)
Short-press PRG to the OLED **WLAN-DIAGNOSE** page, then hold ~1.5 s to
enable the password-protected access point. The OLED shows the SSID,
password and `http://192.168.4.1`. The next page displays a Wi-Fi join QR
code; scan it with a phone, then open the address. The 64-pixel-high OLED
requires a small QR: text credentials remain available if the camera
cannot focus. Choose **stay connected** if the phone warns about no internet.
No app, router, internet connection or captive portal is required.
The OLED and browser UI are in German. Tap a **?** beside a term for a
short beginner-friendly explanation; no mouse hover is required.
The latest signals come first; **Diagnose: Summen und Funkstatus** and
**Optional: eigene Namen für Zähler** expand only when needed. Help panels
close with **Schließen**, the same **?**, an outside tap or Escape. They
remain open while the history refreshes.
- Wi-Fi is **off after every reboot**. Hold on either Wi-Fi page to disable
it. OLED blanking does not stop Wi-Fi. A random per-device password is
generated once and retained in NVS; it is not printed to serial.
- The dashboard shows 256 recent final reception/repeat outcomes,
CRC and decode rejections, deliberate policy skips, TX errors, RSSI,
C1/T1 mode, timing, radio health and rolling-hour duty usage. Synthetic
test/beacon transmissions are identified separately.
- **TX completed means the radio reported completion, not downstream
delivery.** Frames never detected by the Heltec cannot appear in history.
Dashboard counters cover the current boot and are unaffected by
`clear_stats`; history rolls off in RAM and is lost on reboot.
- Import an optional two-column `oms_id,label` CSV, or download a template
and export observed IDs. IDs remain eight-character strings, including
leading zeros. Labels stay only in the browser tab's memory; refresh
clears them. They are never uploaded or saved.
- Manufacturer names and device types are interpreted in offline JavaScript
from the link-layer header. Names use a bundled DLMS FLAG registry.
This is not meter-model/driver detection or encrypted-reading decoding.
Corrupt identities are untrusted; ambiguous IDs retain full raw identity
details. Labels never conceal the original ID.
- **Einstellungen am Heltec-Gerät ändern** exposes all ten existing settings:
forwarding, delay, duty budget, TX power, whitelist, beacon interval,
synthetic L-field, verbose serial output, FEM-CSD and preamble detection.
Expert controls are collapsed. Every field requires its own **Übernehmen**;
loading values never silently discards another unsent draft.
- Only delay and duty budget persist across reboots. A revision check rejects
stale writes; compare the current device value before explicitly resubmitting.
Accepted settings are copied by the radio task at a processing boundary.
TX-power/preamble changes can briefly interrupt reception for reinitialization.
- Disabling the duty guard or raising it above 1000 ppm requires confirmation,
not a new permission to exceed regulatory limits. **Heltec-WLAN ausschalten**
also requires confirmation; reconnecting afterward requires the OLED.
Anyone with access to the WPA2 AP can change settings. The same-origin/CSRF
checks prevent cross-site browser writes, not access by other joined clients.
Details and verification limits: [docs/TESTING.md](docs/TESTING.md).
## Results (measured, not inferred) ## Results (measured, not inferred)
Representative 1200 s run, `captures/2026-09-01T10-34-24-hil`: Representative 1200 s run, `captures/2026-09-01T10-34-24-hil`:
@@ -51,7 +121,7 @@ Representative 1200 s run, `captures/2026-09-01T10-34-24-hil`:
| SDR-classified originals | 129 (44 meters) | | SDR-classified originals | 129 (44 meters) |
| Heltec matched SDR originals | 47 (36.4 %) | | Heltec matched SDR originals | 47 (36.4 %) |
| Heltec TX attempts / success | 72 / 72 (100 %) | | Heltec TX attempts / success | 72 / 72 (100 %) |
| TX events RF-confirmed in IQ | 5 / 5 in the IQ window (100 %) | | TX RF confirmation | withdrawn for this run: measured with the borrow-prone aligner (see caveats) |
| Firmware repeat delay (set 200 ms) | 200.001 ms min/median, 200.008 ms max | | Firmware repeat delay (set 200 ms) | 200.001 ms min/median, 200.008 ms max |
| Radio recoveries / MCU resets | 0 / 0 | | Radio recoveries / MCU resets | 0 / 0 |
@@ -64,8 +134,10 @@ Key hardware findings:
and drops visible meters from 18 to 1. No overload penalty from maximum and drops visible meters from 18 to 1. No overload penalty from maximum
front-end gain at this site. front-end gain at this site.
[docs/RF_FRONTEND_TESTS.md](docs/RF_FRONTEND_TESTS.md) [docs/RF_FRONTEND_TESTS.md](docs/RF_FRONTEND_TESTS.md)
- **Repeats are bit-exact**: 63/63 logged TX payloads equalled the received - **Historical bit-exact baseline**: 63/63 logged TX payloads equalled the
raw frame plus C-mode bytes. received raw frame plus C-mode bytes. Since 2026-09-09, received repeats
intentionally differ only in the OMS hop bit and affected CRC; see
[implementation notes](docs/STANDARDS_GAPS.md#oms-hop-marking-2026-09-09).
- **RX deaf time is ~225.7 ms** per repeat at a 200 ms delay, including a - **RX deaf time is ~225.7 ms** per repeat at a 200 ms delay, including a
12.2 ms fixed-capture tail imposed by the SX1262 packet engine. 12.2 ms fixed-capture tail imposed by the SX1262 packet engine.
[docs/TIMING.md](docs/TIMING.md) [docs/TIMING.md](docs/TIMING.md)
@@ -93,12 +165,17 @@ rtl-wmbus receives our repeat with 1-2 byte errors and fails CRC. Repeats
are therefore verified two ways that are immune to this: are therefore verified two ways that are immune to this:
- synthetic C1 bursts prove the framing is decodable as C1 (`verify_tx.py`); - synthetic C1 bursts prove the framing is decodable as C1 (`verify_tx.py`);
- firmware TX timestamps are aligned to bursts in raw IQ to prove real - `hil/meter_anchored.py` fits the serial<->IQ clock on strong meter
repeats radiate with the right timing and airtime receptions only (a TX-fitted clock can lock at -repeat_delay and match
(`verify_repeats_iq.py`). every repeat to its own original -- that bug produced withdrawn results),
then requires event-correlated FSK spectral excess against nearby non-TX
control windows before reporting `rf_state` strong/weak.
Closing the remaining gap needs physical antenna separation or an inline An earlier RF-alignment tool (`verify_repeats_iq.py`) had exactly that
attenuator, which is not scriptable from the host. clock-borrowing flaw and was removed; historical "N/N TX confirmed in IQ"
numbers from it are withdrawn (docs/FINDINGS.md). Closing the remaining
decode gap needs physical antenna separation or an inline attenuator,
which is not scriptable from the host.
## Documentation ## Documentation
@@ -113,5 +190,5 @@ attenuator, which is not scriptable from the host.
- [TESTING.md](docs/TESTING.md) — how to run things, known pitfalls - [TESTING.md](docs/TESTING.md) — how to run things, known pitfalls
- [DEVBOARD_REQUIREMENTS.md](docs/DEVBOARD_REQUIREMENTS.md) + - [DEVBOARD_REQUIREMENTS.md](docs/DEVBOARD_REQUIREMENTS.md) +
[devboard_signals.csv](docs/devboard_signals.csv) — future PCB needs [devboard_signals.csv](docs/devboard_signals.csv) — future PCB needs
- [FUTURE_UI.md](docs/FUTURE_UI.md) — design note: OLED + button for local - [FUTURE_UI.md](docs/FUTURE_UI.md) — OLED + button local UI: design,
feedback (not implemented; display is untouched by this firmware) constraints, and implementation notes (implemented in firmware/main/ui.c)
+161 -62
View File
@@ -5,18 +5,40 @@ the development bench to a real site. Goal: run the repeater standalone
(no USB host) and verify it over RF alone. This log records what happened, (no USB host) and verify it over RF alone. This log records what happened,
because the sequence of wrong theories is itself a finding. because the sequence of wrong theories is itself a finding.
## Final correction (same date, after source and IQ audit)
The late-evening conclusion that the board had an intermittent TX-chain
hardware fault is **withdrawn**. Two software/methodology faults explain
the evidence:
1. The `pa_low` diagnostic used SetPaConfig
`(0x01,0x00,0x00,0x01)`. Its PA-duty and hpMax bytes came from the
SX1261 +10 dBm row, but `deviceSel=0x00` still selected SX1262. This
undocumented hybrid is not a low SX1262 row. Same-capture A/B testing
against valid SX1262 `(0x02,0x02,0x00,0x01)` measured about 32 dB more RF.
2. The beacon verdict called RF absent from total energy alone. Spectral
reanalysis of the canonical “dead” IQ capture finds weak but repeated
FSK at all 25 TX times: median +1.5 dB over floor versus +0.2 dB in
nearby controls, with +7.6 dB FSK-selective excess.
After deleting the invalid PA row, a flashed-firmware smoke test produced
9/9 beacons at median +27.81 dB over floor (range +27.02..+27.90), nearby
controls +0.00 dB, and +40.73 dB FSK-selective excess at configured
-9 dBm. This report retains the earlier narrative as a chronology of
misdiagnosis; the final conclusions are in the corrected section below.
## Timeline of evidence ## Timeline of evidence
| Setup | LED (TxDone) | RF at SDR | Verdict at the time | | Setup | LED (TxDone) | RF at SDR | Verdict at the time |
|---|---|---|---| |---|---|---|---|
| Laptop USB, board on table (~16:07) | double-blinks | **7/7 TX clock-aligned, median +37 dB over floor** | baseline: transmits | | Laptop USB, board on table (~16:07) | double-blinks | reported 7/7 at +37 dB; later invalidated | baseline claim came from the repeat-borrowing clock-fit bug |
| Power bank (USB-C, then USB-A) | went dark after seconds | none | bank auto-off at ~60 mA idle load | | Power bank (USB-C, then USB-A) | went dark after seconds | none | bank auto-off at ~60 mA idle load |
| UGREEN 100 W GaN wall charger, C-to-C | double-blinks "sometimes" | none in 4 captures (~8 min) | *wrongly* blamed supply sag | | UGREEN 100 W GaN wall charger, C-to-C | double-blinks "sometimes" | none in 4 captures (~8 min) | *wrongly* blamed supply sag |
| LiPo pack attached | blinks, 2-4 double-pulses/90 s | none | supply theory started cracking | | LiPo pack attached | blinks, 2-4 double-pulses/90 s | none | supply theory started cracking |
| LiPo + dangling USB cable (no host) | ~9 double-pulses/90 s | none | RX rate recovered; TX still invisible | | LiPo + dangling USB cable (no host) | ~9 double-pulses/90 s | none | RX rate recovered; TX still invisible |
| Mid-capture unplug (laptop -> LiPo, position frozen) | blinks throughout | **none in either phase** | laptop connection alone does NOT explain it: power theories all dead | | Mid-capture unplug (laptop -> LiPo, position frozen) | blinks throughout | **none in either phase** | laptop connection alone does NOT explain it: power theories all dead |
| Wall power, board hanging free, no LiPo | blinks | none at prior SDR-antenna position | placement of the DUT alone is not it either | | Wall power, board hanging free, no LiPo | blinks | none at prior SDR-antenna position | placement of the DUT alone is not it either |
| **SDR antenna moved to ~20 cm from the hanging board** | blinks | **same-duration burst pairs at 50-54 ms: 10-10, 17-17, 16-16 ms** | repeater IS repeating standalone; radiated/received level is simply far lower than the laptop-connected reference | | **SDR antenna moved to ~20 cm from the hanging board** | blinks | **same-duration burst pairs at 50-54 ms: 10-10, 17-17, 16-16 ms** | standalone RF exists; comparison with the invalid laptop reference is unsupported |
## What was actually established ## What was actually established
@@ -24,23 +46,18 @@ because the sequence of wrong theories is itself a finding.
RX->50 ms->TX cycle runs (LED) and its repeats are observable at RF RX->50 ms->TX cycle runs (LED) and its repeats are observable at RF
(same-duration pairs at the configured delay) once the observer antenna (same-duration pairs at the configured delay) once the observer antenna
is close enough. is close enough.
2. **The laptop-connected "+37 dB at 50 cm" reference was not a pure 2. **The laptop-connected “+37 dB at 50 cm” reference was invalid.**
radiated-field measurement.** With the board on the host's USB, the The old clock fit could align each expected repeat to its original
cable shield and shared ground with the SDR dongle add counterpoise meter burst. It cannot establish a USB-cable counterpoise or conducted
and possibly conducted common-mode coupling. Standalone, at a similar coupling effect.
claimed distance, the same transmitter was invisible; at ~20 cm it shows 3. **No tested power source correlated with the weak RF.**
up at +14..+24 dB. The gap between those numbers is the combined effect - Power bank: real failure, but trivial (low-load auto-off). The LED
of geometry, orientation, antenna environment and the lost cable/ground identified it directly.
contribution -- not a firmware or supply fault. - Wall adapter and LiPo both showed chip-level TX with weak/invisible RF.
3. **Every power-source theory failed when tested properly.** - The frozen-position unplug run did not isolate a supply effect.
- Power bank: real failure, but trivial (auto-off). The LED found it These observations reject the original wall-adapter-sag theory, but
in one glance. “supply exonerated entirely” was stronger than the available evidence.
- Wall-adapter "sag during PA burst": WITHDRAWN. The adapter is a The later PA-row bug is sufficient to explain the large RF deficit.
100 W GaN unit, and the frozen-position unplug test showed the
laptop connection failing at the same spot too. The earlier
conviction (committed to FINDINGS.md at the time) was wrong.
- LiPo (stiffest possible rail): same invisibility -> supply exonerated
entirely.
4. **TxDone still proves nothing about radiated power.** The task spec's 4. **TxDone still proves nothing about radiated power.** The task spec's
warning (§36: "TX successful is not evidence") extends beyond FEM warning (§36: "TX successful is not evidence") extends beyond FEM
configuration to antenna geometry: the SX1262 completes its packet into configuration to antenna geometry: the SX1262 completes its packet into
@@ -62,59 +79,141 @@ because the sequence of wrong theories is itself a finding.
- **A conducted RF test port would have ended this in minutes.** Half a day - **A conducted RF test port would have ended this in minutes.** Half a day
of over-the-air inference replaced one attenuated SMA measurement. of over-the-air inference replaced one attenuated SMA measurement.
Already in devboard_signals.csv; priority upgraded. Already in devboard_signals.csv; priority upgraded.
- **Antenna system design is not optional polish.** The stock whip against - **The antenna conclusion was premature.** Geometry, orientation and
a tiny PCB ground radiates so poorly, and so directionally, that counterpoise always affect over-the-air measurements, but the invalid
deployment placement dominates link budget. The gateway needs a real SX1261-derived PA configuration was not controlled and accounts
antenna with a defined counterpoise, and the battery pack must be kept for about 32 dB by itself. A proper antenna A/B remains useful; this
mechanically away from the radiator. session did not quantify stock-whip efficiency.
- **On-device persistent telemetry (NVS counters, VBAT) is still the - **Persistent counters would improve, but not prove, RF diagnosis.** NVS
missing piece.** The LED collapsed "is it powered/alive/repeating" from RX/TxDone counters and VBAT would separate power, receive, and chip-TX
four SDR captures to one glance, but every RF question still required failures without a host. They still could not distinguish weak RF from a
the laptop. Retained counters would have separated "not receiving" from healthy radiated packet; that requires a conducted detector or external
"not transmitting" instantly. receiver.
- **LED patterns earned their place** and should carry to the gateway - **LED patterns earned their place** and should carry to the gateway
(with the FUTURE_UI.md caveat: an LED can only report chip state, never (with the FUTURE_UI.md caveat: an LED can only report chip state, never
radiated RF). radiated RF).
## Still open after this session ## Questions left by the afternoon run (status after audit)
- Clock-aligned close-antenna run (device on laptop serial + SDR antenna - RESOLVED for the attached-DUT method: meter-anchored event windows plus
at 20 cm) to attribute bursts per TX event and put a number on the spectral controls now attribute RF to each TX. Absolute standalone field
standalone radiated level. Protocol ready; not yet executed. strength is still uncalibrated.
- Quantify laptop-cable contribution: repeat the alignment run twice at - Quantify laptop-cable contribution: repeat the alignment run twice at
identical geometry, cable in vs out (LiPo), antenna close. identical geometry, cable in vs out (LiPo), antenna close.
- Proper antenna A/B (e.g. quarter-wave with radials vs stock whip) -- - Proper antenna A/B (e.g. quarter-wave with radials vs stock whip) --
directly relevant to the gateway RF architecture. directly relevant to the gateway RF architecture.
## Location 3 (evening session) -- the beacon, and the real fault ## Location 3 (evening session) — corrected beacon postmortem
Coordinating physical actions with an async agent kept failing (missed Beacon mode (`set beacon_period_ms N`) was the right instrument: it emits
timestamps, tuner deaths mid-capture), so we changed instruments: a known frames at known times without relying on meter traffic. The first
firmware **beacon mode** (`set beacon_period_ms N`) transmits a synthetic verdict applied the wrong detector to that data.
OMS frame (manufacturer SLN, ID 00000001, access_nr = sequence) every N ms.
No meter traffic, no serial coordination, dense uniform sampling.
The beacon caught what two days of repeat-chasing could not: ### What the retained IQ establishes
- **TX radiated power is intermittent at minute scale.** One 90 s window: - The historical capture
0/25 beacons produced ANY RF (max +0.5 dB over floor) while 27 ambient `captures/2026-09-01T17-35-12-beacon-diag` has a healthy observer:
meter frames in the same IQ showed median +26.8 dB (observer healthy) and 27/32 strong meter anchors, 0.7 ms median clock error, meter median
the chip reported TX_DONE, mode 6, device_errors 0 for every beacon. +26.8 dB.
Thirty minutes later, same boot, same config: repeats, test_tx and - Beacon windows are weak in total energy (median +1.5 dB; none reaches
beacons all radiated at a constant ~+10 dB. +6 dB), but their median spectrum contains the expected approximately
- RX stayed healthy through dead TX windows. Chip-side diagnostics are +/-45 kHz FSK energy. Relative to nearby non-TX controls, FSK-selective
identical in dead and live states. The fault therefore sits between the excess is +7.6 dB across 25 windows.
SX1262 PA output and the antenna: KCT8103L PA path (CPS/DIO2, CTX, PA - A known-live repeat capture
supply) or a mechanical/thermal TX-chain fault. Firmware cannot observe (`2026-09-01T17-41-21-repeat-pair-test`) classifies strong: 29/29 above
it -- exactly the RADIO_VDD_SENSE / conducted-test-port gap in +6 dB, median +10.9 dB, FSK-selective excess +18.8 dB.
docs/devboard_signals.csv. - Therefore “0/25 produced any RF” and “genuinely zero RF” were false.
- **Methodology bug found and fixed:** verify_repeats_iq's single-burst TxDone did not prove RF, but the retained spectrum does.
clock fit can lock at -repeat_delay and "confirm" every repeat with its
own original's burst. The "7/7 at +37 dB" laptop confirmations were this The soak's exact historical PA-row state cannot be reconstructed: serial
artifact. Trustworthy methods: structural same-duration pairs at the telemetry logged SetTxParams power but not the `pa_low` selection, and the
configured delay, content decodes (duplicate payloads), and old soak harness deleted IQ after reducing each segment to scalar energy.
hil/meter_anchored.py (clock fitted on strong meter receptions; ambient Its claimed +8 -> +6 -> zero thermal decay is consequently not auditable.
meter levels double as per-capture observer health). A board-level thermal/mechanical TX fault was never demonstrated.
- Positive control: with a healthy observer, 30 structural pairs at
137 ms and 35 duplicate decoded payloads in 90 s -- the repeater ### Source-level root cause
function itself is solid whenever the TX chain is in its live state.
The firmware's alleged low-power SX1262 PA row was copied from the wrong
line of Semtech table 13-21:
```
old diagnostic row: 01 00 00 01 undocumented SX1261-values/SX1262-select hybrid
fixed SX1262 row: 02 02 00 01 documented +14 dBm-optimal PA config
SetTxParams: -9 02 configured level -9 dBm, 40 us ramp
```
Same-stream A/B measurement found about 32 dB between the two rows. The
invalid path has been removed rather than retained as a diagnostic.
Configured SX1262 power is now limited to -9..+2 dBm; the default remains
-9 dBm because the external KCT8103L adds gain and absolute e.r.p. has not
been calibrated.
### Corrective verification
Flashed fixed firmware, 1.6 Msps SDR, fixed 0.9 dB tuner gain:
```
scheduled beacons 9/9 TxDone
RF envelope over floor +27.81 dB median (+27.02..+27.90)
nearby non-TX controls +0.00 dB median
FSK-selective excess +40.73 dB
SDR clipped samples 0.000 %
computed airtime accounting 24,480 us = 9 x 2,720 us
```
The detector also scored nine fake event times in an off interval at
-0.16 dB FSK excess, versus +40.73 dB for the real aligned events.
`hil/meter_anchored.py` now reports `rf_state=strong|weak|not_observed`
and requires event-correlated FSK spectral excess before claiming RF.
`hil/beacon_soak.sh` retains raw IQ for every weak, absent or unclassified
segment. Strong segments alone may be reduced to a JSON verdict.
The unrelated duty-cycle bug found during the audit is also fixed: the
384-event ring silently forgot airtime at high rates. A 61-minute bucket
ledger now retains every event overlapping the rolling hour, and duty
usage is computed from packet bits rather than SPI/polling latency.
## Where this leaves the project
1. The connected board demonstrably transmits correct FSK after the PA-row
fix. No intermittent board-level TX fault is currently established.
2. TxDone and the LED remain chip-level evidence only. RF conclusions need
the spectral detector or an independent receiver/decode.
3. Absolute radiated power and regulatory e.r.p. remain uncalibrated. Keep
the configured SX1262 level at -9 dBm until a conducted measurement or
calibrated field-strength setup exists.
4. The NESDR observer remains unreliable for long unattended work; its
per-capture health gate and anomaly-IQ retention are mandatory.
## Late evening — standalone battery test with fixed firmware: PASS
First deployment after the PA-row fix and the OLED/button UI. DUT on
battery, no USB host; all verification RF-only plus the on-device screen.
Capture: `captures/2026-09-01T22-22-32-standalone-battery` (360 s IQ at
42.1 dB gain, verdicts archived alongside).
- **Repeat function confirmed standalone** by two independent methods on
one stream: 3 decoded duplicate payloads, and 3 structural RF pairs with
matching durations (10-10, 7-7, 10-10 ms) at 53-54 ms gaps against the
50 ms default delay. The +3-4 ms is the radio-preparation offset between
TX-routine entry and RF onset (standby + packet params + buffer write),
consistent with `tx_operation_us` measurements.
- **Observer health control in-capture**: 46 C1 decodes from 38 unique
meters; floor +2.9 dB.
- **Counter funnel closed from the OLED alone** (no laptop): RX 292 =
VALID 100 + CRCFAIL 63 + NOT-C1 130 + LEN 0 (one frame arrived between
page reads). TX 109/109 at 100%. The 34% valid ratio matches the site
benchmark; CRC failures are the characterized long-encrypted-Techem
sensitivity edge, not a fault.
- **UI-driven beacon toggle verified end to end** earlier in the session:
an independent wmbusmeters receiver decoded beacon ID 00000001 with
valid CRC every ~3.3-3.5 s (3000 ms + scheduling drift) after a button
press, on battery. Beacon was off during this capture (0 beacon decodes,
no comb -- matches the TX counter arithmetic).
- The 44 railed ~+40 dB short bursts in the capture are our repeats PLUS
the fingerprinted neighbour meter's singles; only delay-and-duration
matched pairs were attributed to the repeater.
- Duty note for future runs: the 3000 ms button beacon consumes 907 of
1000 ppm; running it for long alongside repeats drives `DUTYBLK` up by
design. Toggle it off when measuring repeat behaviour.
+102 -44
View File
@@ -19,14 +19,15 @@
- TX proof of life: SDR decoded our synthetic C1 format-A frame as valid - TX proof of life: SDR decoded our synthetic C1 format-A frame as valid
(crc_ok=1, mfr 0x4D8E "SLN", ID 00000001) at configured -9 dBm, and the (crc_ok=1, mfr 0x4D8E "SLN", ID 00000001) at configured -9 dBm, and the
wM-Bus CRC blocks computed by firmware matched rtl_wmbus's checks. wM-Bus CRC blocks computed by firmware matched rtl_wmbus's checks.
- First real repeat observed: 100-byte Techem frame received, repeated - First real repeat observed: a 100-byte Techem frame was received and the
after 50.002 ms (configured 50 ms). firmware entered its TX routine 50.002 ms after the reconstructed frame
- Nooelec NESDR SMArt v5 R820T PLL wedges ("PLL not locked"), producing end (configured 50 ms). This timestamp precedes radio preparation; it is
gain-independent white noise on all frequencies until USB reset. not the exact on-air start time.
`usbreset 0bda:2838` reliably restores operation. Trigger correlated - The Nooelec NESDR SMArt v5 can enter gain-independent, railed-noise
with `rtl_test -t` direct-sampling probe. states until USB reset or physical replug. The tune-time
- rtl-sdr-blog and osmocom rtl_sdr builds behave identically w.r.t. the `[R82XX] PLL not locked!` message is benign and `rtl_test -t` was not the
wedge; not a driver-fork issue. cause. `hil/sdr_health.py` diagnoses the actual failure from gain response
and spectral structure.
- Real C1 traffic exists at this site: 8 meters in 10 min baseline - Real C1 traffic exists at this site: 8 meters in 10 min baseline
(docs/SDR_BASELINE.md); one strong plaintext meter (61471660), several (docs/SDR_BASELINE.md); one strong plaintext meter (61471660), several
marginal encrypted Techem meters. marginal encrypted Techem meters.
@@ -41,6 +42,18 @@
called) -> no notifications despite correct radio-side IRQ config. called) -> no notifications despite correct radio-side IRQ config.
3. `timeout bash -c "rtl_sdr | rtl_wmbus"` orphans the pipeline children 3. `timeout bash -c "rtl_sdr | rtl_wmbus"` orphans the pipeline children
on timeout (device stays claimed). Apply timeout to rtl_sdr directly. on timeout (device stays claimed). Apply timeout to rtl_sdr directly.
4. The `pa_low` diagnostic selected SetPaConfig
`(0x01,0x00,0x00,0x01)`, documented in code as a low SX1262 row. Its
first two parameters came from the SX1261 +10 dBm row, but
`deviceSel=0x00` selected SX1262, creating an undocumented hybrid.
Same-capture A/B testing showed about 32 dB less RF than the valid
SX1262 row `(0x02,0x02,0x00,0x01)`. Fix: remove the invalid row
and diagnostic toggle; always use a valid SX1262 row.
5. The rolling-hour duty ledger retained only 384 individual events. At
beacon rates it wrapped after about 2.7 s of airtime and silently
under-counted the hour. Fix: 61 keyed minute buckets retain all airtime
in the overlapping hour; host tests cover high event counts, expiry,
boundary overlap, and invalid timestamps.
## LIKELY ## LIKELY
@@ -61,20 +74,23 @@
docs/RF_FRONTEND_TESTS.md. docs/RF_FRONTEND_TESTS.md.
- Repeat payloads are byte-exact: 63/63 logged `tx_payload` values equalled - Repeat payloads are byte-exact: 63/63 logged `tx_payload` values equalled
mode bytes + the received raw frame. No corruption in the RX->TX path. mode bytes + the received raw frame. No corruption in the RX->TX path.
- Real repeats are emitted as correct RF: aligning firmware TX timestamps - Real repeats are emitted as correct RF: aligning firmware TX-operation
to bursts in the same stream's IQ confirmed 48 of 57 TX events (84 %), timestamps to bursts in the same stream's IQ confirmed 48 of 57 TX
with alignment error median 1.3 ms (max 3.6 ms) and burst duration within events (84 %), with alignment error median 1.3 ms (max 3.6 ms) and
0.5 ms (median) of the computed airtime. Firmware repeat delay measured burst duration within 0.5 ms (median) of computed airtime. Firmware
200.0 ms min/median/max against a 200 ms setting. entered the TX routine at 200.0 ms against a 200 ms setting; radio
preparation shifts actual RF onset later.
- Firmware TX reliability: 58/58 TX success over 600 s and 72/72 over - Firmware TX reliability: 58/58 TX success over 600 s and 72/72 over
1200 s; tx_timeout 0, tx_failures 0, radio recoveries 0, MCU resets 0. 1200 s; tx_timeout 0, tx_failures 0, radio recoveries 0, MCU resets 0.
- The KCT8103L RX path is essential: holding CSD low in RX costs ~41 dB of - The KCT8103L RX path is essential: holding CSD low in RX costs ~41 dB of
chip-referred level and drops the visible meter population from 18 to 1 chip-referred level and drops the visible meter population from 18 to 1
(600 s per arm, docs/RF_FRONTEND_TESTS.md). No evidence of excessive (600 s per arm, docs/RF_FRONTEND_TESTS.md). No evidence of excessive
front-end gain hurting at this site. front-end gain hurting at this site.
- Repeat-delay accuracy: +1 to +8 us against a 200 ms setting across 72 - Repeat-operation scheduling: +1 to +8 us against a 200 ms setting across
repeats. RX deaf time per repeat ~225.7 ms median, of which 12.2 ms is 72 repeats. This is accuracy at entry to the TX routine, not RF onset.
the fixed-255-byte RX tail and 13.4 ms the TX airtime (docs/TIMING.md). The historical 13.4 ms value called “TX airtime” was operation latency
through observed TxDone; computed channel occupancy was 8.8 ms for the
representative 102-byte radio payload (docs/TIMING.md).
- The SX1262 GFSK engine cannot express wM-Bus length semantics, so RX uses - The SX1262 GFSK engine cannot express wM-Bus length semantics, so RX uses
a fixed 255-byte capture; RxDone therefore fires 9.4-17.1 ms after the a fixed 255-byte capture; RxDone therefore fires 9.4-17.1 ms after the
real end of frame and the firmware reconstructs the true timestamp. real end of frame and the firmware reconstructs the true timestamp.
@@ -147,29 +163,38 @@
- Long-run stability at >=100 and >=500 verified repeat events. - Long-run stability at >=100 and >=500 verified repeat events.
- Early-stop RX (poll GetRxBufferStatus) to cut the ~20 ms deaf tail. - Early-stop RX (poll GetRxBufferStatus) to cut the ~20 ms deaf tail.
## Location 3 follow-up (2026-09-01 evening): intermittent TX RF death ## Location 3 follow-up (2026-09-01 evening): PA configuration postmortem
- CONFIRMED: the DUT's radiated TX output is intermittent on minute scales - **WITHDRAWN:** the conclusion that this board had an intermittent
-- genuinely zero (not weak) for >=10 min windows, then a stable ~+10 dB post-SX1262 hardware TX death. The canonical “0/25 beacons produced any
at the SDR. Verified with beacon mode against in-capture ambient-meter RF” capture was judged only by total energy in 1 ms windows. Reanalysis
controls (observer healthy: meters +26.8 dB median while 25/25 beacons of the retained IQ finds a repeatable event-correlated FSK signature:
produced <= +0.5 dB). RX unaffected; chip reports TX_DONE/mode 6/no TX median +1.5 dB over floor, nearby controls +0.2 dB, and FSK-selective
errors in both states => fault is post-chip (KCT8103L PA path or TX excess +7.6 dB across 25/25 windows. It was weak RF, not zero RF.
chain), invisible to firmware. Hardware follow-up required; strengthens - Root cause in firmware: the `pa_low` diagnostic combined the SX1261
the RADIO_VDD_SENSE and conducted-RF-test-port devboard requirements. +10 dBm PA-duty/hpMax values with SX1262 `deviceSel=0x00`:
- WITHDRAWN: every single-burst "TX aligned to IQ" confirmation (e.g. `(0x01,0x00,0x00,0x01)`. In a same-stream A/B test, documented SX1262
"7/7 at +37 dB", "33/41 at +19.3 dB"). verify_repeats_iq's clock fit on `(0x02,0x02,0x00,0x01)` raised the event envelope by about 32 dB. The
TX events can lock at -repeat_delay and match each repeat to its own invalid toggle and row are now deleted. Configured power
original's burst. Borrow-immune evidence only: structural same-duration is restricted to -9..+2 dBm; the external KCT8103L still follows.
pairs at the configured delay, duplicate content decodes, or - The old logs recorded configured SetTxParams power but not which PA row
hil/meter_anchored.py (meter-anchored clock, exact TX windows). the diagnostic had selected. Exact row state cannot be reconstructed for
- CONFIRMED: observer health must be judged per capture from ambient meter every old soak segment, and the old soak deleted each IQ file after its
levels inside the same IQ (meter median >= +15 dB over floor). The scalar verdict. Therefore its claimed +8 -> +6 -> zero thermal decay is
Nooelec went deaf mid-session again; runs without this control are void. not auditable and is not evidence of a board fault.
- CORRECTION to yesterday's "placement dominates": placement governs - Fixed-firmware RF smoke test at configured -9 dBm: 9/9 scheduled beacons,
whether PAIRS are detectable (originals must be SDR-visible), but the median +27.81 dB over floor (range +27.02..+27.90), nearby controls
standalone invisibility episodes are better explained by the intermittent +0.00 dB, FSK-selective excess +40.73 dB, and no ADC clipping at 0.9 dB
TX death now that it has been directly observed under controls. SDR gain. Firmware also reported 9/9 TxDone and exactly 24,480 us of
computed airtime (9 x 2,720 us).
- `hil/meter_anchored.py` now requires event-correlated FSK spectral excess
before calling RF present and reports `strong`, `weak`, or
`not_observed`. The historical weak capture classifies `weak`; a known
live repeat capture classifies `strong`. `hil/beacon_soak.sh` deletes IQ
only for `strong` segments and retains every anomaly.
- Observer health must still be judged per capture from ambient meter
levels. TxDone remains only chip-level evidence. Neither fact supports a
board-fault conclusion without the RF signature and retained raw IQ.
## Field test 2026-09-01 (onsite standalone deployment) ## Field test 2026-09-01 (onsite standalone deployment)
@@ -185,12 +210,14 @@ Full narrative with the evidence table: docs/FIELD_TEST_2026-09-01.md.
~20 cm of the free-hanging, wall-powered board, same-duration burst pairs ~20 cm of the free-hanging, wall-powered board, same-duration burst pairs
appeared at the 50 ms repeat delay (10-10, 17-17, 16-16 ms; received appeared at the 50 ms repeat delay (10-10, 17-17, 16-16 ms; received
+14..+24 dB over floor). +14..+24 dB over floor).
- CONFIRMED: the laptop-connected "+37 dB at ~50 cm" reference overstates - **WITHDRAWN:** the claimed laptop-connected “+37 dB at ~50 cm”
standalone radiated field -- the USB cable/host ground contributes reference and the inferred USB-cable/counterpoise delta. The +37 dB
counterpoise (and possibly conducted coupling into the shared-ground number came from the repeat-borrowing clock-fit bug, so it cannot support
dongle). Radiated performance is dominated by antenna geometry: a cable contribution estimate.
orientation, surroundings, and the LiPo pack's position relative to the - **NOT ESTABLISHED:** that the stock whip itself explains the weak
antenna. Placement, not power, ruled the day. standalone results. Antenna geometry unquestionably changes an
over-the-air measurement, but the invalid SX1261-derived PA configuration is sufficient to
explain a roughly 32 dB deficit and was not controlled in those runs.
- CONFIRMED: TxDone (and therefore the LED double-blink) proves chip-level - CONFIRMED: TxDone (and therefore the LED double-blink) proves chip-level
packet completion only. It is indistinguishable between a well-matched packet completion only. It is indistinguishable between a well-matched
antenna and a shadowed/mismatched one -- §36's lesson extended to antenna and a shadowed/mismatched one -- §36's lesson extended to
@@ -199,3 +226,34 @@ Full narrative with the evidence table: docs/FIELD_TEST_2026-09-01.md.
singletons", 23-24 ms trains at ~30 ms spacing) are a neighbouring meter singletons", 23-24 ms trains at ~30 ms spacing) are a neighbouring meter
railing the dongle: rate invariant across firmware versions, reboots and railing the dongle: rate invariant across firmware versions, reboots and
power sources. Excluded from pair detection by fingerprint. power sources. Excluded from pair detection by fingerprint.
## T-mode + long-frame support (2026-09-02)
- CONFIRMED: T1 transmit works end to end. Synthetic T1 frames (3-of-6
coded in software, 50 kHz TX deviation via lazy SetModulationParams
swap, same 0x543D sync) were decoded by rtl_wmbus as valid `T1;...`
telegrams, including a long L=140 frame (12 decode lines over 6
airings, `captures/2026-09-02T-t1-verify`).
- CONFIRMED: the T1 receive path decodes standard on-air chips. With no
ambient T1 available (below), the proof is: our own T1 airings --
independently accepted by rtl_wmbus -- were FSK-demodulated from raw IQ
by a separate host tool, and the post-sync byte stream was fed through
the unmodified firmware decode code (`wmbus_3of6_first_byte` ->
`wmbus_3of6_decode` -> `wmbus_check_crc`): 5/5 CRC-OK with the exact
transmitted content. A C1 burst pushed through the same path is
correctly rejected at the first coded byte.
- CONFIRMED (site): there is NO ambient T-mode traffic at this site --
every ambient rtl_wmbus decode is C1. **Correction to earlier belief:**
the large `rx_not_c1` bucket (44 % of sync matches overnight) is NOT
T1 meters; it is C1 frames whose two NRZ mode bytes were corrupted by
bit errors, plus false syncs from the deliberately short 8-bit preamble
detector. The Techem meters here are C-mode.
- Long frames: format B >128-byte CRC chunking and format A up to L=200
are host-tested (sanitizers) and the L=200 format A frame was decoded
CRC-OK over the air by rtl_wmbus.
- T1 length cap: the fixed 255-byte capture holds ceil(total * 1.5) coded
bytes, so T1 receive/repeat covers format A total <= 170 (L <= ~150).
Long C1 covers total <= 253.
- 3-of-6 tables verified against rtl-wmbus t1_c1_packet_decoder.h; codes
are constant weight 3, so every single-chip corruption is detected
(host test flips all 384 chip positions of a 32-byte payload).
+93 -6
View File
@@ -1,10 +1,9 @@
# Future feature note: OLED + button for immediate local feedback # OLED + button for immediate local feedback
Status: **design note only. Not implemented.** The task description Status: **implemented** (firmware/main/ui.c, 2026-09-01). This note holds
explicitly excluded a "production OLED UI" from this experiment, and the the design rationale and constraints; deviations of the implementation
display is untouched by the current firmware. This note records what a from the original sketch are listed at the end. Pins were verified against
local UI should show and the constraints it must respect, while the RTNode-HeltecV4 and are now exercised by our firmware (`ui_init ok:true`).
reasoning is still fresh.
## Why this is worth building ## Why this is worth building
@@ -182,3 +181,91 @@ does **not** share a rail or bus with anything RF-critical, plus at least two
buttons so navigation and confirmation are separable — a single button buttons so navigation and confirmation are separable — a single button
forces gesture overloading, which is how dangerous actions end up behind forces gesture overloading, which is how dangerous actions end up behind
timing tricks. timing tricks.
## Implementation notes (what was actually built)
- `firmware/main/ui.c`: esp_lcd SSD1306 panel over the new i2c_master
driver, 5x7 font (`font5x7.h`, host-verified by
`firmware/test/test_font_render.c`), UI task at priority 3 pinned to
core 0 (radio task is priority 10 on core 1). Rendering is a 1024-byte
full-frame draw every 500 ms while awake.
- Data flow: radio task publishes `g_ui` (last RX / last TX / heartbeat
probe results) in `repeater.c`; the UI additionally reads `g_stats`,
`g_cfg`, and `repeater_duty_used_us()`. The UI never touches the SX1262.
- Button: short press = next page / wake; hold ~1.5 s = page action.
Actions emit `{"event":"ui_action","cmd":...,"value":...}` so serial
logs remain authoritative. A press while the display is blanked only
wakes it and fires nothing.
- Page actions: Status = toggle `repeat_enabled`; Health = clear stats;
Config = toggle beacon at a fixed 3000 ms (907 ppm at L=19 — inside the
default 1000 ppm duty budget, so a button-started beacon cannot violate
the guard). Last-telegram page has no action.
- Display blanks after 3 min idle (panel off command; Vext is never
toggled). Init failure is non-fatal: `{"event":"ui_init","ok":false}`
and the task exits.
- Deviations from the sketch: no RESETS counter on the health page (needs
NVS boot counting, still unimplemented); the duty bar shows used/budget
from the minute-bucket ledger; the config page omits `PA LOW` (the
invalid PA row was removed from the firmware entirely) and `fem_rx_csd`
(console-only diagnostic).
## Wi-Fi dashboard and QR addition (2026-09-09)
Implemented in `wifi_debug.c`, `debug_history.c`, `wifi_qr.c` and
`firmware/main/web/`. Two pages follow Config: Wi-Fi credentials and Wi-Fi
join QR. A long press on either page toggles the AP; no boot-time gesture
is used. The existing four page actions remain unchanged.
The radio publishes a separate 256-entry immutable final-outcome history,
including silent/verbose-only rejection and skip paths, with synchronized
per-row copies. Web clients do not read the deliberately racy OLED snapshot
or query the SX1262. Wi-Fi, TCP/IP, HTTP and control processing use core 0;
the radio remains on core 1. No network/JSON allocation was added to the
radio history producer. Final row IDs correlate reception and transmission
directly, not by frame-hash matching.
The AP is off at boot and stays on until explicitly disabled or rebooted;
display blanking is independent. The password is randomly generated once,
persisted in NVS and shown only on the physical display. The QR encodes
the same credentials and is generated once per boot when its page is used.
Its encoder is the unmodified Nayuki C library v1.8.0 under MIT, with
copyright/license notices retained in `firmware/main/vendor/qrcodegen.*`.
The 64-pixel display height requires small integer-scaled modules; do not
crop the quiet zone or promise camera readability without a physical scan.
The dashboard is entirely offline. CSV labels, templates,
exports, manufacturer registry lookups and device-type interpretation run
in browser JavaScript. Labels never reach the device or persistent browser
storage. See README and `docs/TESTING.md` for usage, exact success semantics
and the distinction between localhost, USB, phone and RF verification.
Both surfaces now use German UI text (ASCII transliterations on the OLED).
The phone dashboard puts current events before collapsed diagnosis and
optional CSV naming. A shared, nonmodal **?** help panel explains wM-Bus
terms without hover, stays outside the refreshed rows, and supports outside
click, explicit close and Escape with focus restoration. Its scrollable
body and visible close control are bounded to the viewport. Detail-cell
spans follow the 560 px radio-column breakpoint, including resize, so
expanded rows do not introduce a phantom column on phones.
## Writable settings addition (2026-09-09)
`settings.c` is the common coordinator for all ten existing USB settings and
OLED toggles. It serializes writers and two-key NVS persistence, publishes
accepted values under a short spinlock, and lets the radio owner copy a whole
revision at a processing boundary. A pending-only IRQ check drains completed
captures and defers known in-flight captures; required radio reinitialization
can still interrupt reception. The applied revision acknowledges copying,
not RF success. OLED rendering reads the applied snapshot, while settings
responses and serial status report accepted values plus both revision numbers.
`settings_http.c` adds bounded JSON writes guarded by AP-host/origin checks,
a random per-AP CSRF token and boot/revision comparison. WPA2 access remains
the authorization boundary. The mobile panel has separate drafts/submit
actions, dirty-value preservation, conflict review, persistence labels and
confirmation for dangerous duty limits or AP shutdown. Expert controls remain
collapsed. Wi-Fi shutdown is queued to its control task, not performed inside
the server being stopped. Only delay and duty budget persist, as before.
The build embeds deterministic gzip assets and serves them directly, avoiding
runtime compression and keeping the existing app/NVS partition layout.
+17 -3
View File
@@ -9,9 +9,10 @@
interferers? -> It helps decisively. CSD low costs ~41 dB and reduces interferers? -> It helps decisively. CSD low costs ~41 dB and reduces
visible meters from 18 to 1; no overload degradation observed visible meters from 18 to 1; no overload degradation observed
(docs/RF_FRONTEND_TESTS.md). (docs/RF_FRONTEND_TESTS.md).
- CLOSED: RX dead time during retransmit -> ~225.7 ms median at a 200 ms - CLOSED: historical RX-unavailable interval during retransmit was
repeat delay, of which 12.2 ms is the fixed-255 RX tail and 13.4 ms the ~225.7 ms median at a 200 ms delay: 12.2 ms fixed-255 RX tail + 200 ms
TX airtime (docs/TIMING.md). Early-stop RX would cut the tail. scheduling delay + 13.4 ms TX operation latency. The representative
packet's computed RF occupancy was 8.8 ms (docs/TIMING.md).
- Can the SX1262 re-arm RX fast enough to catch a meter's immediate - Can the SX1262 re-arm RX fast enough to catch a meter's immediate
follow-up telegram after our TX? follow-up telegram after our TX?
- Exact production repeater framing/hop requirements (EN 13757-5). - Exact production repeater framing/hop requirements (EN 13757-5).
@@ -39,3 +40,16 @@
at this site, so the question is unresolved empirically -- it needs the at this site, so the question is unresolved empirically -- it needs the
EN 13757-4 text, or a meter that emits one. Until then, a real meter using EN 13757-4 text, or a meter that emits one. Until then, a real meter using
those lengths is an interoperability risk worth a targeted test. those lengths is an interoperability risk worth a targeted test.
## Duty ledger event-capacity bug (closed 2026-09-01, loc3)
The old `DUTY_RING=384` implementation saturated at about 2.7 s of history
at ~7 ms per event, below the 3.6 s hourly budget. It silently forgot old
events while they were still inside the hour; this was observed during the
beacon soak.
Fixed: 61 keyed minute buckets accumulate every successful transmission.
The rolling-hour query includes every bucket overlapping the window,
including the oldest partial minute in full (safe over-count). Host tests
cover 10,000 events in one bucket, all 61 overlapping minutes, exact expiry,
invalid timestamps, and zero-length records.
+48 -14
View File
@@ -1,6 +1,34 @@
# Reliability # Reliability
## Soak result (final firmware, `captures/2026-09-01T11-34-08-soak`) ## Overnight standalone battery soak (2026-09-01/02): milestones A-D reached
DUT on LiPo, no USB host, no observer needed -- firmware counters read via
OLED overnight and archived exactly over serial in the morning
(`captures/2026-09-01T22-48-32-standalone-soak/overnight_final_stats.log`).
```
uptime : 42 339 s (11 h 45 m), zero resets
RX candidates : 9 617 = 4 905 valid + 1 423 crc_fail
+ 3 274 not_c1 + 15 len_invalid (exact closure)
TX attempts / success : 2 822 / 2 822 (100 %)
TX timeouts / failures : 0 / 0
radio recoveries/reinits : 0 / 0
duty suppressions : 2 092 (~41 % of valid traffic over budget)
cumulative TX airtime : 23.72 s computed occupancy (8.4 ms avg/frame)
lifetime duty cycle : 560 ppm (guard held the night at 56 % of cap)
```
Milestones A (>=10), B (>=100), C (>=500), D (>=1000 repeats, no restart):
**all REACHED** in one unattended run. Independent RF confirmation the
following morning: meter-anchored capture verified live repeats (2 decoded
duplicates, 2 RF pairs at 53-54 ms vs the 50 ms setting).
The 2 092 suppressions are the first production evidence for the
STANDARDS_GAPS conclusion that repeat-everything exceeds the 0.1 % duty
budget at a real site (~1.7x here); an installation-list filter is
mandatory for a product.
## Historical soak result (`captures/2026-09-01T11-34-08-soak`)
Repeater running unattended, no SDR involved, repeat delay 200 ms, Repeater running unattended, no SDR involved, repeat delay 200 ms,
duty-cycle guard at 0.1 %. duty-cycle guard at 0.1 %.
@@ -18,12 +46,12 @@ TX attempts : 380
TX success : 380 (100.0 %) TX success : 380 (100.0 %)
TX timeouts / failures : 0 / 0 TX timeouts / failures : 0 / 0
repeat delay : 200.001 ms min, 200.001 median, 200.006 max repeat delay : 200.001 ms min, 200.001 median, 200.006 max
TX airtime : 10.2 / 13.4 / 14.9 ms (min/median/max) TX operation latency : 10.2 / 13.4 / 14.9 ms (min/median/max)
radio recoveries : 0 radio recoveries : 0
heartbeats not in RX : 0 heartbeats not in RX : 0
heartbeats config lost : 0 heartbeats config lost : 0
duty-cycle suppressions : 8 (guard working as designed) old-guard suppressions : 8 (based on operation latency, not RF airtime)
``` ```
## Milestones (firmware-reported repeats, no restart) ## Milestones (firmware-reported repeats, no restart)
@@ -35,23 +63,29 @@ duty-cycle suppressions : 8 (guard working as designed)
| C | >= 500 | not reached (run stopped early at 380) | | C | >= 500 | not reached (run stopped early at 380) |
| D | >= 1000 | not reached | | D | >= 1000 | not reached |
Milestone C needs roughly 2 h at the observed rate, or longer once the Milestone C needs roughly 2 h at the observed rate. The run was ended
duty-cycle guard caps output at ~268 repeats/hour. The run was ended early early by operator request; nothing in the data suggests it would not
by operator request; nothing in the data suggests it would not continue -- continue -- the last heartbeat was as healthy as the first, with zero
the last heartbeat was as healthy as the first, with zero recoveries and recoveries and zero resets across 1.5 h. To continue:
zero resets across 1.5 h. To continue:
``` ```
nix develop --command ./hil/soak.sh 9000 nix develop --command ./hil/soak.sh 9000
``` ```
## Duty-cycle guard behaviour ## Duty-cycle guard correction
At the observed traffic rate the repeater wants ~320 repeats/hour, which at The old report multiplied ~320 repeats/hour by 13.4 ms TX-operation
13.4 ms measured airtime each is ~0.12 % -- above the 0.1 % ceiling for latency and called the result ~0.12 % RF duty. For the representative
868.7-869.2 MHz. The guard suppressed 8 repeats to stay inside the budget 102-byte radio payload, computed occupancy is 8.8 ms, so the same rate is
(`used_us` 3 594 561 against `budget_us` 3 600 000) and reported a final about 0.078 %. The eight suppressions at `used_us` 3,594,561 were caused by
`tx_duty_cycle_ppm` of 905, i.e. 0.0905 %. See docs/STANDARDS_GAPS.md. the old conservative wall-time metric, not proof that actual channel
occupancy reached 0.1 %. Likewise, the reported 905 ppm was cumulative
operation latency divided by uptime.
Current firmware budgets computed packet occupancy and stores it in a
61-minute bucket ledger. Historical stability/TxDone counts above remain
valid; historical airtime, suppression, and duty-rate interpretations do
not. See docs/TIMING.md and docs/STANDARDS_GAPS.md.
## What has NOT been demonstrated ## What has NOT been demonstrated
+32 -2
View File
@@ -41,8 +41,15 @@ RX gain: boosted (reg 0x08AC = 0x96)
TX params: default -9 dBm configured (min), ramp 40 us; PA config TX params: default -9 dBm configured (min), ramp 40 us; PA config
(0x02,0x02,0x00,0x01) = +14 dBm-optimal table, deliberately (0x02,0x02,0x00,0x01) = +14 dBm-optimal table, deliberately
capped -- the external KCT8103L PA adds gain on top capped -- the external KCT8103L PA adds gain on top
``` ```
PA-row invariant: `deviceSel` must remain `0x00` for SX1262, and the other
bytes must come from an SX1262 row. The removed diagnostic
`(0x01,0x00,0x00,0x01)` mixed the SX1261 +10 dBm PA-duty/hpMax values with
SX1262 selection. This undocumented hybrid reduced measured RF by about
32 dB while all chip-side TX diagnostics still passed.
## Consequences of the fixed-255-byte RX capture ## Consequences of the fixed-255-byte RX capture
RxDone fires ~ (255 - frame_len) * 80 us after the actual end of frame; RxDone fires ~ (255 - frame_len) * 80 us after the actual end of frame;
@@ -54,5 +61,28 @@ time per frame. Acceptable for the experiment; optimization candidate
## TX power ## TX power
Configured SX1262 power is NOT radiated power: the KCT8103L PA follows. Configured SX1262 power is NOT radiated power: the KCT8103L PA follows.
Development default is the SX1262 minimum (-9 dBm). Log lines carry Development default is the SX1262 minimum (-9 dBm), and the console accepts
`configured_tx_dbm` to keep this distinction explicit. only -9..+2 dBm. +2 is the level used by known-good Heltec V4.3 firmware,
not a declaration of legal radiated power. Keep -9 dBm until the complete
FEM/antenna path has a conducted or calibrated e.r.p. measurement.
`wmbus_tx.configured_tx_dbm` records SetTxParams. `airtime_us` is computed
channel occupancy (48-bit preamble + 16-bit sync + payload at 100 kbps);
`tx_operation_us` is the longer firmware-entry-through-TxDone latency.
## T-mode (T1) support
T1 shares the 0x543D access code, so ONE radio configuration receives
both modes: C-mode announces itself with two NRZ mode bytes after the
sync; T-mode continues directly with 3-of-6 coded data (decoded in
software from the same fixed 255-byte capture; wM-Bus C/T share the
100 kchip/s rate). Tables verified against rtl-wmbus.
TX: T1 frames are 3-of-6 encoded in software and sent with 50 kHz FSK
deviation (raw 0x00CCCD) instead of C-mode's 45 kHz; the swap is a lazy
per-TX SetModulationParams (deviation is a TX-only GFSK parameter, RX is
unaffected). Verified: rtl_wmbus decodes our synthetic T1 frames,
including L=140.
Length caps from the fixed 255-byte capture: C1 total <= 253 bytes;
T1 total <= 170 decoded bytes (coded 1.5x).
+22 -10
View File
@@ -127,6 +127,11 @@ negligible. In the *full* state, however, an earlier IQ capture showed our
repeat at +44.8 dB over floor with IQ amplitude at the dongle's full scale repeat at +44.8 dB over floor with IQ amplitude at the dongle's full scale
(rms 88.6 of 127) while the meter original sat at +8.4 dB - a ~36 dB gap. (rms 88.6 of 127) while the meter original sat at +8.4 dB - a ~36 dB gap.
These TX amplitudes predate PA-row telemetry. They demonstrate the
observer's compression behavior in those captures, but must not be used as
the output level of the fixed firmware: the now-removed `pa_low` diagnostic
could select an undocumented SX1261-values/SX1262-select hybrid.
Consequence: with a fully sensitive dongle, meter originals decode well at Consequence: with a fully sensitive dongle, meter originals decode well at
high gain but our own transmission is driven into compression and high gain but our own transmission is driven into compression and
rtl-wmbus receives it with a few byte errors (CRC fails). Observed rtl-wmbus receives it with a few byte errors (CRC fails). Observed
@@ -134,15 +139,20 @@ directly - the decoded hex differed from the transmitted frame in 1-2
bytes, e.g. transmitted `...78534f4c5458...` received `...78514f4c5448...`, bytes, e.g. transmitted `...78534f4c5458...` received `...78514f4c5448...`,
with the rest of a 113-byte frame bit-exact. with the rest of a 113-byte frame bit-exact.
Mitigations applied in firmware: SX1262 at its minimum configured power Firmware correction: the former “lowest documented PA table”
(-9 dBm) and the lowest documented PA table (paDutyCycle 0x01, hpMax 0x00, `(paDutyCycle=0x01, hpMax=0x00, deviceSel=0x00, paLut=0x01)` mixed the
SX1262 datasheet table 13-21). Remaining mitigation is physical (antenna PA-duty/hpMax values from the SX1261 +10 dBm row with SX1262 selection.
separation or an inline attenuator) and is not scriptable from this host. It is not a documented SX1262 row and cost about 32 dB. It has been
deleted. Current firmware uses documented SX1262
`(0x02,0x02,0x00,0x01)` with SetTxParams -9 dBm. Receiver compression must
be handled at the observer with fixed low gain, physical separation, or an
attenuator—not by misconfiguring the DUT PA.
Note: `rtl_sdr -g 0` selects *automatic* gain, not 0 dB. The lowest real Note: `rtl_sdr -g 0` selects *automatic* gain, not 0 dB. The lowest real
fixed gain on this tuner is 0.9 dB. At 0.9 and 7.7 dB fixed gain the fixed gain on this tuner is 0.9 dB. In the historical degraded-observer
degraded dongle decoded nothing at all (neither meters nor our TX), so low test, 0.9 and 7.7 dB decoded neither meters nor the then-configured TX.
gain is not a usable workaround in that state. With fixed firmware, a 0.9 dB-gain smoke capture measured all 9 beacons at
median +27.81 dB over floor without clipping.
## Repeat-delay dependence of observer decoding ## Repeat-delay dependence of observer decoding
@@ -164,6 +174,8 @@ the firmware's own repeat delay measures 200.0 ms min/median/max.
1. Meter originals and Heltec RX match rate: rtl-wmbus decodes at high gain. 1. Meter originals and Heltec RX match rate: rtl-wmbus decodes at high gain.
2. Heltec TX framing is decodable as C1: proven with synthetic bursts that 2. Heltec TX framing is decodable as C1: proven with synthetic bursts that
are not preceded by a weak frame (`hil/verify_tx.py`). are not preceded by a weak frame (`hil/verify_tx.py`).
3. Real repeats: proven at RF level from the same stream's IQ by aligning 3. Real repeats: proven at RF level from the same stream's IQ by
firmware TX timestamps to observed bursts (`hil/verify_repeats_iq.py`), `hil/meter_anchored.py` -- clock fitted on strong meter receptions
which is immune to both compression and observer sensitivity drift. (never on TX events, which can borrow their original's burst), then
event-correlated FSK spectral excess against non-TX controls. Immune to
compression and observer drift; classifies strong/weak/not_observed.
+66 -14
View File
@@ -5,36 +5,88 @@ repeater. Known deviations:
| # | Experimental behavior | Standard requirement | | # | Experimental behavior | Standard requirement |
|---|---|---| |---|---|---|
| 1 | Repeats the raw telegram bit-exact, including hop-related fields | EN 13757-5 repeaters must manage the hop counter / C-field semantics so telegrams are not repeated endlessly | | 1 | Marks supported OMS uplinks with H=1 and repairs the affected CRC; unsupported layouts are skipped | Full repeater behavior still requires installation handling and timing compliance; see implementation notes below |
| 2 | Fixed development repeat delay 20-200 ms (default 50 ms) | OMS repeaters use randomized delays in the seconds range to avoid collisions | | 2 | Fixed repeat delay 20-1000 ms (persisted; 500 ms in current field testing) | OMS repeaters use randomized delays in the seconds range to avoid collisions |
| 3 | Repeats every CRC-valid C1 telegram (optional dev whitelist) | Real repeaters filter by installation list | | 3 | Repeats CRC-valid C1/T1 uplinks passing C-field, hop/access-bit and supported-header checks (optional dev whitelist) | Real repeaters filter by installation list |
| 4 | Rolling-hour duty-cycle guard, default 0.1 % (1000 ppm), suppresses repeats over budget and counts them (`tx_suppressed_duty`) | A production repeater needs proper duty-cycle management, or LBT+AFA, plus per-sub-band awareness | | 4 | Rolling-hour duty-cycle guard, default 0.1 % (1000 ppm), suppresses repeats over budget and counts them (`tx_suppressed_duty`) | A production repeater needs proper duty-cycle management, or LBT+AFA, plus per-sub-band awareness |
| 5 | Duplicate suppression is a 2.5 s hash ring | Standard requires proper duplicate/loop protection semantics | | 5 | H=1/R=1 frames are suppressed; a 2.5 s hash ring also suppresses duplicate originals | Full installation and duplicate-management policy still needs review |
| 6 | No AES, no decryption, payload treated as opaque | OMS security profiles apply to end devices; a transparent repeater may pass ciphertext, but production behavior needs review | | 6 | No AES, no decryption, payload treated as opaque | OMS security profiles apply to end devices; a transparent repeater may pass ciphertext, but production behavior needs review |
| 7 | T1 telegrams are detected (shared 0x543D sync) but dropped | A combined C/T repeater would need 3-of-6 decode/encode | | 7 | C1 and T1 both received and repeated in their native mode (3-of-6 codec in software, per-TX deviation swap). S-mode out of scope | A production repeater still needs reviewed mode policy (e.g. never re-air T1 as C1) |
| 8 | Format B frames >128 bytes CRC-checked but rare path untested | -- | | 8 | Format B >128 bytes and format A up to L=200 host-tested and verified on air (2026-09-02) | -- |
None of these shortcuts may be carried into the production Solenos/Gebos None of these shortcuts may be carried into the production Solenos/Gebos
gateway without explicit review. gateway without explicit review.
Scope decision (2026-09-02): S-mode support is explicitly OUT OF SCOPE --
no S-mode traffic observed at either test site. T-mode receive/repeat and
long-frame support were implemented and RF-verified 2026-09-02. Site
finding from that verification: this site has NO ambient T-mode traffic
either (all ambient decodes are C1); the firmware's historical `rx_not_c1`
bucket is mode-byte-corrupted C1 plus false syncs, not T1 meters.
Persistence exception (2026-09-02): `duty_budget_ppm` and
`repeat_delay_ms` survive power cycles (NVS), because battery-standalone
testing needs settings that outlive reboots. **A persisted
`duty_budget_ppm` of 0 disables the duty guard indefinitely** -- the
device transmits over the ERC/REC 70-03 budget whenever traffic exceeds
it, until `set duty_budget_ppm 1000` is sent again. The OLED config page
shows the effective values (`DUTYCAP`, `DELAY`); boot logs `cfg_restore`.
Re-enable the guard after every guard-off test session.
## OMS hop marking (2026-09-09)
`wmbus_mark_repeated()` in `firmware/main/wmbus.c` operates on a CRC-validated
raw format A/B frame, before C1 framing or T1 3-of-6 encoding. It accepts
only C-fields `44` (SND_NR) and `46` (SND_IR), with H=0 and R=0:
- ELL CI `8C` or `8E`: set bit 4 of the Communication Control byte.
ELL takes precedence over any inner Transport Layer configuration.
- Without ELL: an explicitly recognized short/long uplink TPL header in
security mode 0 or 5 uses bit 0 of the Configuration field.
- Already-repeated/access-marked frames, truncated headers, and unsupported
layouts are left unchanged and not transmitted. Unsupported includes
headerless CI `78`, ELL `8D`/`8F`, and AFL without a supported outer ELL.
There is no bit-exact fallback.
Only H and its enclosing block's CRC change. The helper maps logical header
offsets across raw CRC boundaries; it neither decrypts nor copies the payload.
Frame length, meter identity, access number and ciphertext remain unchanged.
The original RX hash remains the RX/TX log correlation key; TX `raw` contains
the actual modified physical payload. Verbose mode reports policy rejection
as `tx_suppressed` with reason `hop_policy`.
H identifies a repeated copy, not a repeater ID, and does not enable multihop.
Synthetic `test_tx`, `test_tx_t1`, beacons and `test_burst` remain unchanged
PHY probes, not examples of received-frame repeater policy. Existing delay,
whitelist and duty-cycle settings are unchanged.
Reference: [OMS Volume 2, issue 5.0.1](https://oms-group.org/wp-content/uploads/2024/10/OMS-Spec_Vol2_Primary_v501_01.pdf),
sections 5.2.2.2, 5.2.5.2 and 7.2.4. Setting H alone does not establish full
OMS compliance. The new marking path has not yet been verified over RF.
## Duty cycle — measured, and why it matters ## Duty cycle — measured, and why it matters
868.95 MHz falls in the 868.7-869.2 MHz sub-band, which ERC/REC 70-03 868.95 MHz falls in the 868.7-869.2 MHz sub-band, which ERC/REC 70-03
(annex h1.6) limits to 25 mW e.r.p. with **<= 0.1 % duty cycle**, unless the (annex h1.6) limits to 25 mW e.r.p. with **<= 0.1 % duty cycle**, unless the
device implements LBT+AFA. device implements LBT+AFA.
Measured on this bench: Absolute e.r.p. from the SX1262 plus KCT8103L and antenna has not been
calibrated. The default -9 dBm SetTxParams value is the minimum chip setting,
not proof of compliance with the 25 mW e.r.p. cap.
Current computed occupancy for the historical bench traffic:
``` ```
TX airtime per repeat : 10.4-14.6 ms (median 13.4 ms), frame-length dependent RF occupancy per repeat : ~5.8-9.8 ms (8.8 ms for 102 radio bytes)
observed repeat rate : ~5-6 repeats/min when repeating every valid telegram observed repeat rate : ~5-6 repeats/min when repeating every valid telegram
resulting duty cycle : ~0.11-0.13 % resulting duty cycle : roughly 0.07-0.09 % at the representative length
``` ```
That is at or slightly above the 0.1 % ceiling — while repeating only the An older report used 10.4-14.6 ms TX-operation latency (median 13.4 ms)
CRC-valid C1 telegrams audible at a single indoor location. A production as if it were RF airtime and consequently reported 0.11-0.13 %. That was a
repeater in a denser environment, or one that also handles T-mode, would safe overestimate but not channel occupancy. Even the corrected site rate
exceed the budget substantially. is close to 0.1%; traffic variation, longer frames, a denser environment,
or adding T-mode can exceed the budget.
Consequences for the production gateway: Consequences for the production gateway:
+231 -13
View File
@@ -13,8 +13,8 @@ capture -> correlation -> report (text + report.json). Exit 0 = PASS.
Useful flags: Useful flags:
- `--no-flash` reuse the already-flashed firmware - `--no-flash` reuse the already-flashed firmware
- `--duration N` capture window seconds - `--duration N` capture window seconds
- `--tx-power N` configured SX1262 dBm (-9..14; FEM adds gain!) - `--tx-power N` configured SX1262 dBm (-9..+2; FEM adds gain!)
- `--delay MS` repeat delay (20..200) - `--delay MS` repeat delay (20..1000; note: run.sh sets it on the DUT, which persists)
- `--gain G` SDR tuner gain - `--gain G` SDR tuner gain
- `--min-repeats N` PASS threshold - `--min-repeats N` PASS threshold
@@ -33,15 +33,25 @@ setup.log DUT configuration acks
``` ```
./tools/discover_devices.sh -v # device inventory ./tools/discover_devices.sh -v # device inventory
./tools/flash.sh # build + flash ./tools/flash.sh # build + flash; no SDR required
./hil/capture_sdr.sh 60 /tmp/sdr.log # SDR-only capture ./hil/capture_sdr.sh 60 /tmp/sdr.log # SDR-only capture
./result-py/bin/python3 hil/dut_cmd.py PORT --listen 10 status stats ./result-py/bin/python3 hil/dut_cmd.py PORT --listen 10 status stats
./result-py/bin/python3 hil/iq_energy.py iq.raw # burst energy probe ./result-py/bin/python3 hil/iq_energy.py iq.raw # burst energy probe
./result-py/bin/python3 hil/iq_spectrum.py iq.raw # spectrum sanity ./result-py/bin/python3 hil/iq_spectrum.py iq.raw # spectrum sanity
./result-py/bin/python3 hil/sdr_health.py # observer sensitivity ./result-py/bin/python3 hil/sdr_health.py # observer sensitivity
./firmware/test/run_tests.sh # frame-layer tests (ASan) ./firmware/test/run_tests.sh # frame + duty-ledger tests (sanitizers)
``` ```
Hop-marker regression coverage in the host frame suite checks ELL precedence,
short/long TPL headers, H/R and security-mode rejection, truncated frames,
format A/B block boundaries, unchanged payload bytes and T1 encode/decode.
The 2026-09-09 host smoke also marked three captured meter frames and passed
them through `wmbusmeters`: ELL was reported as `relayed`, mode 5 as `hc=1`,
and the unencrypted water telegram still decoded its readings. Encrypted
captures were not decrypted (no meter keys); ciphertext preservation was
checked byte-for-byte. Target firmware build and HIL CLI smoke passed;
the new marking behavior has not been flashed or RF-verified.
## DUT serial commands ## DUT serial commands
All output is single-line JSON; every line the HIL parses starts with `{`. All output is single-line JSON; every line the HIL parses starts with `{`.
@@ -54,23 +64,199 @@ radio_status chip mode, command status, device errors, RSSI
radio_reset queue a full radio re-init radio_reset queue a full radio re-init
probe low-level scripted SPI/IRQ/TX diagnostic with raw dumps probe low-level scripted SPI/IRQ/TX diagnostic with raw dumps
test_tx transmit one synthetic C1 frame test_tx transmit one synthetic C1 frame
test_tx_t1 transmit one synthetic T1 frame (3-of-6, 50 kHz dev)
test_burst transmit the same frame twice, repeat_delay_ms apart test_burst transmit the same frame twice, repeat_delay_ms apart
inject standby fault injection: leave the radio out of RX inject standby fault injection: leave the radio out of RX
inject sleep fault injection: destroy the radio configuration inject sleep fault injection: destroy the radio configuration
reboot reboot
set repeat_delay_ms N 20..200 set repeat_delay_ms N 20..1000. PERSISTED across reboots (NVS)
set tx_power N -9..14 (configured SX1262 level; FEM adds gain) set tx_power N -9..+2 (configured SX1262 level; FEM adds gain)
set repeat_enabled 0|1 set repeat_enabled 0|1
set verbose 0|1 set verbose 0|1
set fem_rx_csd 0|1 KCT8103L CSD level while in RX (LNA experiment) set fem_rx_csd 0|1 KCT8103L CSD level while in RX (LNA experiment)
set pa_low 0|1 1 = lowest documented PA table
set preamble_bits N 0|8|16|24|32 preamble detector length set preamble_bits N 0|8|16|24|32 preamble detector length
set duty_budget_ppm N rolling-hour TX airtime cap; 1000 = 0.1 %, 0 = off set duty_budget_ppm N rolling-hour TX airtime cap; 1000 = 0.1 %, 0 = off.
0..100000. PERSISTED across reboots (NVS), like delay.
Re-enable after guard-off tests!
set test_lfield N 19..200, length of synthetic test frames set test_lfield N 19..200, length of synthetic test frames
set whitelist ID[,ID...] | set whitelist clear set beacon_period_ms N 0 (off) or 250..600000; periodic synthetic frames
set whitelist ID[,ID...] | set whitelist clear (up to 8 unique eight-hex IDs)
``` ```
The ten `set` commands, OLED toggles and web writes share validation and
revisioned configuration. Integers/booleans must be complete, not valid-looking
prefixes; malformed or duplicate IDs are rejected rather than truncated.
`status` retains its previous fields and adds all missing settings,
`revision`, `applied_revision` and the complete whitelist. Accepted values can
briefly precede application by the radio task. A TX-power or preamble change
requires radio reinitialization; a copied revision is not hardware/RF proof.
## On-device UI (OLED + PRG button)
Standalone debug without a host (docs/FUTURE_UI.md for design + pins):
- Pages (short press cycles, wraps): live status w/ duty bar -> health
counters -> last telegram -> effective config -> Wi-Fi credentials ->
Wi-Fi join QR.
- Hold ~1.5 s for the page action, each logged as
`{"event":"ui_action",...}`: status = toggle repeat, health = clear
stats, config = toggle beacon at 3000 ms (duty-safe at L=19), either
Wi-Fi page = enable/disable the debug access point.
- Display blanks after 3 min; any press wakes it without acting.
- `{"event":"ui_init","ok":...}` at boot reports display bring-up; a
missing/broken display never blocks the repeater.
- Config shown is the applied RAM snapshot. Delay and duty budget are restored
from NVS on boot; other settings reset. Unplugging USB with LiPo attached
does not reboot the device.
## Wi-Fi dashboard checks
Enable **WLAN-DIAGNOSE** using the OLED, join the displayed WPA2 network, and
open `http://192.168.4.1`. The following page provides a standard `WIFI:`
join QR (SSID and password, not the dashboard URL). Wi-Fi starts off on
reboot; its password persists in the separate `wifi_debug` NVS namespace.
On enable/disable, serial emits `wifi_debug` states: 0 off, 1 starting,
2 on, 3 stopping, 4 error, plus the ESP-IDF error code. Credentials are
not logged. Never change the test workstation's Wi-Fi without permission;
phone-based testing avoids disturbing its network.
The history API remains read-only: `GET /api/events?after=N`. Start at zero;
responses carry `boot_id`, cursor, retention/eviction metadata, cached
status and immutable final rows. A stale/ahead cursor causes `reset`.
Clients must fetch from zero on a new boot ID. The browser polls once per
second and keeps at most 256 rows. Pause freezes the event display, not
recording/polling. RX/repeat counters exclude synthetic events and survive
OLED/serial `clear_stats`, but not reboot.
### Writable settings API
Open **Einstellungen am Heltec-Gerät ändern**. Each field has its own draft,
accepted device value, persistence indication and explicit submit action.
The ten fields match the serial commands above; T1 synthetic sends still cap
the effective test L-field at 140. The browser warns before duty 0 or >1000
and before disabling the AP. CSV names remain browser-only.
- `GET /api/settings` returns `boot_id`, `revision`, `applied_revision`,
`csrf_token` and `settings` containing all ten keys.
- `POST /api/settings` accepts exactly `{boot_id,revision,key,value}`, one
setting at a time. Values are JSON integers, booleans or an array of up to
eight unique eight-hex-digit whitelist strings; an empty list allows all.
The response has the same snapshot shape.
- `POST /api/wifi/disable` accepts exactly `{boot_id}` and returns `{ok:true}`
before requesting an idempotent stop from the separate Wi-Fi control task.
A lost response leaves the client uncertain; it never retries automatically.
- Writes require `Content-Type: application/json` and `X-CSRF-Token` from GET.
Host must be `192.168.4.1` (optional port 80); foreign Origin/Fetch-Site values
are rejected. The random CSRF token rotates when the AP starts. WPA2 AP
access is the authorization boundary; there is no separate per-user login.
- Bodies are bounded to 512 bytes and shallow JSON, with duplicate/unknown
fields and embedded NULs rejected. Invalid inputs return 400, stale boot or
revision 409, origin/token failures 403, and busy/persistence failures 503.
No failed write is reported as saved.
- Pending settings are copied coherently by the radio owner, never written
into a half-processed reception from HTTP/OLED/USB. NVS runs under the writer
mutex outside the radio task; short spinlocks protect only memory copies.
Settings GETs while pending are capped at 1 Hz and 30 attempts, with no
overlap or blind POST retry. Conflicts preserve drafts and require review.
Static assets are gzip-compressed at build time by `tools/compress_web_asset.py`,
then served directly with `Content-Encoding: gzip`; no runtime compression or
partition-layout change is required.
Acceptance scenarios:
- See each reception's CRC/decode result and repeat completion, failure or
explicit skip. A TX timestamp is software-operation entry (including
driver setup), not an independently measured RF-start timestamp. A TX
outcome timestamp can represent an error, not successful completion.
- Load the downloaded CSV template or observed-ID export, preserving
leading zeros. Quoted commas/newlines are supported. A duplicate ID or
malformed CSV must leave all previous mappings unchanged. Refresh clears
mappings. Labels apply only to CRC-valid received identities.
- Check manufacturer-scoped type meanings (e.g. TCH), unknown raw codes,
version bytes and ambiguity warnings. Identity refers to the link-layer
sender, not necessarily a separately addressed transport-layer meter.
- Pause while new events arrive, reconnect after history eviction, and
reboot: no cross-boot or cross-reception joins are allowed.
- Compare radio timing/health with Wi-Fi off, on and actively serving
clients. Verify disable/re-enable and password persistence. Independently
observe RF if claiming unchanged sensitivity or downstream reception.
- Scan the OLED QR with a phone. Its integer-scaled, positive-polarity
modules retain at least a four-module quiet zone. On this small OLED,
camera focus can still be limiting; use text credentials if needed.
- On 320/390-pixel phone viewports, check that the current signals are easy
to find, controls are tappable and there is no horizontal page overflow.
Open **?** explanations by touch, including near the bottom of the page.
Close with the same button, outside tap, explicit close and Escape.
Explanations must remain usable while live rows update.
All authored visible UI/accessibility text is German; technical raw codes,
exact CSV/API headers and registered company names are intentionally kept.
2026-09-09 integration checks: test/debug builds and existing host suites
passed. A sanitized history smoke exercised 200,000 writes with concurrent
snapshots, overflow, cursor reset and synthetic/counter separation.
The actual browser assets were exercised on a localhost fixture server:
mobile layout, labels/filtering, atomic CSV rejection, downloaded template,
pause, ambiguity, eviction, disconnect/reconnect, reboot and refresh.
An independent ZBar decoder recovered the expected join payload from the
exact 128x64 framebuffer generated by the production QR renderer.
The German UI was checked at 320/390 px, including popup scrolling,
44 px help/button targets, local German CSV labels, outside/same-button/
explicit-close/Escape dismissal and focus restoration. A detail popup
remained open while the live history grew from five to six rows. Expanded
rows initially created a phantom fourth column on phones; the corrected
column spans were exercised across 320 -> 760 -> 390 px without reload.
Page/header widths stayed aligned and there was no horizontal overflow.
Browser checks used coordinate mouse input on narrow/mobile-emulated
viewports; native touchscreen automation timed out, so a physical phone
touch/QR check is still required. Evidence is retained locally under
`captures/2026-09-09-wifi-dashboard/`.
Pre-settings image sizes were test 927,360 bytes and debug 1,041,264 bytes.
The writable-settings build with compressed assets is now 862,672 bytes
(test, 18% app space free) and 978,656 bytes (debug, 7% free). The partition
layout and NVS locations were not changed.
After flashing the earlier, pre-settings German test build, USB telemetry at 59.74 s showed
six reception candidates, one CRC-valid reception, one CRC rejection, no
TX errors and no recoveries. Heartbeats reported RX mode and intact radio
configuration. This confirms live firmware operation, not phone access.
The test-profile firmware was flashed to the attached ESP32-S3. In the
pre-QR hardware smoke, the OLED action started the AP successfully; seven
CRC-valid receptions produced five completed repeats with no recoveries or
TX errors. Four repeats while the AP was on had software delays of
50.001–50.005 ms for a 50 ms setting. This small sample is not a controlled
RX-sensitivity comparison, RF delivery proof, or proof of active HTTP load.
Physical phone scanning and end-to-end HTTP checks require a phone report
or an explicitly authorized network connection; do not infer them from the
localhost fixture checks.
Writable-settings checks: 49 sanitized host scenarios ran the production
`settings.c`, `settings_http.c` and ESP-IDF cJSON parser through small host
HTTP/FreeRTOS/NVS adapters. They exercised all ten accepted settings,
non-mutating validation/security failures, two concurrent revision-CAS writers,
simulated storage failure/reboot and radio-copy acknowledgement. This is not
physical NVS or radio-handoff verification.
Chromium exercised all ten forms against that coordinator, preserved unrelated
drafts and edits made while a POST was delayed, rejected malformed input,
handled 409/503 without automatic writes, and gated dangerous duty changes and
Wi-Fi-off with native confirm/cancel dialogs. Confirmed Wi-Fi-off stopped
automatic polling while retaining CSV names. Layout/help were inspected at
320/390 px; setting inputs are 16 px and buttons at least 44 px high. All five
built gzip assets decompressed byte-for-byte to their sources and loaded in
Chromium. Existing frame, duty-ledger, long-T1 and font suites passed.
The settings firmware is built but **not yet flashed**: the Heltec USB device
disappeared before the flash command could open it; both serial discovery and
USB enumeration found it absent. Reconnect USB for the final on-device setting,
radio-handoff and reboot/persistence smoke. Workstation Wi-Fi was not changed.
Physical phone HTTP/QR checks remain separate. Local proof artifacts are in
`captures/2026-09-09-web-settings/`.
## Known pitfalls ## Known pitfalls
- SDR PLL wedge -> gain-independent white noise; `usbreset 0bda:2838`. - SDR PLL wedge -> gain-independent white noise; `usbreset 0bda:2838`.
@@ -96,6 +282,35 @@ Every run records `SDR sensitivity: full | degraded` from
runs report the same state -- this dongle loses ~17 dB within minutes of runs report the same state -- this dongle loses ~17 dB within minutes of
streaming (docs/HARDWARE.md). streaming (docs/HARDWARE.md).
## Meter-anchored TX verification
When serial telemetry and raw IQ were captured together:
```
./result-py/bin/python3 hil/meter_anchored.py \
--iq iq.raw --serial serial.log --json
```
The verifier first fits the DUT/IQ clocks only from strong meter receptions,
which prevents a repeat from borrowing its own original burst. It then
compares the median spectrum at exact TX times with nearby non-TX control
windows. `rf_state` is:
- `strong`: event-correlated FSK is present and median event energy is at
least 6 dB over the capture floor;
- `weak`: event-correlated FSK is present below that energy threshold;
- `not_observed`: no event-correlated FSK signature;
- `no_events`: the serial log contained no in-range TX events.
`tx_above_6db` is only an energy count; it is not an RF verdict by itself.
`fsk_excess_db` is the in-band (20-80 kHz offset) event/control excess after
subtracting wideband (250-700 kHz offset) event/control change. At least
five analyzable TX/control pairs are required.
For unattended beacon runs, `hil/beacon_soak.sh` discards raw IQ only when
the result is `strong`. Weak, absent, or unclassified segments retain IQ
for reanalysis.
## Long reliability soak (DUT only, no SDR) ## Long reliability soak (DUT only, no SDR)
``` ```
@@ -161,10 +376,13 @@ cat iq.raw | rtl_wmbus -f > decodes.log
./result-py/bin/python3 hil/verify_standalone.py --iq iq.raw --decodes decodes.log ./result-py/bin/python3 hil/verify_standalone.py --iq iq.raw --decodes decodes.log
``` ```
Reports decoded repeats (same payload twice) and RF-level repeat pairs Reports decoded C1/T1 repeats (a supported H=0 original followed by its H=1
(burst pairs of matching duration inside the delay window). The latter counterpart, with every other cooked byte identical) and RF-level repeat
matters because our transmission usually overloads the dongle and fails CRC pairs (burst pairs of matching duration inside the delay window). Decoded
even though the RF is correct. pairs use occurrence order because SDR timestamps are quantized; each
original is matched once. Same-H duplicate decodes are not repeat proof.
The RF-level check matters because our transmission usually overloads the
dongle and fails CRC even though the RF is correct.
Note: only one process can hold the RTL-SDR. If another tool (e.g. an Note: only one process can hold the RTL-SDR. If another tool (e.g. an
oms-tui / wmbusmeters pipeline) is running, `rtl_sdr` fails with oms-tui / wmbusmeters pipeline) is running, `rtl_sdr` fails with
+38 -28
View File
@@ -9,24 +9,24 @@ repeats, 214 RX candidates, repeat delay set to 200 ms).
| Quantity | min | median | max | n | | Quantity | min | median | max | n |
|---|---|---|---|---| |---|---|---|---|---|
| RxDone -> reconstructed end of frame ("deaf tail") | 9 360 us | 12 240 us | 17 120 us | 214 | | RxDone -> reconstructed end of frame ("deaf tail") | 9 360 us | 12 240 us | 17 120 us | 214 |
| TX airtime (SetTx to TxDone) | 10 421 us | 13 422 us | 14 560 us | 72 | | TX operation latency (routine entry -> observed TxDone) | 10 421 us | 13 422 us | 14 560 us | 72 |
| Programmed repeat delay (frame end -> TX start) | 200 001 us | 200 001 us | 200 008 us | 72 | | Scheduled frame end -> TX-routine entry | 200 001 us | 200 001 us | 200 008 us | 72 |
| Repeated frame length (over-the-air bytes) | 63 | 100 | 113 | 72 | | Repeated frame length (over-the-air bytes) | 63 | 100 | 113 | 72 |
Independent confirmation from the SDR side (raw IQ, same run): observed Independent confirmation from the SDR side (raw IQ, same run): observed
burst duration differs from the computed airtime by 0.2-1.5 ms burst duration differs from the computed airtime by 0.2-1.5 ms
(median 1.2 ms), and firmware TX events align to observed RF within (median 1.2 ms), and firmware TX-operation events align to observed RF
0-3.1 ms (median 2.4 ms). within 0-3.1 ms (median 2.4 ms).
## Derived ## Derived
``` ```
repeat delay accuracy : +1 us to +8 us against a 200 ms setting repeat scheduling accuracy : +1 us to +8 us against a 200 ms setting
(jitter well under 10 us) (at TX-routine entry, not RF onset)
RX deaf time per repeat : ~225.7 ms median RX deaf time per repeat : ~225.7 ms historical median
= 12.2 ms deaf tail = 12.2 ms deaf tail
+ 200.0 ms programmed delay + 200.0 ms programmed delay
+ 13.4 ms TX airtime + 13.4 ms TX operation latency
``` ```
The programmed delay dominates by design; it exists to make SDR The programmed delay dominates by design; it exists to make SDR
@@ -59,31 +59,41 @@ a production repeater.
artefact, not a design target (see docs/STANDARDS_GAPS.md). artefact, not a design target (see docs/STANDARDS_GAPS.md).
- The fixed-255 tail is an SX1262 packet-engine limitation, so it applies - The fixed-255 tail is an SX1262 packet-engine limitation, so it applies
to any SX126x-based design. Budget for it, or implement early-stop RX. to any SX126x-based design. Budget for it, or implement early-stop RX.
- Repeat-delay accuracy of a few microseconds shows the ESP32-S3 side has - TX-routine scheduling jitter is only a few microseconds. Actual RF starts
ample timing margin; timing precision will not be the constraint. after packet setup and buffer transfer, so it must be measured at RF when
exact over-the-air delay matters.
## Airtime measurement vs true channel occupancy ## Computed airtime vs TX operation latency
`tx_airtime_us` and the duty-cycle ledger both use wall time from `SetTx` Current `airtime_us`, cumulative `stats.tx_airtime_us`, and the duty ledger
to the moment `TxDone` is observed. That interval includes SPI round-trips all use computed channel occupancy:
and up to ~1 ms of polling granularity, so it over-states true channel
occupancy:
``` ```
computed airtime, 102-byte payload : (102 * 80 us) + 640 us = 8.8 ms airtime = 48-bit preamble + 16-bit sync + payload at 100 kbps
measured SetTx -> TxDone observed : 13.4 ms median = (radio_payload_bytes * 80 us) + 640 us
102-byte radio payload : 8.8 ms
26-byte beacon payload : 2.72 ms
``` ```
Consequences, both deliberate: `wmbus_tx.tx_operation_us` separately records the longer interval from
entry into the TX routine through observed TxDone. It includes standby,
packet-parameter and buffer SPI transactions, the actual transmission, and
polling/notification latency. Historical firmware mislabeled this interval
as `airtime_us`; its 102-byte median was 13.4 ms.
- The reported duty cycle is conservative (over-counted by roughly 50 %), The distinction matters:
so the 0.1 % guard suppresses slightly earlier than strictly required.
For a compliance guard, erring high is the safe direction.
- Independent confirmation that the real occupancy matches the computed
airtime comes from the SDR side, not the firmware: observed burst
durations in raw IQ differ from the computed airtime by 0.2-1.5 ms
(median 1.2 ms), i.e. the transmission itself is ~9-10 ms for a 100-byte
frame as expected.
A production implementation should budget on computed airtime and use the - Computed occupancy is independent of task scheduling and SPI speed, so
measured value only for latency diagnostics. the duty guard no longer consumes roughly 50% extra budget.
- Operation latency remains useful for diagnosing stalls and TxDone timing,
but is not a regulatory airtime measurement.
- Raw-IQ burst duration remains the independent check. In the historical
102-byte run it differed from computed airtime by 0.2-1.5 ms (median
1.2 ms).
The rolling-hour ledger uses 61 keyed one-minute buckets rather than a
fixed event ring. It therefore cannot forget high-rate events merely
because an event count was exceeded. The oldest overlapping minute is
counted in full, making the result conservatively high by at most one
minute's included traffic at the window boundary.
+26
View File
@@ -4,7 +4,33 @@ idf_component_register(
"sx126x.c" "sx126x.c"
"wmbus.c" "wmbus.c"
"repeater.c" "repeater.c"
"duty_ledger.c"
"console.c" "console.c"
"led.c" "led.c"
"cfg_store.c"
"ui.c"
"debug_history.c"
"wifi_debug.c"
"settings.c"
"settings_http.c"
"wifi_qr.c"
"vendor/qrcodegen.c"
INCLUDE_DIRS "." INCLUDE_DIRS "."
REQUIRES driver esp_timer esp_lcd esp_wifi esp_netif esp_event esp_http_server
nvs_flash bootloader_support json
) )
# Ship compressed assets to retain the existing app/NVS partition layout.
# Python and gzip are host build tools only; ESP32 serves these bytes directly.
foreach(asset index.html dashboard.css dashboard.js identity.js manufacturers.js)
set(source "${CMAKE_CURRENT_SOURCE_DIR}/web/${asset}")
set(compressed "${CMAKE_CURRENT_BINARY_DIR}/web/${asset}.gz")
add_custom_command(
OUTPUT "${compressed}"
COMMAND "${PYTHON}" "${CMAKE_CURRENT_SOURCE_DIR}/../../tools/compress_web_asset.py"
"${source}" "${compressed}"
DEPENDS "${source}" "${CMAKE_CURRENT_SOURCE_DIR}/../../tools/compress_web_asset.py"
VERBATIM
)
target_add_binary_data(${COMPONENT_LIB} "${compressed}" BINARY)
endforeach()
+12
View File
@@ -37,3 +37,15 @@
// Overcurrent protection value from RNode 1.86 ("OCP_TUNED 0x28") // Overcurrent protection value from RNode 1.86 ("OCP_TUNED 0x28")
#define BOARD_SX1262_OCP 0x28 #define BOARD_SX1262_OCP 0x28
// SSD1306 OLED (128x64, I2C 0x3C) + PRG button.
// Pins verified against RTNode-HeltecV4 Display.h / Boards.h for this exact
// board revision (docs/FUTURE_UI.md). Vext is an ACTIVE-LOW external rail
// that powers the display; set once at boot, never toggled mid-TX.
#define BOARD_OLED_SDA 17
#define BOARD_OLED_SCL 18
#define BOARD_OLED_RST 21
#define BOARD_VEXT 36
// GPIO0 is the BOOT strap pin: input only, sampled well after boot,
// debounced. No boot-time gestures (docs/FUTURE_UI.md constraint 3).
#define BOARD_BTN_PRG 0
+56
View File
@@ -0,0 +1,56 @@
// Persistence for the SHORT LIST of config keys allowed to survive power
// cycles: duty_budget_ppm and repeat_delay_ms. Battery-standalone testing
// needs settings that outlive reboots (no host to re-send commands).
// Everything else in g_cfg stays deliberately RAM-only.
//
// Persisted values are restored at boot and logged as a cfg_restore
// event; the OLED config page shows the effective values. A device with a
// persisted duty_budget_ppm of 0 (guard disabled) stays non-compliant
// until explicitly set back -- docs/STANDARDS_GAPS.md.
#include "cfg_store.h"
#include <stdio.h>
#include "nvs_flash.h"
#include "nvs.h"
#define NS "repeater"
static bool s_ready;
void cfg_store_init(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
if (nvs_flash_erase() != ESP_OK) return;
err = nvs_flash_init();
}
s_ready = (err == ESP_OK);
if (!s_ready) {
printf("{\"event\":\"cfg_store\",\"ok\":false,\"err\":%d}\n", (int)err);
fflush(stdout);
}
}
bool cfg_store_load_u32(const char *key, uint32_t *out)
{
if (!s_ready) return false;
nvs_handle_t h;
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) return false;
uint32_t v = 0;
esp_err_t err = nvs_get_u32(h, key, &v);
nvs_close(h);
if (err != ESP_OK) return false;
*out = v;
return true;
}
bool cfg_store_save_u32(const char *key, uint32_t v)
{
if (!s_ready) return false;
nvs_handle_t h;
if (nvs_open(NS, NVS_READWRITE, &h) != ESP_OK) return false;
esp_err_t err = nvs_set_u32(h, key, v);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err == ESP_OK;
}
+13
View File
@@ -0,0 +1,13 @@
// NVS persistence for a SHORT LIST of config keys (see cfg_store.c).
// Current keys: "duty_ppm" (duty_budget_ppm), "delay_ms" (repeat_delay_ms).
#pragma once
#include <stdint.h>
#include <stdbool.h>
#define CFG_KEY_DUTY_PPM "duty_ppm"
#define CFG_KEY_DELAY_MS "delay_ms"
void cfg_store_init(void);
bool cfg_store_load_u32(const char *key, uint32_t *out); // true if present
bool cfg_store_save_u32(const char *key, uint32_t v); // true only after commit
+108 -75
View File
@@ -1,13 +1,16 @@
// Line-based scriptable serial console on USB-Serial-JTAG. // Line-based scriptable serial console on USB-Serial-JTAG.
// Commands (one per line): // Commands (one per line):
// status | stats | clear_stats | radio_status | radio_reset | test_tx // status | stats | clear_stats | radio_status | radio_reset | test_tx | test_tx_t1
// set repeat_delay_ms N | set tx_power N | set repeat_enabled 0|1 // set repeat_delay_ms N | set tx_power N | set repeat_enabled 0|1
// set verbose 0|1 | set whitelist ID[,ID...] | set whitelist clear // set verbose 0|1 | set whitelist ID[,ID...] | set whitelist clear
// set beacon_period_ms N (0=off, uses test_lfield) | set duty_budget_ppm N // set beacon_period_ms N (0=off, uses test_lfield) | set duty_budget_ppm N
// set fem_rx_csd 0|1 | set preamble_bits 0|8|16|24|32 | set test_lfield N
// reboot // reboot
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "esp_system.h" #include "esp_system.h"
@@ -15,7 +18,7 @@
#include "driver/usb_serial_jtag_vfs.h" #include "driver/usb_serial_jtag_vfs.h"
#include "repeater.h" #include "repeater.h"
#include "sx126x.h" #include "settings.h"
static void ack(const char *cmd, bool ok, const char *detail) static void ack(const char *cmd, bool ok, const char *detail)
{ {
@@ -25,81 +28,100 @@ static void ack(const char *cmd, bool ok, const char *detail)
fflush(stdout); fflush(stdout);
} }
static bool parse_integer(const char *text, int32_t *out)
{
const char *digits = text;
if (*digits == '-' || *digits == '+') digits++;
if (!*digits) return false;
for (const char *p = digits; *p; p++) {
if (*p < '0' || *p > '9') return false;
}
char *end;
errno = 0;
long value = strtol(text, &end, 10);
if (errno == ERANGE || *end || value < INT32_MIN || value > INT32_MAX) return false;
*out = (int32_t)value;
return true;
}
static bool parse_whitelist(const char *text, settings_change_t *change)
{
if (strcmp(text, "clear") == 0) return true;
for (;;) {
if (change->whitelist_len == 8) return false;
uint32_t id = 0;
for (unsigned i = 0; i < 8; i++) {
unsigned char c = (unsigned char)*text++;
unsigned digit;
if (c >= '0' && c <= '9') digit = c - '0';
else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10;
else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10;
else return false;
id = (id << 4) | digit;
}
change->whitelist[change->whitelist_len++] = id;
if (!*text) return true;
if (*text++ != ',' || !*text) return false;
}
}
static void handle_set(char *args) static void handle_set(char *args)
{ {
char *key = strtok(args, " "); char *save;
char *val = strtok(NULL, " "); char *key = strtok_r(args, " \t", &save);
if (!key || !val) { ack("set", false, "usage"); return; } char *val = strtok_r(NULL, " \t", &save);
if (!key || !val || strtok_r(NULL, " \t", &save)) {
if (strcmp(key, "repeat_delay_ms") == 0) { ack("set", false, "usage: set KEY VALUE");
long v = strtol(val, NULL, 10); return;
if (v < 20 || v > 200) { ack("set", false, "range 20..200"); return; } }
g_cfg.repeat_delay_ms = (uint32_t)v; static const struct {
ack("set repeat_delay_ms", true, NULL); const char *name;
} else if (strcmp(key, "tx_power") == 0) { settings_key_t key;
long v = strtol(val, NULL, 10); const char *range;
if (v < -9 || v > 14) { ack("set", false, "range -9..14"); return; } } keys[] = {
g_cfg.tx_power_dbm = (int8_t)v; {"repeat_delay_ms", SETTINGS_REPEAT_DELAY_MS, "integer 20..1000"},
repeater_request_radio_reset(); {"tx_power", SETTINGS_TX_POWER, "integer -9..2"},
ack("set tx_power", true, "radio reinit queued"); {"repeat_enabled", SETTINGS_REPEAT_ENABLED, "use 0|1"},
} else if (strcmp(key, "repeat_enabled") == 0) { {"verbose", SETTINGS_VERBOSE, "use 0|1"},
g_cfg.repeat_enabled = (val[0] == '1'); {"fem_rx_csd", SETTINGS_FEM_RX_CSD, "use 0|1"},
ack("set repeat_enabled", true, NULL); {"preamble_bits", SETTINGS_PREAMBLE_BITS, "use 0|8|16|24|32"},
} else if (strcmp(key, "duty_budget_ppm") == 0) { {"duty_budget_ppm", SETTINGS_DUTY_BUDGET_PPM, "integer 0..100000 ppm"},
long v = strtol(val, NULL, 10); {"test_lfield", SETTINGS_TEST_LFIELD, "integer 19..200"},
if (v < 0 || v > 100000) { ack("set", false, "range 0..100000 ppm"); return; } {"whitelist", SETTINGS_WHITELIST, "clear or 1..8 unique eight-hex-digit IDs"},
g_cfg.duty_budget_ppm = (uint32_t)v; {"beacon_period_ms", SETTINGS_BEACON_PERIOD_MS, "integer 0 or 250..600000 ms"},
ack("set duty_budget_ppm", true, v == 0 ? "guard disabled" : NULL); };
} else if (strcmp(key, "beacon_period_ms") == 0) { const size_t count = sizeof(keys) / sizeof(keys[0]);
long v = strtol(val, NULL, 10); size_t index = 0;
if (v != 0 && (v < 250 || v > 600000)) { ack("set", false, "0 or 250..600000 ms"); return; } while (index < count && strcmp(key, keys[index].name) != 0) index++;
g_cfg.beacon_period_ms = (uint32_t)v; if (index == count) {
ack("set beacon_period_ms", true, v == 0 ? "beacon off" : NULL);
} else if (strcmp(key, "preamble_bits") == 0) {
long v = strtol(val, NULL, 10);
uint8_t code;
switch (v) {
case 0: code = 0x00; break;
case 8: code = 0x04; break;
case 16: code = 0x05; break;
case 24: code = 0x06; break;
case 32: code = 0x07; break;
default: ack("set", false, "use 0|8|16|24|32"); return;
}
sx126x_set_preamble_detect(code);
repeater_request_radio_reset();
ack("set preamble_bits", true, "radio reinit queued");
} else if (strcmp(key, "pa_low") == 0) {
sx126x_set_pa_low(val[0] == '1');
repeater_request_radio_reset();
ack("set pa_low", true, "radio reinit queued");
} else if (strcmp(key, "test_lfield") == 0) {
long v = strtol(val, NULL, 10);
if (v < 19 || v > 200) { ack("set", false, "range 19..200"); return; }
repeater_set_test_lfield((uint8_t)v);
ack("set test_lfield", true, NULL);
} else if (strcmp(key, "fem_rx_csd") == 0) {
fem_set_rx_csd(val[0] == '1');
ack("set fem_rx_csd", true, "applies at next RX entry");
} else if (strcmp(key, "verbose") == 0) {
g_cfg.verbose = (val[0] == '1');
ack("set verbose", true, NULL);
} else if (strcmp(key, "whitelist") == 0) {
if (strcmp(val, "clear") == 0) {
g_cfg.whitelist_len = 0;
ack("set whitelist", true, "cleared");
return;
}
int n = 0;
for (char *tok = strtok(val, ","); tok && n < 8; tok = strtok(NULL, ",")) {
// meter ID as printed (BCD hex digits) -> stored LE uint32
uint32_t id = (uint32_t)strtoul(tok, NULL, 16);
g_cfg.whitelist[n++] = id;
}
g_cfg.whitelist_len = n;
ack("set whitelist", true, NULL);
} else {
ack("set", false, "unknown key"); ack("set", false, "unknown key");
return;
}
settings_change_t change = {.key = keys[index].key};
bool parsed;
if (change.key == SETTINGS_WHITELIST) {
parsed = parse_whitelist(val, &change);
} else if (change.key == SETTINGS_REPEAT_ENABLED || change.key == SETTINGS_VERBOSE
|| change.key == SETTINGS_FEM_RX_CSD) {
parsed = strcmp(val, "0") == 0 || strcmp(val, "1") == 0;
change.value = val[0] == '1';
} else {
parsed = parse_integer(val, &change.value);
}
settings_result_t result = parsed ? settings_update(&change, 0, NULL) : SETTINGS_INVALID;
char command[48];
snprintf(command, sizeof(command), "set %s", keys[index].name);
switch (result) {
case SETTINGS_OK:
ack(command, true,
change.key == SETTINGS_REPEAT_DELAY_MS || change.key == SETTINGS_DUTY_BUDGET_PPM
? "persisted; accepted for radio loop boundary"
: "accepted for radio loop boundary");
break;
case SETTINGS_INVALID: ack(command, false, keys[index].range); break;
case SETTINGS_CONFLICT: ack(command, false, "settings changed; reload status"); break;
case SETTINGS_STORAGE_ERROR: ack(command, false, "storage failed; settings unchanged"); break;
case SETTINGS_BUSY: ack(command, false, "settings busy; unchanged"); break;
} }
} }
@@ -112,6 +134,13 @@ static void console_task(void *arg)
vTaskDelay(pdMS_TO_TICKS(50)); vTaskDelay(pdMS_TO_TICKS(50));
continue; continue;
} }
if (!strpbrk(line, "\r\n")) {
// Never apply the valid-looking prefix of an oversized command.
int c;
while ((c = getchar()) != '\n' && c != '\r' && c != EOF) {}
ack("set", false, "line too long");
continue;
}
line[strcspn(line, "\r\n")] = 0; line[strcspn(line, "\r\n")] = 0;
if (line[0] == 0) continue; if (line[0] == 0) continue;
@@ -144,13 +173,17 @@ static void console_task(void *arg)
repeater_request_test_tx(); repeater_request_test_tx();
ack("test_tx", true, "queued"); ack("test_tx", true, "queued");
} }
else if (strcmp(line, "test_tx_t1") == 0) {
repeater_request_test_tx_t1();
ack("test_tx_t1", true, "queued");
}
else if (strncmp(line, "set ", 4) == 0) handle_set(line + 4); else if (strncmp(line, "set ", 4) == 0) handle_set(line + 4);
else if (strcmp(line, "reboot") == 0) { else if (strcmp(line, "reboot") == 0) {
ack("reboot", true, NULL); ack("reboot", true, NULL);
vTaskDelay(pdMS_TO_TICKS(100)); vTaskDelay(pdMS_TO_TICKS(100));
esp_restart(); esp_restart();
} }
else ack(line, false, "unknown command"); else ack("unknown", false, "unknown command");
} }
} }
+117
View File
@@ -0,0 +1,117 @@
#include "debug_history.h"
#include <string.h>
#include "freertos/FreeRTOS.h"
// One radio writer; HTTP readers only copy under this lock. Every critical
// section is bounded by one row/status copy, never a traversal or formatting.
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static debug_record_t s_rows[DEBUG_HISTORY_CAPACITY];
static debug_status_t s_status;
static uint32_t s_latest;
static uint32_t oldest_id(uint32_t latest)
{
return latest > DEBUG_HISTORY_CAPACITY
? latest - DEBUG_HISTORY_CAPACITY + 1 : 1;
}
void debug_history_record(const debug_record_t *record)
{
// Classify outside the critical section. These boot-lifetime counters are
// independent of the resettable console/OLED statistics and ring eviction.
const bool received = strcmp(record->source, "rx") == 0;
const bool completed = strcmp(record->outcome, "ok") == 0
|| strcmp(record->outcome, "ok_polled") == 0;
const bool failed = strcmp(record->outcome, "encode_failed") == 0
|| strcmp(record->outcome, "start_failed") == 0
|| strcmp(record->outcome, "radio_timeout") == 0
|| strcmp(record->outcome, "irq_timeout") == 0;
const bool skipped = strcmp(record->outcome, "repeat_disabled") == 0
|| strcmp(record->outcome, "whitelist") == 0
|| strcmp(record->outcome, "duplicate") == 0
|| strcmp(record->outcome, "duty_cycle") == 0
|| strcmp(record->outcome, "hop_policy") == 0;
portENTER_CRITICAL(&s_lock);
const uint32_t id = ++s_latest;
debug_record_t *slot = &s_rows[(id - 1) % DEBUG_HISTORY_CAPACITY];
*slot = *record;
slot->id = id;
if (received) {
if (record->crc_ok) {
s_status.rx_valid++;
s_status.last_rx_us = record->timestamp_us;
if (completed) s_status.repeats_completed++;
else if (failed) s_status.tx_failed++;
else if (skipped) s_status.skipped++;
} else {
s_status.rx_rejected++;
}
}
// Synthetic TX is visible in the last-TX age, never in RX/repeat totals.
if (completed) s_status.last_tx_us = record->tx_done_us;
portEXIT_CRITICAL(&s_lock);
}
void debug_history_publish_status(const debug_status_t *status)
{
portENTER_CRITICAL(&s_lock);
// Deliberately do not overwrite counters or last-event timestamps owned
// by record(), even if this health sample predates a finalized RX.
s_status.sampled_at_us = status->sampled_at_us;
s_status.heartbeat_us = status->heartbeat_us;
s_status.duty_used_us = status->duty_used_us;
s_status.duty_budget_us = status->duty_budget_us;
s_status.recoveries = status->recoveries;
s_status.repeat_delay_ms = status->repeat_delay_ms;
s_status.chip_mode = status->chip_mode;
s_status.config_intact = status->config_intact;
s_status.repeat_enabled = status->repeat_enabled;
portEXIT_CRITICAL(&s_lock);
}
void debug_history_snapshot(uint32_t after, debug_snapshot_t *out)
{
portENTER_CRITICAL(&s_lock);
out->cursor = s_latest;
out->status = s_status;
portEXIT_CRITICAL(&s_lock);
out->oldest_id = out->cursor ? oldest_id(out->cursor) : 0;
out->evicted = out->cursor > DEBUG_HISTORY_CAPACITY
? out->cursor - DEBUG_HISTORY_CAPACITY : 0;
out->reset = after > out->cursor
|| (after != 0 && after < out->evicted);
out->count = 0;
if (!out->cursor) return;
uint32_t id = after == 0 || out->reset ? out->oldest_id : after + 1;
// cursor fixes the upper bound at entry, so a busy producer cannot make
// this read unbounded. The immutable ID is a slot-generation guard: an
// overwritten slot must never be returned as the originally requested RX.
while (id != 0 && id <= out->cursor) {
portENTER_CRITICAL(&s_lock);
const debug_record_t *slot = &s_rows[(id - 1) % DEBUG_HISTORY_CAPACITY];
const bool present = slot->id == id;
if (present) out->rows[out->count] = *slot;
const uint32_t oldest = present ? 0 : oldest_id(s_latest);
portEXIT_CRITICAL(&s_lock);
if (present) {
out->count++;
id++;
} else {
// Concurrent eviction: discard the copied prefix and return only
// a contiguous surviving suffix of the entry-time window. A fully
// evicted window returns no rows; the next cursor request catches
// up normally. Never retry or hold the producer while copying 256
// rows. oldest_id/evicted now describe the observed loss boundary.
out->reset = true;
out->count = 0;
out->oldest_id = oldest;
out->evicted = oldest - 1;
id = oldest;
}
}
}
+70
View File
@@ -0,0 +1,70 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define DEBUG_HISTORY_CAPACITY 256
// Immutable final outcome. String pointers must refer to static literals.
// Identity is the link-layer sender, never an inferred transport-layer meter.
typedef struct {
uint32_t id;
int64_t timestamp_us;
int64_t tx_start_us;
int64_t tx_done_us;
uint32_t meter_id;
uint32_t hash;
uint16_t manufacturer;
uint16_t length;
uint8_t version;
uint8_t device_type;
int8_t rssi_dbm;
bool identity_present;
bool crc_ok;
const char *source; // rx, beacon, test
const char *mode; // C1, T1, unknown
const char *format; // A, B, unknown
const char *reception; // ok, crc_failed, bad_length, undecodable,
// t1_too_long, rx_read_failed, not_applicable
const char *outcome; // ok, ok_polled, crc_failed, bad_length, undecodable,
// t1_too_long, rx_read_failed, repeat_disabled,
// whitelist, duplicate, duty_cycle, hop_policy,
// encode_failed, start_failed, radio_timeout, irq_timeout
} debug_record_t;
typedef struct {
int64_t sampled_at_us;
int64_t heartbeat_us;
int64_t last_rx_us; // last CRC-valid reception
int64_t last_tx_us; // last completed transmission (includes synthetic)
uint64_t rx_valid;
uint64_t rx_rejected;
uint64_t repeats_completed;
uint64_t tx_failed; // received repeats only
uint64_t skipped; // valid received frames intentionally not repeated
uint64_t duty_used_us;
uint64_t duty_budget_us; // zero means disabled
uint32_t recoveries;
uint32_t repeat_delay_ms;
uint8_t chip_mode;
bool config_intact;
bool repeat_enabled;
} debug_status_t;
typedef struct {
uint32_t cursor;
uint32_t oldest_id;
uint32_t evicted;
bool reset; // caller must discard retained rows before merging
size_t count;
debug_status_t status;
debug_record_t rows[DEBUG_HISTORY_CAPACITY]; // ascending id
} debug_snapshot_t;
// Single writer: radio task. No allocation, formatting, or network operations.
void debug_history_record(const debug_record_t *record);
// Radio publishes health/config/duty; record() owns counters and last-event ages.
void debug_history_publish_status(const debug_status_t *status);
// HTTP task owns the output buffer. No lock held while formatting or sending.
void debug_history_snapshot(uint32_t after, debug_snapshot_t *out);
+48
View File
@@ -0,0 +1,48 @@
#include "duty_ledger.h"
#include <limits.h>
#include <stdbool.h>
uint64_t duty_ledger_used(const duty_ledger_t *ledger, int64_t now_us)
{
if (now_us < 0) return 0;
const uint64_t now = (uint64_t)now_us;
const bool has_full_window = now >= DUTY_LEDGER_WINDOW_US;
const uint64_t cutoff = has_full_window ? now - DUTY_LEDGER_WINDOW_US : 0;
uint64_t sum = 0;
for (int i = 0; i < DUTY_LEDGER_BUCKETS; i++) {
const duty_ledger_bucket_t *bucket = &ledger->buckets[i];
if (bucket->minute_key == 0) continue;
const uint64_t minute = bucket->minute_key - 1;
const uint64_t start = minute * DUTY_LEDGER_BUCKET_US;
if (start > now) continue;
if (has_full_window && start + DUTY_LEDGER_BUCKET_US <= cutoff) continue;
if (UINT64_MAX - sum < bucket->airtime_us) return UINT64_MAX;
sum += bucket->airtime_us;
}
return sum;
}
void duty_ledger_record(duty_ledger_t *ledger, int64_t now_us,
uint32_t airtime_us)
{
if (now_us < 0 || airtime_us == 0) return;
const uint64_t minute = (uint64_t)now_us / DUTY_LEDGER_BUCKET_US;
duty_ledger_bucket_t *bucket = &ledger->buckets[minute % DUTY_LEDGER_BUCKETS];
const uint64_t key = minute + 1;
if (bucket->minute_key != key) {
bucket->minute_key = key;
bucket->airtime_us = 0;
}
if (UINT64_MAX - bucket->airtime_us < airtime_us) {
bucket->airtime_us = UINT64_MAX;
} else {
bucket->airtime_us += airtime_us;
}
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <stdint.h>
#define DUTY_LEDGER_BUCKET_US 60000000ULL
#define DUTY_LEDGER_WINDOW_US 3600000000ULL
#define DUTY_LEDGER_BUCKETS 61
typedef struct {
uint64_t minute_key; // uptime minute + 1; zero means unused
uint64_t airtime_us;
} duty_ledger_bucket_t;
typedef struct {
duty_ledger_bucket_t buckets[DUTY_LEDGER_BUCKETS];
} duty_ledger_t;
// Minute buckets conservatively include the whole oldest overlapping minute.
// The result can over-count by less than one minute, but never drops airtime
// that may still be inside the rolling-hour window.
uint64_t duty_ledger_used(const duty_ledger_t *ledger, int64_t now_us);
void duty_ledger_record(duty_ledger_t *ledger, int64_t now_us,
uint32_t airtime_us);
+110
View File
@@ -0,0 +1,110 @@
// Classic public-domain 5x7 bitmap font, ASCII 0x20..0x7E.
// Each glyph is 5 column bytes; bit 0 = top pixel row. Rendered into a
// 6x8 cell (1 blank spacer column, 1 blank pixel row).
// Host-verified by firmware/test/test_font_render.c (ASCII-art dump).
#pragma once
#include <stdint.h>
#define FONT5X7_FIRST 0x20
#define FONT5X7_LAST 0x7E
#define FONT5X7_W 5
#define FONT5X7_H 7
static const uint8_t font5x7[95][5] = {
{0x00, 0x00, 0x00, 0x00, 0x00}, // ' '
{0x00, 0x00, 0x5F, 0x00, 0x00}, // '!'
{0x00, 0x07, 0x00, 0x07, 0x00}, // '"'
{0x14, 0x7F, 0x14, 0x7F, 0x14}, // '#'
{0x24, 0x2A, 0x7F, 0x2A, 0x12}, // '$'
{0x23, 0x13, 0x08, 0x64, 0x62}, // '%'
{0x36, 0x49, 0x55, 0x22, 0x50}, // '&'
{0x00, 0x05, 0x03, 0x00, 0x00}, // '\''
{0x00, 0x1C, 0x22, 0x41, 0x00}, // '('
{0x00, 0x41, 0x22, 0x1C, 0x00}, // ')'
{0x14, 0x08, 0x3E, 0x08, 0x14}, // '*'
{0x08, 0x08, 0x3E, 0x08, 0x08}, // '+'
{0x00, 0x50, 0x30, 0x00, 0x00}, // ','
{0x08, 0x08, 0x08, 0x08, 0x08}, // '-'
{0x00, 0x60, 0x60, 0x00, 0x00}, // '.'
{0x20, 0x10, 0x08, 0x04, 0x02}, // '/'
{0x3E, 0x51, 0x49, 0x45, 0x3E}, // '0'
{0x00, 0x42, 0x7F, 0x40, 0x00}, // '1'
{0x42, 0x61, 0x51, 0x49, 0x46}, // '2'
{0x21, 0x41, 0x45, 0x4B, 0x31}, // '3'
{0x18, 0x14, 0x12, 0x7F, 0x10}, // '4'
{0x27, 0x45, 0x45, 0x45, 0x39}, // '5'
{0x3C, 0x4A, 0x49, 0x49, 0x30}, // '6'
{0x01, 0x71, 0x09, 0x05, 0x03}, // '7'
{0x36, 0x49, 0x49, 0x49, 0x36}, // '8'
{0x06, 0x49, 0x49, 0x29, 0x1E}, // '9'
{0x00, 0x36, 0x36, 0x00, 0x00}, // ':'
{0x00, 0x56, 0x36, 0x00, 0x00}, // ';'
{0x08, 0x14, 0x22, 0x41, 0x00}, // '<'
{0x14, 0x14, 0x14, 0x14, 0x14}, // '='
{0x00, 0x41, 0x22, 0x14, 0x08}, // '>'
{0x02, 0x01, 0x51, 0x09, 0x06}, // '?'
{0x32, 0x49, 0x79, 0x41, 0x3E}, // '@'
{0x7E, 0x11, 0x11, 0x11, 0x7E}, // 'A'
{0x7F, 0x49, 0x49, 0x49, 0x36}, // 'B'
{0x3E, 0x41, 0x41, 0x41, 0x22}, // 'C'
{0x7F, 0x41, 0x41, 0x22, 0x1C}, // 'D'
{0x7F, 0x49, 0x49, 0x49, 0x41}, // 'E'
{0x7F, 0x09, 0x09, 0x09, 0x01}, // 'F'
{0x3E, 0x41, 0x49, 0x49, 0x7A}, // 'G'
{0x7F, 0x08, 0x08, 0x08, 0x7F}, // 'H'
{0x00, 0x41, 0x7F, 0x41, 0x00}, // 'I'
{0x20, 0x40, 0x41, 0x3F, 0x01}, // 'J'
{0x7F, 0x08, 0x14, 0x22, 0x41}, // 'K'
{0x7F, 0x40, 0x40, 0x40, 0x40}, // 'L'
{0x7F, 0x02, 0x0C, 0x02, 0x7F}, // 'M'
{0x7F, 0x04, 0x08, 0x10, 0x7F}, // 'N'
{0x3E, 0x41, 0x41, 0x41, 0x3E}, // 'O'
{0x7F, 0x09, 0x09, 0x09, 0x06}, // 'P'
{0x3E, 0x41, 0x51, 0x21, 0x5E}, // 'Q'
{0x7F, 0x09, 0x19, 0x29, 0x46}, // 'R'
{0x46, 0x49, 0x49, 0x49, 0x31}, // 'S'
{0x01, 0x01, 0x7F, 0x01, 0x01}, // 'T'
{0x3F, 0x40, 0x40, 0x40, 0x3F}, // 'U'
{0x1F, 0x20, 0x40, 0x20, 0x1F}, // 'V'
{0x3F, 0x40, 0x38, 0x40, 0x3F}, // 'W'
{0x63, 0x14, 0x08, 0x14, 0x63}, // 'X'
{0x07, 0x08, 0x70, 0x08, 0x07}, // 'Y'
{0x61, 0x51, 0x49, 0x45, 0x43}, // 'Z'
{0x00, 0x7F, 0x41, 0x41, 0x00}, // '['
{0x02, 0x04, 0x08, 0x10, 0x20}, // '\\'
{0x00, 0x41, 0x41, 0x7F, 0x00}, // ']'
{0x04, 0x02, 0x01, 0x02, 0x04}, // '^'
{0x40, 0x40, 0x40, 0x40, 0x40}, // '_'
{0x00, 0x01, 0x02, 0x04, 0x00}, // '`'
{0x20, 0x54, 0x54, 0x54, 0x78}, // 'a'
{0x7F, 0x48, 0x44, 0x44, 0x38}, // 'b'
{0x38, 0x44, 0x44, 0x44, 0x20}, // 'c'
{0x38, 0x44, 0x44, 0x48, 0x7F}, // 'd'
{0x38, 0x54, 0x54, 0x54, 0x18}, // 'e'
{0x08, 0x7E, 0x09, 0x01, 0x02}, // 'f'
{0x0C, 0x52, 0x52, 0x52, 0x3E}, // 'g'
{0x7F, 0x08, 0x04, 0x04, 0x78}, // 'h'
{0x00, 0x44, 0x7D, 0x40, 0x00}, // 'i'
{0x20, 0x40, 0x44, 0x3D, 0x00}, // 'j'
{0x7F, 0x10, 0x28, 0x44, 0x00}, // 'k'
{0x00, 0x41, 0x7F, 0x40, 0x00}, // 'l'
{0x7C, 0x04, 0x18, 0x04, 0x78}, // 'm'
{0x7C, 0x08, 0x04, 0x04, 0x78}, // 'n'
{0x38, 0x44, 0x44, 0x44, 0x38}, // 'o'
{0x7C, 0x14, 0x14, 0x14, 0x08}, // 'p'
{0x08, 0x14, 0x14, 0x18, 0x7C}, // 'q'
{0x7C, 0x08, 0x04, 0x04, 0x08}, // 'r'
{0x48, 0x54, 0x54, 0x54, 0x20}, // 's'
{0x04, 0x3F, 0x44, 0x40, 0x20}, // 't'
{0x3C, 0x40, 0x40, 0x20, 0x7C}, // 'u'
{0x1C, 0x20, 0x40, 0x20, 0x1C}, // 'v'
{0x3C, 0x40, 0x30, 0x40, 0x3C}, // 'w'
{0x44, 0x28, 0x10, 0x28, 0x44}, // 'x'
{0x0C, 0x50, 0x50, 0x50, 0x3C}, // 'y'
{0x44, 0x64, 0x54, 0x4C, 0x44}, // 'z'
{0x00, 0x08, 0x36, 0x41, 0x00}, // '{'
{0x00, 0x00, 0x7F, 0x00, 0x00}, // '|'
{0x00, 0x41, 0x36, 0x08, 0x00}, // '}'
{0x08, 0x04, 0x08, 0x10, 0x08}, // '~'
};
+8
View File
@@ -5,6 +5,10 @@
#include "esp_timer.h" #include "esp_timer.h"
#include "repeater.h" #include "repeater.h"
#include "led.h" #include "led.h"
#include "ui.h"
#include "cfg_store.h"
#include "settings.h"
#include "wifi_debug.h"
void console_start(void); void console_start(void);
@@ -14,6 +18,10 @@ void app_main(void)
"\"reset_reason\":%d}\n", __DATE__, __TIME__, (int)esp_reset_reason()); "\"reset_reason\":%d}\n", __DATE__, __TIME__, (int)esp_reset_reason());
fflush(stdout); fflush(stdout);
led_init(); // solid ON = powered, initialising led_init(); // solid ON = powered, initialising
cfg_store_init();
settings_init();
console_start(); console_start();
repeater_start(); // led_boot_done() fires once the radio is in RX repeater_start(); // led_boot_done() fires once the radio is in RX
wifi_debug_init(); // control task only; AP is off until OLED enables it
ui_start(); // OLED + button; non-fatal if absent
} }
+492 -129
View File
@@ -3,6 +3,9 @@
#include "wmbus.h" #include "wmbus.h"
#include "board.h" #include "board.h"
#include "led.h" #include "led.h"
#include "duty_ledger.h"
#include "debug_history.h"
#include "settings.h"
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
@@ -35,63 +38,129 @@ repeater_cfg_t g_cfg = {
#else #else
.verbose = false, .verbose = false,
#endif #endif
.fem_rx_csd = true,
.preamble_bits = 8,
.test_lfield = 19,
.whitelist = {0}, .whitelist = {0},
.whitelist_len = 0, .whitelist_len = 0,
}; };
repeater_stats_t g_stats; repeater_stats_t g_stats;
repeater_ui_t g_ui;
static TaskHandle_t s_task; static TaskHandle_t s_task;
static volatile int64_t s_irq_ts; static volatile int64_t s_irq_ts;
static volatile bool s_want_radio_reset; static volatile bool s_want_radio_reset;
static volatile bool s_want_test_tx; static volatile bool s_want_test_tx;
static volatile bool s_want_test_tx_t1;
static volatile bool s_want_probe; static volatile bool s_want_probe;
static volatile bool s_want_test_burst; static volatile bool s_want_test_burst;
static volatile int s_inject; // 1 = standby, 2 = sleep (config loss) static volatile int s_inject; // 1 = standby, 2 = sleep (config loss)
static uint8_t s_test_access_nr; static uint8_t s_test_access_nr;
static uint8_t s_test_lfield = 19;
static uint32_t s_seq; static uint32_t s_seq;
static int64_t s_last_beacon; static int64_t s_last_beacon;
static struct { uint32_t hash; int64_t ts; } s_dup[DUP_RING]; static struct { uint32_t hash; int64_t ts; } s_dup[DUP_RING];
static int s_dup_idx; static int s_dup_idx;
// Rolling-hour TX airtime ledger for the duty-cycle guard. At 0.1 % and // Minute buckets retain every transmission in the rolling hour without an
// ~13 ms per repeat the hourly ceiling is ~270 transmissions, so this ring // event-count limit. The oldest partial minute is included in full, so the
// cannot overflow within the window. // compliance guard can over-count slightly but cannot silently under-count.
#define DUTY_RING 384 static duty_ledger_t s_duty;
#define DUTY_WINDOW_US 3600000000LL
static struct { int64_t ts; uint32_t airtime_us; } s_duty[DUTY_RING]; // Cached radio-task health. heartbeat_us is the last existing hardware probe;
static int s_duty_idx; // sampled_at_us also advances on idle loops without any new SPI/UI queries.
// Recovery count is boot-lifetime, independent of clear_stats.
static debug_status_t s_debug_status;
static void publish_debug_status(void)
{
int64_t now = esp_timer_get_time();
s_debug_status.sampled_at_us = now;
s_debug_status.duty_used_us = duty_ledger_used(&s_duty, now);
s_debug_status.duty_budget_us = (uint64_t)g_cfg.duty_budget_ppm
* DUTY_LEDGER_WINDOW_US / 1000000ULL;
s_debug_status.repeat_delay_ms = g_cfg.repeat_delay_ms;
s_debug_status.repeat_enabled = g_cfg.repeat_enabled;
debug_history_publish_status(&s_debug_status);
}
static debug_record_t debug_record_init(const char *source, const char *mode,
const char *format, int64_t timestamp_us)
{
// Zero timestamps mean no TX attempt; zero identity fields are absent
// unless identity_present is set. Synthetic RSSI/CRC are not measurements.
return (debug_record_t) {
.timestamp_us = timestamp_us,
.source = source,
.mode = mode,
.format = format,
.reception = "not_applicable",
.outcome = "encode_failed",
};
}
static void debug_identity(debug_record_t *record, const uint8_t *frame, int length)
{
// Link-layer L,C,M,A header only, before any hop mutation. Rejected
// frames may carry an untrusted identity, but never read beyond capture.
if (length < 10) return;
record->manufacturer = (uint16_t)frame[2] | ((uint16_t)frame[3] << 8);
record->meter_id = (uint32_t)frame[4] | ((uint32_t)frame[5] << 8)
| ((uint32_t)frame[6] << 16) | ((uint32_t)frame[7] << 24);
record->version = frame[8];
record->device_type = frame[9];
record->identity_present = true;
}
static void debug_frame(debug_record_t *record, const uint8_t *frame, int length)
{
record->length = (uint16_t)length;
record->hash = wmbus_hash(frame, (size_t)length);
debug_identity(record, frame, length);
}
static void debug_rx_rejected(debug_record_t *record, const char *reason,
const uint8_t *bytes, int length)
{
record->reception = reason;
record->outcome = reason;
// Undecoded captures hash their available physical bytes; decoded rows
// hash the original complete frame including CRCs, excluding mode bytes.
// length always counts the bytes hashed, not an untrusted declared size.
if (length > 0) {
record->length = (uint16_t)length;
record->hash = wmbus_hash(bytes, (size_t)length);
}
}
static uint32_t tx_airtime_us(int payload_bytes)
{
// 48-bit preamble + 16-bit sync + payload at 100 kbps.
return (uint32_t)(payload_bytes * US_PER_BYTE + 640);
}
static uint64_t duty_used_us(int64_t now) static uint64_t duty_used_us(int64_t now)
{ {
uint64_t sum = 0; return duty_ledger_used(&s_duty, now);
for (int i = 0; i < DUTY_RING; i++) {
if (s_duty[i].airtime_us && now - s_duty[i].ts < DUTY_WINDOW_US) {
sum += s_duty[i].airtime_us;
}
}
return sum;
} }
static void duty_record(int64_t now, uint32_t airtime_us) uint64_t repeater_duty_used_us(void)
{ {
s_duty[s_duty_idx].ts = now; return duty_ledger_used(&s_duty, esp_timer_get_time());
s_duty[s_duty_idx].airtime_us = airtime_us;
s_duty_idx = (s_duty_idx + 1) % DUTY_RING;
} }
// Would transmitting `bytes` now exceed the configured rolling-hour budget? // Would transmitting `bytes` now exceed the configured rolling-hour budget?
static bool duty_would_exceed(int64_t now, int bytes, uint64_t *used_out, static bool duty_would_exceed(int64_t now, int bytes, uint64_t *used_out,
uint64_t *budget_out) uint64_t *budget_out)
{ {
uint64_t budget_us = (uint64_t)g_cfg.duty_budget_ppm * 3600000000ULL / 1000000ULL; uint64_t budget_us = (uint64_t)g_cfg.duty_budget_ppm
* DUTY_LEDGER_WINDOW_US / 1000000ULL;
uint64_t used = duty_used_us(now); uint64_t used = duty_used_us(now);
uint32_t want = (uint32_t)(bytes * US_PER_BYTE + 640); uint32_t want = tx_airtime_us(bytes);
if (used_out) *used_out = used; if (used_out) *used_out = used;
if (budget_out) *budget_out = budget_us; if (budget_out) *budget_out = budget_us;
if (g_cfg.duty_budget_ppm == 0) return false; if (g_cfg.duty_budget_ppm == 0) return false;
return (used + want) > budget_us; return used > budget_us || want > budget_us - used;
} }
// ------------------------------------------------------------------ logging // ------------------------------------------------------------------ logging
@@ -116,6 +185,11 @@ static void irq_cb(int64_t ts)
portYIELD_FROM_ISR(hp); portYIELD_FROM_ISR(hp);
} }
static uint8_t preamble_detect_code(uint8_t bits)
{
return bits ? (uint8_t)(bits / 8 + 3) : 0;
}
static bool radio_full_init(void) static bool radio_full_init(void)
{ {
sx126x_diag_t diag; sx126x_diag_t diag;
@@ -137,6 +211,9 @@ static bool radio_full_init(void)
diag.device_errors, diag.chip_mode, diag.device_errors, diag.chip_mode,
(int)g_cfg.tx_power_dbm, (int)g_cfg.tx_power_dbm,
cfg_ok ? "ok" : "fail"); cfg_ok ? "ok" : "fail");
s_debug_status.chip_mode = diag.chip_mode;
s_debug_status.config_intact = cfg_ok;
publish_debug_status();
return cfg_ok; return cfg_ok;
} }
@@ -145,6 +222,7 @@ static bool radio_full_init(void)
static bool recover(const char *reason, int level) static bool recover(const char *reason, int level)
{ {
g_stats.recoveries++; g_stats.recoveries++;
s_debug_status.recoveries++;
led_notify_fault(); led_notify_fault();
bool ok = false; bool ok = false;
switch (level) { switch (level) {
@@ -174,6 +252,9 @@ static bool recover(const char *reason, int level)
ok = radio_full_init() && sx126x_set_rx() && sx126x_config_intact(); ok = radio_full_init() && sx126x_set_rx() && sx126x_config_intact();
break; break;
default: default:
s_debug_status.chip_mode = 0;
s_debug_status.config_intact = false;
publish_debug_status();
LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d," LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d,"
"\"result\":\"mcu_reset\"", reason, level); "\"result\":\"mcu_reset\"", reason, level);
fflush(stdout); fflush(stdout);
@@ -182,6 +263,10 @@ static bool recover(const char *reason, int level)
} }
LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d," LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d,"
"\"result\":\"%s\"", reason, level, ok ? "rx_restored" : "failed"); "\"result\":\"%s\"", reason, level, ok ? "rx_restored" : "failed");
// Reuse the ladder's existing observations; zero means unknown on failure.
s_debug_status.chip_mode = ok ? 0x5 : 0;
s_debug_status.config_intact = ok;
publish_debug_status();
return ok; return ok;
} }
@@ -221,15 +306,6 @@ static bool whitelist_pass(const uint8_t *frame)
return false; return false;
} }
// Wait for DIO1 with timeout; returns IRQ mask (0 on timeout).
static uint16_t wait_irq(uint32_t timeout_ms)
{
if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(timeout_ms)) == 0) return 0;
uint16_t irq = sx126x_get_irq();
sx126x_clear_irq(irq);
return irq;
}
static void precise_delay_until(int64_t target_us) static void precise_delay_until(int64_t target_us)
{ {
int64_t now = esp_timer_get_time(); int64_t now = esp_timer_get_time();
@@ -240,18 +316,26 @@ static void precise_delay_until(int64_t target_us)
// ------------------------------------------------------------------ TX // ------------------------------------------------------------------ TX
// Transmit mode bytes + frame. Returns result string for logging. // Transmit a physical radio payload. For C-mode that is mode bytes +
static const char *do_tx(const uint8_t *payload, int payload_len, // frame; for T-mode the 3-of-6 coded stream. Returns result string.
int64_t *tx_start_us, int64_t *tx_done_us) static const char *do_tx_raw(const uint8_t *payload, int payload_len,
bool t1, int64_t *tx_start_us, int64_t *tx_done_us,
debug_record_t *record)
{ {
g_stats.tx_attempts++; g_stats.tx_attempts++;
// Software TX-operation start includes the driver's SPI setup. Completion
// is the actual IRQ timestamp or the time polling observes the result,
// never a delay/airtime estimate. No RF-start timestamp is exposed by SPI.
*tx_start_us = esp_timer_get_time(); *tx_start_us = esp_timer_get_time();
if (!sx126x_start_tx(payload, (uint8_t)payload_len)) { *tx_done_us = *tx_start_us;
record->tx_start_us = *tx_start_us;
if (!sx126x_start_tx_mode(payload, (uint8_t)payload_len, t1)) {
record->tx_done_us = esp_timer_get_time();
g_stats.tx_failures++; g_stats.tx_failures++;
return "start_failed"; return "start_failed";
} }
// airtime: 48 bit preamble + 16 bit sync + payload -> ~80us/byte + 640 const uint32_t airtime_us = tx_airtime_us(payload_len);
uint32_t airtime_ms = (payload_len * US_PER_BYTE + 640) / 1000; const uint32_t airtime_ms = (airtime_us + 999) / 1000;
// Instrumented wait: poll IRQ flags, DIO1 level and chip mode while // Instrumented wait: poll IRQ flags, DIO1 level and chip mode while
// also honoring the ISR notification. Gives ground truth about the // also honoring the ISR notification. Gives ground truth about the
// TX sequence even when the interrupt path is broken. // TX sequence even when the interrupt path is broken.
@@ -270,6 +354,12 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
vTaskDelay(pdMS_TO_TICKS(1)); vTaskDelay(pdMS_TO_TICKS(1));
} }
*tx_done_us = notify_seen ? s_irq_ts : esp_timer_get_time(); *tx_done_us = notify_seen ? s_irq_ts : esp_timer_get_time();
// Leave legacy log/delay inputs unchanged, but do not attach a stale or
// unrelated RX notification timestamp to this record's TX completion.
record->tx_done_us = !notify_seen
|| ((irq & (SX126X_IRQ_TX_DONE | SX126X_IRQ_TIMEOUT))
&& *tx_done_us >= *tx_start_us)
? *tx_done_us : esp_timer_get_time();
fem_set_tx(false); fem_set_tx(false);
sx126x_clear_irq(SX126X_IRQ_ALL); sx126x_clear_irq(SX126X_IRQ_ALL);
#ifdef CONFIG_WMBUS_TX_DIAG_ALWAYS #ifdef CONFIG_WMBUS_TX_DIAG_ALWAYS
@@ -287,9 +377,8 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
if (irq & SX126X_IRQ_TX_DONE) { if (irq & SX126X_IRQ_TX_DONE) {
g_stats.tx_success++; g_stats.tx_success++;
led_notify_tx(); led_notify_tx();
if (*tx_done_us > *tx_start_us) { g_stats.tx_airtime_us += airtime_us;
g_stats.tx_airtime_us += (uint64_t)(*tx_done_us - *tx_start_us); duty_ledger_record(&s_duty, *tx_start_us, airtime_us);
}
return notify_seen ? "ok" : "ok_polled"; return notify_seen ? "ok" : "ok_polled";
} }
if (irq & SX126X_IRQ_TIMEOUT) { if (irq & SX126X_IRQ_TIMEOUT) {
@@ -300,17 +389,31 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
return "irq_timeout"; return "irq_timeout";
} }
static void log_tx(const char *result, uint32_t hash, int len, static const char *do_tx(const uint8_t *payload, int payload_len, bool t1,
int64_t rx_ts, int64_t tx_start, int64_t tx_done, int64_t *tx_start_us, int64_t *tx_done_us,
const uint8_t *payload, int payload_len) debug_record_t *record)
{
const char *res = do_tx_raw(payload, payload_len, t1,
tx_start_us, tx_done_us, record);
record->outcome = res;
// UI snapshot: single writer (this task), lock-free readers.
strlcpy(g_ui.tx_result, res, sizeof(g_ui.tx_result));
g_ui.tx_ts_us = *tx_done_us;
return res;
}
static void log_tx(const char *result, uint32_t hash, int len, int phys_len,
const char *mode, int64_t rx_ts, int64_t tx_start,
int64_t tx_done, const uint8_t *payload, int payload_len)
{ {
printf("{\"seq\":%" PRIu32 ",\"event\":\"wmbus_tx\",\"timestamp_us\":%lld," printf("{\"seq\":%" PRIu32 ",\"event\":\"wmbus_tx\",\"timestamp_us\":%lld,"
"\"source_rx_timestamp_us\":%lld,\"delay_us\":%lld," "\"source_rx_timestamp_us\":%lld,\"delay_us\":%lld,"
"\"length\":%d,\"hash\":\"%08" PRIx32 "\"," "\"length\":%d,\"mode\":\"%s\",\"hash\":\"%08" PRIx32 "\","
"\"configured_tx_dbm\":%d,\"airtime_us\":%lld,\"result\":\"%s\"", "\"configured_tx_dbm\":%d,\"airtime_us\":%" PRIu32 ","
"\"tx_operation_us\":%lld,\"result\":\"%s\"",
s_seq++, (long long)tx_start, (long long)rx_ts, s_seq++, (long long)tx_start, (long long)rx_ts,
(long long)(tx_start - rx_ts), len, hash, (long long)(tx_start - rx_ts), len, mode, hash,
(int)g_cfg.tx_power_dbm, (int)g_cfg.tx_power_dbm, tx_airtime_us(phys_len),
(long long)(tx_done > tx_start ? tx_done - tx_start : 0), result); (long long)(tx_done > tx_start ? tx_done - tx_start : 0), result);
#ifdef CONFIG_WMBUS_LOG_RAW_FRAMES #ifdef CONFIG_WMBUS_LOG_RAW_FRAMES
if (payload && payload_len > 0) { if (payload && payload_len > 0) {
@@ -327,24 +430,68 @@ static void log_tx(const char *result, uint32_t hash, int len,
static void run_test_tx(void) static void run_test_tx(void)
{ {
debug_record_t record = debug_record_init("test", "C1", "A", esp_timer_get_time());
uint8_t frame[256]; uint8_t frame[256];
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++, int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++,
s_test_lfield); g_cfg.test_lfield);
if (n < 0) return; if (n < 0) {
debug_history_record(&record);
return;
}
static uint8_t payload[258]; static uint8_t payload[258];
payload[0] = WMBUS_MODE_BYTE_A_HI; payload[0] = WMBUS_MODE_BYTE_A_HI;
payload[1] = WMBUS_MODE_BYTE_A_LO; payload[1] = WMBUS_MODE_BYTE_A_LO;
memcpy(payload + 2, frame, n); memcpy(payload + 2, frame, n);
uint32_t hash = wmbus_hash(frame, n); debug_frame(&record, frame, n);
uint32_t hash = record.hash;
int64_t t0, t1; int64_t t0, t1;
const char *res = do_tx(payload, n + 2, &t0, &t1); const char *res = do_tx(payload, n + 2, false, &t0, &t1, &record);
log_tx(res, hash, n, t0, t0, t1, NULL, 0); log_tx(res, hash, n, n + 2, "C1", t0, t0, t1, NULL, 0);
printf("{\"seq\":%" PRIu32 ",\"event\":\"test_tx_frame\",\"lfield\":%u,\"raw\":\"", printf("{\"seq\":%" PRIu32 ",\"event\":\"test_tx_frame\",\"lfield\":%u,\"raw\":\"",
s_seq++, s_test_lfield); s_seq++, g_cfg.test_lfield);
print_hex(frame, n); print_hex(frame, n);
printf("\"}\n"); printf("\"}\n");
fflush(stdout); fflush(stdout);
record.timestamp_us = t0;
debug_history_record(&record);
sx126x_restore_rx_payload_len();
if (!sx126x_set_rx()) recover_ladder("test_tx_rx_restore");
}
// Synthetic T1 transmission: the same OMS test frame, 3-of-6 coded and
// sent with T-mode deviation. Proves the T TX chain against rtl_wmbus
// ("T1;..." decode of SLN 00000001) without needing T-mode meter traffic.
static void run_test_tx_t1(void)
{
debug_record_t record = debug_record_init("test", "T1", "A", esp_timer_get_time());
uint8_t frame[192];
uint8_t lf = g_cfg.test_lfield > 140 ? 140 : g_cfg.test_lfield; // coded <= 255
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++, lf);
if (n < 0) {
debug_history_record(&record);
return;
}
debug_frame(&record, frame, n);
static uint8_t coded[300];
int clen = wmbus_3of6_encode(frame, n, coded, sizeof(coded));
if (clen < 0 || clen > 255) {
debug_history_record(&record);
return;
}
uint32_t hash = record.hash;
int64_t t0, t1;
const char *res = do_tx(coded, clen, true, &t0, &t1, &record);
log_tx(res, hash, n, clen, "T1", t0, t0, t1, NULL, 0);
printf("{\"seq\":%" PRIu32 ",\"event\":\"test_tx_frame\",\"mode\":\"T1\","
"\"lfield\":%u,\"coded_len\":%d,\"raw\":\"", s_seq++, lf, clen);
print_hex(frame, n);
printf("\"}\n");
fflush(stdout);
record.timestamp_us = t0;
debug_history_record(&record);
sx126x_restore_rx_payload_len(); sx126x_restore_rx_payload_len();
if (!sx126x_set_rx()) recover_ladder("test_tx_rx_restore"); if (!sx126x_set_rx()) recover_ladder("test_tx_rx_restore");
@@ -355,16 +502,23 @@ static void run_test_tx(void)
// Respects the duty guard; suppressed beacons skip to the next period. // Respects the duty guard; suppressed beacons skip to the next period.
static void run_beacon(void) static void run_beacon(void)
{ {
debug_record_t record = debug_record_init("beacon", "C1", "A", esp_timer_get_time());
uint8_t frame[256]; uint8_t frame[256];
uint8_t acc = s_test_access_nr++; uint8_t acc = s_test_access_nr++;
int n = wmbus_build_test_frame(frame, sizeof(frame), acc, s_test_lfield); int n = wmbus_build_test_frame(frame, sizeof(frame), acc, g_cfg.test_lfield);
if (n < 0) return; if (n < 0) {
debug_history_record(&record);
return;
}
uint64_t duty_used = 0, duty_budget = 0; uint64_t duty_used = 0, duty_budget = 0;
if (duty_would_exceed(esp_timer_get_time(), n + 2, &duty_used, &duty_budget)) { if (duty_would_exceed(esp_timer_get_time(), n + 2, &duty_used, &duty_budget)) {
g_stats.tx_suppressed_duty++; g_stats.tx_suppressed_duty++;
LOGJ("\"event\":\"beacon_suppressed\",\"reason\":\"duty_cycle\"," LOGJ("\"event\":\"beacon_suppressed\",\"reason\":\"duty_cycle\","
"\"used_us\":%llu,\"budget_us\":%llu", "\"used_us\":%llu,\"budget_us\":%llu",
(unsigned long long)duty_used, (unsigned long long)duty_budget); (unsigned long long)duty_used, (unsigned long long)duty_budget);
debug_frame(&record, frame, n);
record.outcome = "duty_cycle";
debug_history_record(&record);
return; return;
} }
static uint8_t payload[258]; static uint8_t payload[258];
@@ -373,11 +527,13 @@ static void run_beacon(void)
memcpy(payload + 2, frame, n); memcpy(payload + 2, frame, n);
int64_t t0, t1; int64_t t0, t1;
const char *res = do_tx(payload, n + 2, &t0, &t1); const char *res = do_tx(payload, n + 2, false, &t0, &t1, &record);
if (t1 > t0) duty_record(t0, (uint32_t)(t1 - t0));
LOGJ("\"event\":\"beacon\",\"acc\":%u,\"lfield\":%u,\"result\":\"%s\"," LOGJ("\"event\":\"beacon\",\"acc\":%u,\"lfield\":%u,\"result\":\"%s\","
"\"timestamp_us\":%lld,\"tx_done_us\":%lld", "\"timestamp_us\":%lld,\"tx_done_us\":%lld",
acc, s_test_lfield, res, (long long)t0, (long long)t1); acc, g_cfg.test_lfield, res, (long long)t0, (long long)t1);
debug_frame(&record, frame, n);
record.timestamp_us = t0;
debug_history_record(&record);
sx126x_restore_rx_payload_len(); sx126x_restore_rx_payload_len();
if (!sx126x_set_rx()) recover_ladder("beacon_rx_restore"); if (!sx126x_set_rx()) recover_ladder("beacon_rx_restore");
@@ -389,33 +545,45 @@ static void run_beacon(void)
// from anything in the RX path. // from anything in the RX path.
static void run_test_burst(void) static void run_test_burst(void)
{ {
debug_record_t record = debug_record_init("test", "C1", "A", esp_timer_get_time());
uint8_t frame[256]; uint8_t frame[256];
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++, int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++,
s_test_lfield); g_cfg.test_lfield);
if (n < 0) return; if (n < 0) {
debug_history_record(&record);
return;
}
static uint8_t payload[258]; static uint8_t payload[258];
payload[0] = WMBUS_MODE_BYTE_A_HI; payload[0] = WMBUS_MODE_BYTE_A_HI;
payload[1] = WMBUS_MODE_BYTE_A_LO; payload[1] = WMBUS_MODE_BYTE_A_LO;
memcpy(payload + 2, frame, n); memcpy(payload + 2, frame, n);
uint32_t hash = wmbus_hash(frame, n); debug_frame(&record, frame, n);
uint32_t hash = record.hash;
debug_record_t second = record;
printf("{\"seq\":%" PRIu32 ",\"event\":\"test_burst_frame\",\"lfield\":%u," printf("{\"seq\":%" PRIu32 ",\"event\":\"test_burst_frame\",\"lfield\":%u,"
"\"delay_ms\":%" PRIu32 ",\"raw\":\"", "\"delay_ms\":%" PRIu32 ",\"raw\":\"",
s_seq++, s_test_lfield, g_cfg.repeat_delay_ms); s_seq++, g_cfg.test_lfield, g_cfg.repeat_delay_ms);
print_hex(frame, n); print_hex(frame, n);
printf("\"}\n"); printf("\"}\n");
fflush(stdout); fflush(stdout);
int64_t t0, t1; int64_t t0, t1;
const char *r1 = do_tx(payload, n + 2, &t0, &t1); const char *r1 = do_tx(payload, n + 2, false, &t0, &t1, &record);
int64_t first_end = t1 > t0 ? t1 : esp_timer_get_time(); int64_t first_end = t1 > t0 ? t1 : esp_timer_get_time();
log_tx(r1, hash, n, t0, t0, t1, NULL, 0); log_tx(r1, hash, n, n + 2, "C1", t0, t0, t1, NULL, 0);
precise_delay_until(first_end + (int64_t)g_cfg.repeat_delay_ms * 1000); precise_delay_until(first_end + (int64_t)g_cfg.repeat_delay_ms * 1000);
int64_t t2, t3; int64_t t2, t3;
const char *r2 = do_tx(payload, n + 2, &t2, &t3); const char *r2 = do_tx(payload, n + 2, false, &t2, &t3, &second);
log_tx(r2, hash, n, first_end, t2, t3, NULL, 0); log_tx(r2, hash, n, n + 2, "C1", first_end, t2, t3, NULL, 0);
// Publish both immutable synthetic outcomes after the second TX, so no
// history lock or extra serial output intrudes on the inter-burst delay.
record.timestamp_us = t0;
debug_history_record(&record);
second.timestamp_us = t2;
debug_history_record(&second);
sx126x_restore_rx_payload_len(); sx126x_restore_rx_payload_len();
if (!sx126x_set_rx()) recover_ladder("test_burst_rx_restore"); if (!sx126x_set_rx()) recover_ladder("test_burst_rx_restore");
@@ -432,6 +600,7 @@ static void hexdump_json(const char *key, const uint8_t *d, int n)
// Scripted low-level diagnostic with raw SPI response dumps. // Scripted low-level diagnostic with raw SPI response dumps.
static void run_probe(void) static void run_probe(void)
{ {
debug_record_t record = debug_record_init("test", "C1", "A", 0);
uint8_t r[16]; uint8_t r[16];
printf("{\"event\":\"probe\","); printf("{\"event\":\"probe\",");
@@ -453,16 +622,29 @@ static void run_probe(void)
// small TX: 8 byte payload // small TX: 8 byte payload
uint8_t pkt[8] = {0x54, 0xCD, 0xAA, 0x55, 0xDE, 0xAD, 0xBE, 0xEF}; uint8_t pkt[8] = {0x54, 0xCD, 0xAA, 0x55, 0xDE, 0xAD, 0xBE, 0xEF};
sx126x_start_tx(pkt, 8); record.tx_start_us = esp_timer_get_time();
record.timestamp_us = record.tx_start_us;
bool started = sx126x_start_tx(pkt, 8);
record.outcome = started ? "irq_timeout" : "start_failed";
if (!started) record.tx_done_us = esp_timer_get_time();
printf("\"txpoll\":["); printf("\"txpoll\":[");
for (int i = 0; i < 12; i++) { for (int i = 0; i < 12; i++) {
vTaskDelay(pdMS_TO_TICKS(2)); vTaskDelay(pdMS_TO_TICKS(2));
uint8_t s2[2], q[4]; uint8_t s2[2], q[4];
sx126x_raw(0xC0, NULL, 0, s2, 2); sx126x_raw(0xC0, NULL, 0, s2, 2);
sx126x_raw(0x12, NULL, 0, q, 4); bool irq_read = sx126x_raw(0x12, NULL, 0, q, 4);
// Observe the probe's existing polls without changing its diagnostic
// window or injecting normal TX waits/duty policy into this command.
uint16_t irq = irq_read ? ((uint16_t)q[2] << 8) | q[3] : 0;
if (started && record.tx_done_us == 0
&& (irq & (SX126X_IRQ_TX_DONE | SX126X_IRQ_TIMEOUT))) {
record.tx_done_us = esp_timer_get_time();
record.outcome = irq & SX126X_IRQ_TX_DONE ? "ok_polled" : "radio_timeout";
}
printf("\"%02X-%02X%02X%02X%02X\"%s", s2[1], q[0], q[1], q[2], q[3], printf("\"%02X-%02X%02X%02X%02X\"%s", s2[1], q[0], q[1], q[2], q[3],
i < 11 ? "," : ""); i < 11 ? "," : "");
} }
if (record.tx_done_us == 0) record.tx_done_us = esp_timer_get_time();
printf("],"); printf("],");
fem_set_tx(false); fem_set_tx(false);
@@ -474,6 +656,8 @@ static void run_probe(void)
sx126x_set_rx(); sx126x_set_rx();
printf("\"done\":true}\n"); printf("\"done\":true}\n");
fflush(stdout); fflush(stdout);
debug_frame(&record, pkt + 2, sizeof(pkt) - 2);
debug_history_record(&record);
} }
@@ -481,52 +665,126 @@ static void run_probe(void)
static void handle_rx(int64_t rxdone_ts) static void handle_rx(int64_t rxdone_ts)
{ {
debug_record_t record = debug_record_init("rx", "unknown", "unknown", rxdone_ts);
bool restore_rx = false;
bool read_failed = false;
static uint8_t buf[RX_PAYLOAD_LEN]; static uint8_t buf[RX_PAYLOAD_LEN];
int8_t rssi = 0; int8_t rssi = 0;
int n = sx126x_read_rx(buf, sizeof(buf), &rssi); int n = sx126x_read_rx(buf, sizeof(buf), &rssi);
record.rssi_dbm = rssi;
if (n < 3) { if (n < 3) {
recover_ladder("rx_read_failed"); debug_rx_rejected(&record, "rx_read_failed", buf, n);
return; read_failed = true;
goto done;
} }
g_stats.rx_candidates++; g_stats.rx_candidates++;
g_stats.rx_bytes += n; g_stats.rx_bytes += n;
// Classify: C-mode announces itself with two NRZ mode bytes right
// after the shared 0x543D access code; T-mode continues with 3-of-6
// coded data directly, so a T1 frame's L-field is the first decoded
// byte of the capture. T1 uses format A framing only.
wmbus_frame_fmt_t fmt = wmbus_frame_format(buf[0], buf[1]); wmbus_frame_fmt_t fmt = wmbus_frame_format(buf[0], buf[1]);
if (fmt == WMBUS_FRAME_UNKNOWN) { bool t1 = false;
g_stats.rx_not_c1++; bool identity_available = true;
if (g_cfg.verbose) { uint8_t *frame;
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"not_c1\"," int total;
"\"mode_bytes\":\"%02X%02X\",\"rssi_dbm\":%d", buf[0], buf[1], rssi); int onair_len; // physical radio-payload bytes on air
bool crc_ok;
static uint8_t t1frame[192]; // decoded T1 frame; coded fits 255 => total <= 170
if (fmt != WMBUS_FRAME_UNKNOWN) {
record.mode = "C1";
record.format = fmt == WMBUS_FRAME_A ? "A" : "B";
total = wmbus_frame_total_len(fmt, buf[2]);
if (total < 0 || total + 2 > n) {
g_stats.rx_len_invalid++;
if (g_cfg.verbose) {
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"bad_length\","
"\"lfield\":%u,\"rssi_dbm\":%d", buf[2], rssi);
}
debug_rx_rejected(&record, "bad_length", buf + 2, n - 2);
debug_identity(&record, buf + 2, n - 2);
goto done;
}
frame = buf + 2;
onair_len = total + 2;
crc_ok = wmbus_check_crc(fmt, frame, total);
} else {
int lfield = wmbus_3of6_first_byte(buf, (size_t)n);
total = lfield >= 9
? wmbus_frame_total_len(WMBUS_FRAME_A, (uint8_t)lfield) : -1;
if (total < 0) {
g_stats.rx_not_c1++;
if (g_cfg.verbose) {
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"not_c1\","
"\"mode_bytes\":\"%02X%02X\",\"rssi_dbm\":%d",
buf[0], buf[1], rssi);
}
debug_rx_rejected(&record, "undecodable", buf, n);
goto done;
}
record.mode = "T1";
record.format = "A";
onair_len = wmbus_3of6_coded_len(total);
if (onair_len > n || total > (int)sizeof(t1frame)) {
g_stats.rx_len_invalid++;
if (g_cfg.verbose) {
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"t1_too_long\","
"\"lfield\":%d,\"rssi_dbm\":%d", lfield, rssi);
}
debug_rx_rejected(&record, "t1_too_long", buf, n);
// A truncated T1 capture can still have a complete clean header.
uint8_t header[10];
if (wmbus_3of6_decode(buf, (size_t)n, header, sizeof(header)) == 0)
debug_identity(&record, header, sizeof(header));
goto done;
}
int bad = wmbus_3of6_decode(buf, (size_t)n, t1frame, total);
t1 = true;
fmt = WMBUS_FRAME_A;
frame = t1frame;
g_stats.rx_t1++;
crc_ok = bad == 0 && wmbus_check_crc(WMBUS_FRAME_A, frame, total);
// Invalid 3-of-6 symbols remain CRC-rejected as in the radio parser;
// decoded replacement nibbles must never become a successful repeat.
if (bad != 0) {
uint8_t header[10];
identity_available = wmbus_3of6_decode(buf, (size_t)n, header,
sizeof(header)) == 0;
} }
return;
} }
int total = wmbus_frame_total_len(fmt, buf[2]);
if (total < 0 || total + 2 > n) {
g_stats.rx_len_invalid++;
if (g_cfg.verbose) {
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"bad_length\","
"\"lfield\":%u,\"rssi_dbm\":%d", buf[2], rssi);
}
return;
}
const uint8_t *frame = buf + 2;
bool crc_ok = wmbus_check_crc(fmt, frame, total);
if (crc_ok) g_stats.rx_valid++; else g_stats.rx_crc_fail++; if (crc_ok) g_stats.rx_valid++; else g_stats.rx_crc_fail++;
if (crc_ok) led_notify_rx(); if (crc_ok) led_notify_rx();
uint32_t hash = wmbus_hash(frame, total); uint32_t hash = wmbus_hash(frame, total);
// RxDone fires after the fixed 255-byte capture; the frame actually // RxDone fires after the fixed 255-byte capture; the frame actually
// ended earlier. Reconstruct the real end-of-frame time. // ended earlier. Reconstruct the real end-of-frame time from the
int64_t frame_end_ts = rxdone_ts - (int64_t)(RX_PAYLOAD_LEN - (total + 2)) * US_PER_BYTE; // physical on-air length (coded for T1, mode bytes + frame for C).
int64_t frame_end_ts = rxdone_ts - (int64_t)(RX_PAYLOAD_LEN - onair_len) * US_PER_BYTE;
record.timestamp_us = frame_end_ts;
record.length = (uint16_t)total;
record.hash = hash;
record.crc_ok = crc_ok;
record.reception = crc_ok ? "ok" : "crc_failed";
record.outcome = crc_ok ? "repeat_disabled" : "crc_failed";
if (identity_available) debug_identity(&record, frame, total);
g_ui.rx_meter_id = (uint32_t)frame[4] | ((uint32_t)frame[5] << 8)
| ((uint32_t)frame[6] << 16) | ((uint32_t)frame[7] << 24);
g_ui.rx_hash = hash;
g_ui.rx_len = (int16_t)total;
g_ui.rx_rssi_dbm = rssi;
g_ui.rx_format = t1 ? 'T' : (fmt == WMBUS_FRAME_A ? 'A' : 'B');
g_ui.rx_crc_ok = crc_ok;
g_ui.rx_ts_us = frame_end_ts;
printf("{\"seq\":%" PRIu32 ",\"event\":\"wmbus_rx\",\"timestamp_us\":%lld," printf("{\"seq\":%" PRIu32 ",\"event\":\"wmbus_rx\",\"timestamp_us\":%lld,"
"\"rxdone_us\":%lld,\"frequency_hz\":868950000,\"format\":\"%c\"," "\"rxdone_us\":%lld,\"frequency_hz\":868950000,\"mode\":\"%s\","
"\"length\":%d,\"rssi_dbm\":%d,\"crc_ok\":%s," "\"format\":\"%c\",\"length\":%d,\"rssi_dbm\":%d,\"crc_ok\":%s,"
"\"hash\":\"%08" PRIx32 "\"", "\"hash\":\"%08" PRIx32 "\"",
s_seq++, (long long)frame_end_ts, (long long)rxdone_ts, s_seq++, (long long)frame_end_ts, (long long)rxdone_ts,
fmt == WMBUS_FRAME_A ? 'A' : 'B', total, rssi, t1 ? "T1" : "C1", fmt == WMBUS_FRAME_A ? 'A' : 'B', total, rssi,
crc_ok ? "true" : "false", hash); crc_ok ? "true" : "false", hash);
#ifdef CONFIG_WMBUS_LOG_RAW_FRAMES #ifdef CONFIG_WMBUS_LOG_RAW_FRAMES
printf(",\"raw\":\""); printf(",\"raw\":\"");
@@ -536,10 +794,11 @@ static void handle_rx(int64_t rxdone_ts)
printf("}\n"); printf("}\n");
fflush(stdout); fflush(stdout);
if (!g_cfg.repeat_enabled || !crc_ok) return; if (!g_cfg.repeat_enabled || !crc_ok) goto done;
if (!whitelist_pass(frame)) { if (!whitelist_pass(frame)) {
g_stats.tx_suppressed_whitelist++; g_stats.tx_suppressed_whitelist++;
return; record.outcome = "whitelist";
goto done;
} }
int64_t now = esp_timer_get_time(); int64_t now = esp_timer_get_time();
if (is_dup(hash, now)) { if (is_dup(hash, now)) {
@@ -547,32 +806,67 @@ static void handle_rx(int64_t rxdone_ts)
if (g_cfg.verbose) { if (g_cfg.verbose) {
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"dup\",\"hash\":\"%08" PRIx32 "\"", hash); LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"dup\",\"hash\":\"%08" PRIx32 "\"", hash);
} }
return; record.outcome = "duplicate";
goto done;
} }
uint64_t duty_used = 0, duty_budget = 0; uint64_t duty_used = 0, duty_budget = 0;
if (duty_would_exceed(now, total + 2, &duty_used, &duty_budget)) { if (duty_would_exceed(now, onair_len, &duty_used, &duty_budget)) {
g_stats.tx_suppressed_duty++; g_stats.tx_suppressed_duty++;
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"duty_cycle\"," LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"duty_cycle\","
"\"hash\":\"%08" PRIx32 "\",\"used_us\":%llu,\"budget_us\":%llu", "\"hash\":\"%08" PRIx32 "\",\"used_us\":%llu,\"budget_us\":%llu",
hash, (unsigned long long)duty_used, hash, (unsigned long long)duty_used,
(unsigned long long)duty_budget); (unsigned long long)duty_budget);
return; record.outcome = "duty_cycle";
goto done;
} }
// ---- repeat ---- // RX logging/hash above describe the original. TX carries only the
static uint8_t txbuf[RX_PAYLOAD_LEN + 2]; // standard H-bit change and repaired CRC; ciphertext is untouched.
txbuf[0] = buf[0]; if (!wmbus_mark_repeated(fmt, frame, total)) {
txbuf[1] = buf[1]; if (g_cfg.verbose) {
memcpy(txbuf + 2, frame, total); LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"hop_policy\","
"\"hash\":\"%08" PRIx32 "\"", hash);
}
record.outcome = "hop_policy";
goto done;
}
// ---- repeat: rebuild the physical payload in the source mode ----
static uint8_t txbuf[300];
int phys;
if (t1) {
phys = wmbus_3of6_encode(frame, total, txbuf, sizeof(txbuf));
if (phys < 0 || phys > 255) {
record.outcome = "encode_failed";
goto done;
}
} else {
txbuf[0] = buf[0];
txbuf[1] = buf[1];
memcpy(txbuf + 2, frame, total);
phys = total + 2;
}
precise_delay_until(frame_end_ts + (int64_t)g_cfg.repeat_delay_ms * 1000); precise_delay_until(frame_end_ts + (int64_t)g_cfg.repeat_delay_ms * 1000);
int64_t t0, t1; int64_t t0, t1_done;
const char *res = do_tx(txbuf, total + 2, &t0, &t1); const char *res = do_tx(txbuf, phys, t1, &t0, &t1_done, &record);
if (t1 > t0) duty_record(t0, (uint32_t)(t1 - t0));
remember_dup(hash, esp_timer_get_time()); remember_dup(hash, esp_timer_get_time());
log_tx(res, hash, total, frame_end_ts, t0, t1, txbuf, total + 2); log_tx(res, hash, total, phys, t1 ? "T1" : "C1",
frame_end_ts, t0, t1_done, txbuf, phys);
restore_rx = true;
done:
// Exactly one final record per RX candidate, before recovery can reboot.
// Keep existing serial events unchanged: an additional blocking printf/
// fflush per row would extend deaf time even after a decision or TX.
debug_history_record(&record);
if (read_failed) {
recover_ladder("rx_read_failed");
return;
}
if (!restore_rx) return;
// Always return to RX // Always return to RX
sx126x_restore_rx_payload_len(); sx126x_restore_rx_payload_len();
@@ -588,6 +882,47 @@ static void handle_rx(int64_t rxdone_ts)
} }
} }
static void handle_irq(uint16_t irq)
{
sx126x_clear_irq(irq);
if (irq & SX126X_IRQ_RX_DONE) handle_rx(s_irq_ts);
// TIMEOUT in RX continuous should not happen; TX_DONE is consumed
// by do_tx's instrumented wait. Anything unexpected: just note it.
if (g_cfg.verbose && (irq & ~SX126X_IRQ_RX_DONE)) {
LOGJ("\"event\":\"irq_other\",\"mask\":%u", irq);
}
}
static void apply_pending_settings(void)
{
if (!settings_radio_pending()) return;
// Only settings changes add an IRQ probe. Drain the old capture using its
// old configuration before copying a new coherent snapshot. A latched sync
// without RxDone means the fixed-length capture is still in progress.
uint16_t irq = sx126x_get_irq();
if (irq & SX126X_IRQ_RX_DONE) {
ulTaskNotifyTake(pdTRUE, 0);
handle_irq(irq);
irq = sx126x_get_irq();
}
if (irq & (SX126X_IRQ_SYNCWORD_VALID | SX126X_IRQ_RX_DONE)) return;
int8_t old_tx_power = g_cfg.tx_power_dbm;
uint8_t old_preamble = g_cfg.preamble_bits;
bool old_fem_rx_csd = g_cfg.fem_rx_csd;
if (!settings_radio_apply(&g_cfg)) return;
// Driver desired values are radio-owned too. No driver access takes place
// under the settings spinlock, or from USB/HTTP/OLED writer tasks.
sx126x_set_preamble_detect(preamble_detect_code(g_cfg.preamble_bits));
fem_set_rx_csd(g_cfg.fem_rx_csd);
if (old_tx_power != g_cfg.tx_power_dbm || old_preamble != g_cfg.preamble_bits) {
s_want_radio_reset = true;
} else if (old_fem_rx_csd != g_cfg.fem_rx_csd) {
// Apply the RX pin without a full modem reinitialization.
fem_set_tx(false);
}
}
// ------------------------------------------------------------------ task // ------------------------------------------------------------------ task
static void repeater_task(void *arg) static void repeater_task(void *arg)
@@ -596,27 +931,38 @@ static void repeater_task(void *arg)
s_task = xTaskGetCurrentTaskHandle(); s_task = xTaskGetCurrentTaskHandle();
sx126x_set_irq_callback(irq_cb); sx126x_set_irq_callback(irq_cb);
esp_task_wdt_add(NULL); esp_task_wdt_add(NULL);
settings_radio_apply(&g_cfg);
sx126x_set_preamble_detect(preamble_detect_code(g_cfg.preamble_bits));
fem_set_rx_csd(g_cfg.fem_rx_csd);
if (!radio_full_init()) { if (!radio_full_init()) {
// keep retrying with full ladder rather than dying // keep retrying with full ladder rather than dying
recover_ladder("boot_init_failed"); recover_ladder("boot_init_failed");
} }
if (!sx126x_set_rx()) recover_ladder("boot_rx_failed"); if (!sx126x_set_rx()) recover_ladder("boot_rx_failed");
s_debug_status.chip_mode = 0x5;
publish_debug_status();
led_boot_done(); led_boot_done();
int64_t last_heartbeat = 0; int64_t last_heartbeat = 0;
for (;;) { for (;;) {
esp_task_wdt_reset(); esp_task_wdt_reset();
apply_pending_settings();
if (s_want_radio_reset) { if (s_want_radio_reset) {
s_want_radio_reset = false; s_want_radio_reset = false;
g_stats.radio_reinit++; g_stats.radio_reinit++;
if (!radio_full_init() || !sx126x_set_rx()) recover_ladder("manual_reset"); if (!radio_full_init() || !sx126x_set_rx()) recover_ladder("manual_reset");
else s_debug_status.chip_mode = 0x5;
} }
if (s_want_test_tx) { if (s_want_test_tx) {
s_want_test_tx = false; s_want_test_tx = false;
run_test_tx(); run_test_tx();
} }
if (s_want_test_tx_t1) {
s_want_test_tx_t1 = false;
run_test_tx_t1();
}
if (s_want_test_burst) { if (s_want_test_burst) {
s_want_test_burst = false; s_want_test_burst = false;
run_test_burst(); run_test_burst();
@@ -640,14 +986,7 @@ static void repeater_task(void *arg)
} }
if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(1000)) > 0) { if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(1000)) > 0) {
uint16_t irq = sx126x_get_irq(); handle_irq(sx126x_get_irq());
sx126x_clear_irq(irq);
if (irq & SX126X_IRQ_RX_DONE) handle_rx(s_irq_ts);
// TIMEOUT in RX continuous should not happen; TX_DONE is consumed
// by do_tx's wait_irq. Anything unexpected: just note it.
if (g_cfg.verbose && (irq & ~(SX126X_IRQ_RX_DONE))) {
LOGJ("\"event\":\"irq_other\",\"mask\":%u", irq);
}
} }
if (g_cfg.beacon_period_ms) { if (g_cfg.beacon_period_ms) {
int64_t bnow = esp_timer_get_time(); int64_t bnow = esp_timer_get_time();
@@ -667,16 +1006,25 @@ static void repeater_task(void *arg)
uint8_t st = sx126x_get_status(); uint8_t st = sx126x_get_status();
uint8_t mode = (st >> 4) & 0x7; uint8_t mode = (st >> 4) & 0x7;
bool cfg_ok = sx126x_config_intact(); bool cfg_ok = sx126x_config_intact();
int8_t rssi_now = sx126x_get_rssi_inst();
g_ui.chip_mode = mode;
g_ui.config_intact = cfg_ok;
g_ui.rssi_dbm = rssi_now;
g_ui.hb_ts_us = now;
s_debug_status.heartbeat_us = now;
s_debug_status.chip_mode = mode;
s_debug_status.config_intact = cfg_ok;
LOGJ("\"event\":\"heartbeat\",\"uptime_us\":%lld,\"chip_mode\":%u," LOGJ("\"event\":\"heartbeat\",\"uptime_us\":%lld,\"chip_mode\":%u,"
"\"config_intact\":%s,\"rssi_dbm\":%d", "\"config_intact\":%s,\"rssi_dbm\":%d",
(long long)now, mode, cfg_ok ? "true" : "false", (long long)now, mode, cfg_ok ? "true" : "false",
sx126x_get_rssi_inst()); (int)rssi_now);
if (mode != 0x5) { if (mode != 0x5) {
recover_ladder("not_in_rx"); recover_ladder("not_in_rx");
} else if (!cfg_ok) { } else if (!cfg_ok) {
recover_ladder("config_lost"); recover_ladder("config_lost");
} }
} }
publish_debug_status();
} }
} }
@@ -687,8 +1035,8 @@ void repeater_start(void)
void repeater_request_radio_reset(void) { s_want_radio_reset = true; } void repeater_request_radio_reset(void) { s_want_radio_reset = true; }
void repeater_request_test_tx(void) { s_want_test_tx = true; } void repeater_request_test_tx(void) { s_want_test_tx = true; }
void repeater_request_test_tx_t1(void) { s_want_test_tx_t1 = true; }
void repeater_request_probe(void) { s_want_probe = true; } void repeater_request_probe(void) { s_want_probe = true; }
void repeater_set_test_lfield(uint8_t l) { s_test_lfield = l; }
void repeater_request_test_burst(void) { s_want_test_burst = true; } void repeater_request_test_burst(void) { s_want_test_burst = true; }
void repeater_inject_fault(int what) { s_inject = what; } void repeater_inject_fault(int what) { s_inject = what; }
@@ -696,22 +1044,35 @@ void repeater_inject_fault(int what) { s_inject = what; }
void repeater_print_status(void) void repeater_print_status(void)
{ {
settings_snapshot_t snapshot;
settings_get_snapshot(&snapshot);
const repeater_cfg_t *cfg = &snapshot.values;
char whitelist[8 * 11] = "";
size_t used = 0;
for (int i = 0; i < cfg->whitelist_len; i++) {
used += (size_t)snprintf(whitelist + used, sizeof(whitelist) - used,
"%s\"%08" PRIx32 "\"", i ? "," : "", cfg->whitelist[i]);
}
// Settings describe the accepted state, which may be pending. The applied
// revision acknowledges only the radio's copy, not hardware/RF success.
LOGJ("\"event\":\"status\",\"uptime_us\":%lld," LOGJ("\"event\":\"status\",\"uptime_us\":%lld,"
"\"repeat_delay_ms\":%" PRIu32 ",\"configured_tx_dbm\":%d," "\"repeat_delay_ms\":%" PRIu32 ",\"configured_tx_dbm\":%d,"
"\"repeat_enabled\":%s,\"verbose\":%s,\"whitelist_len\":%d," "\"repeat_enabled\":%s,\"verbose\":%s,\"whitelist_len\":%d,"
"\"preamble_detect_code\":%u,\"duty_budget_ppm\":%" PRIu32 "," "\"preamble_detect_code\":%u,\"duty_budget_ppm\":%" PRIu32 ","
"\"beacon_period_ms\":%" PRIu32 "," "\"beacon_period_ms\":%" PRIu32 ","
"\"duty_used_us\":%llu,\"reset_reason\":%d", "\"duty_used_us\":%llu,\"reset_reason\":%d,"
"\"fem_rx_csd\":%s,\"preamble_bits\":%u,\"test_lfield\":%u,"
"\"whitelist\":[%s],\"revision\":%" PRIu32 ",\"applied_revision\":%" PRIu32,
(long long)esp_timer_get_time(), (long long)esp_timer_get_time(),
g_cfg.repeat_delay_ms, (int)g_cfg.tx_power_dbm, cfg->repeat_delay_ms, (int)cfg->tx_power_dbm,
g_cfg.repeat_enabled ? "true" : "false", cfg->repeat_enabled ? "true" : "false",
g_cfg.verbose ? "true" : "false", cfg->verbose ? "true" : "false",
g_cfg.whitelist_len, cfg->whitelist_len, preamble_detect_code(cfg->preamble_bits),
sx126x_get_preamble_detect(), cfg->duty_budget_ppm, cfg->beacon_period_ms,
g_cfg.duty_budget_ppm,
g_cfg.beacon_period_ms,
(unsigned long long)duty_used_us(esp_timer_get_time()), (unsigned long long)duty_used_us(esp_timer_get_time()),
(int)esp_reset_reason()); (int)esp_reset_reason(),
cfg->fem_rx_csd ? "true" : "false", cfg->preamble_bits, cfg->test_lfield,
whitelist, snapshot.revision, snapshot.applied_revision);
} }
void repeater_print_stats(void) void repeater_print_stats(void)
@@ -719,7 +1080,8 @@ void repeater_print_stats(void)
LOGJ("\"event\":\"stats\",\"uptime_us\":%lld," LOGJ("\"event\":\"stats\",\"uptime_us\":%lld,"
"\"rx_candidates\":%" PRIu32 ",\"rx_valid\":%" PRIu32 "," "\"rx_candidates\":%" PRIu32 ",\"rx_valid\":%" PRIu32 ","
"\"rx_crc_fail\":%" PRIu32 ",\"rx_not_c1\":%" PRIu32 "," "\"rx_crc_fail\":%" PRIu32 ",\"rx_not_c1\":%" PRIu32 ","
"\"rx_len_invalid\":%" PRIu32 ",\"rx_bytes\":%" PRIu32 "," "\"rx_len_invalid\":%" PRIu32 ",\"rx_t1\":%" PRIu32 ","
"\"rx_bytes\":%" PRIu32 ","
"\"tx_attempts\":%" PRIu32 ",\"tx_success\":%" PRIu32 "," "\"tx_attempts\":%" PRIu32 ",\"tx_success\":%" PRIu32 ","
"\"tx_timeout\":%" PRIu32 ",\"tx_failures\":%" PRIu32 "," "\"tx_timeout\":%" PRIu32 ",\"tx_failures\":%" PRIu32 ","
"\"tx_suppressed_dup\":%" PRIu32 ",\"tx_suppressed_whitelist\":%" PRIu32 "," "\"tx_suppressed_dup\":%" PRIu32 ",\"tx_suppressed_whitelist\":%" PRIu32 ","
@@ -729,7 +1091,8 @@ void repeater_print_stats(void)
"\"tx_duty_cycle_ppm\":%llu", "\"tx_duty_cycle_ppm\":%llu",
(long long)esp_timer_get_time(), (long long)esp_timer_get_time(),
g_stats.rx_candidates, g_stats.rx_valid, g_stats.rx_crc_fail, g_stats.rx_candidates, g_stats.rx_valid, g_stats.rx_crc_fail,
g_stats.rx_not_c1, g_stats.rx_len_invalid, g_stats.rx_bytes, g_stats.rx_not_c1, g_stats.rx_len_invalid, g_stats.rx_t1,
g_stats.rx_bytes,
g_stats.tx_attempts, g_stats.tx_success, g_stats.tx_timeout, g_stats.tx_attempts, g_stats.tx_success, g_stats.tx_timeout,
g_stats.tx_failures, g_stats.tx_suppressed_dup, g_stats.tx_failures, g_stats.tx_suppressed_dup,
g_stats.tx_suppressed_whitelist, g_stats.tx_suppressed_duty, g_stats.tx_suppressed_whitelist, g_stats.tx_suppressed_duty,
+36 -4
View File
@@ -9,6 +9,7 @@ typedef struct {
uint32_t rx_crc_fail; uint32_t rx_crc_fail;
uint32_t rx_not_c1; // sync matched but not C-mode (e.g. T1) uint32_t rx_not_c1; // sync matched but not C-mode (e.g. T1)
uint32_t rx_len_invalid; uint32_t rx_len_invalid;
uint32_t rx_t1; // receptions classified as T-mode (any CRC state)
uint32_t rx_bytes; uint32_t rx_bytes;
uint32_t tx_attempts; uint32_t tx_attempts;
uint32_t tx_success; uint32_t tx_success;
@@ -24,24 +25,55 @@ typedef struct {
} repeater_stats_t; } repeater_stats_t;
typedef struct { typedef struct {
uint32_t repeat_delay_ms; // 20..200 uint32_t repeat_delay_ms; // 20..1000; persisted (cfg_store)
uint32_t duty_budget_ppm; // rolling-hour TX airtime cap, 0 = disabled uint32_t duty_budget_ppm; // rolling-hour TX airtime cap, 0 = disabled; persisted
uint32_t beacon_period_ms; // periodic synthetic test frame, 0 = off uint32_t beacon_period_ms; // periodic synthetic test frame, 0 = off
int8_t tx_power_dbm; // configured SX1262 level, not radiated power int8_t tx_power_dbm; // configured SX1262 level, not radiated power
bool repeat_enabled; bool repeat_enabled;
bool verbose; bool verbose;
uint32_t whitelist[8]; // A-field ID (4 bytes LE as uint32), 0 = empty slot bool fem_rx_csd; // experimental FEM CSD level in RX
uint8_t preamble_bits; // 0, 8, 16, 24 or 32 detected bits
uint8_t test_lfield; // 19..200, synthetic frame payload length
uint32_t whitelist[8]; // A-field ID (4 bytes LE as uint32)
int whitelist_len; int whitelist_len;
} repeater_cfg_t; } repeater_cfg_t;
// Radio-owned applied configuration after boot; other tasks may display it,
// but all mutations must go through settings_update.
extern repeater_cfg_t g_cfg; extern repeater_cfg_t g_cfg;
extern repeater_stats_t g_stats; extern repeater_stats_t g_stats;
// Last-event snapshot published by the radio task for the local UI.
// Written only from the radio task; read from the UI task without locks.
// Races tear at most one displayed frame and are deliberately accepted --
// the UI must never block or query the radio (docs/FUTURE_UI.md).
typedef struct {
int64_t rx_ts_us; // 0 = no reception yet
uint32_t rx_meter_id; // A-field ID, LE uint32 (prints as meter number)
uint32_t rx_hash;
int16_t rx_len;
int8_t rx_rssi_dbm;
char rx_format; // 'A' / 'B'
bool rx_crc_ok;
int64_t tx_ts_us; // 0 = no TX yet
char tx_result[16]; // includes full "radio_timeout" + terminator
int64_t hb_ts_us; // last heartbeat probe
uint8_t chip_mode;
bool config_intact;
int8_t rssi_dbm;
} repeater_ui_t;
extern repeater_ui_t g_ui;
// Rolling-hour duty usage right now. Pure memory reads (ledger + monotonic
// clock); safe to call from the UI task.
uint64_t repeater_duty_used_us(void);
void repeater_start(void); void repeater_start(void);
void repeater_request_radio_reset(void); void repeater_request_radio_reset(void);
void repeater_request_test_tx(void); void repeater_request_test_tx(void);
void repeater_request_test_tx_t1(void);
void repeater_request_probe(void); void repeater_request_probe(void);
void repeater_set_test_lfield(uint8_t l);
void repeater_request_test_burst(void); void repeater_request_test_burst(void);
void repeater_inject_fault(int what); // 1 = standby, 2 = sleep void repeater_inject_fault(int what); // 1 = standby, 2 = sleep
void repeater_print_status(void); void repeater_print_status(void);
+170
View File
@@ -0,0 +1,170 @@
#include "settings.h"
#include "cfg_store.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
// The writer mutex spans validation against the current revision, NVS and
// publication. The radio never takes it. The spinlock only protects small
// in-memory snapshots; no logging, SPI, NVS or blocking calls run underneath it.
static SemaphoreHandle_t s_writer;
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static settings_snapshot_t s_desired;
static bool valid_change(const settings_change_t *change)
{
if (!change) return false;
int32_t v = change->value;
switch (change->key) {
case SETTINGS_REPEAT_DELAY_MS: return v >= 20 && v <= 1000;
case SETTINGS_TX_POWER: return v >= -9 && v <= 2;
case SETTINGS_REPEAT_ENABLED:
case SETTINGS_VERBOSE:
case SETTINGS_FEM_RX_CSD: return v == 0 || v == 1;
case SETTINGS_PREAMBLE_BITS:
return v == 0 || v == 8 || v == 16 || v == 24 || v == 32;
case SETTINGS_DUTY_BUDGET_PPM: return v >= 0 && v <= 100000;
case SETTINGS_TEST_LFIELD: return v >= 19 && v <= 200;
case SETTINGS_BEACON_PERIOD_MS: return v == 0 || (v >= 250 && v <= 600000);
case SETTINGS_WHITELIST:
if (change->whitelist_len > 8) return false;
for (unsigned i = 0; i < change->whitelist_len; i++) {
for (unsigned j = 0; j < i; j++) {
if (change->whitelist[i] == change->whitelist[j]) return false;
}
}
return true;
default: return false;
}
}
void settings_init(void)
{
s_writer = xSemaphoreCreateMutex();
configASSERT(s_writer);
repeater_cfg_t initial = g_cfg;
uint32_t value;
bool restored = false;
if (cfg_store_load_u32(CFG_KEY_DUTY_PPM, &value)) {
if (value <= 100000) {
initial.duty_budget_ppm = value;
restored = true;
} else {
printf("{\"event\":\"cfg_restore_invalid\",\"key\":\"duty_budget_ppm\",\"value\":%" PRIu32 "}\n", value);
}
}
if (cfg_store_load_u32(CFG_KEY_DELAY_MS, &value)) {
if (value >= 20 && value <= 1000) {
initial.repeat_delay_ms = value;
restored = true;
} else {
printf("{\"event\":\"cfg_restore_invalid\",\"key\":\"repeat_delay_ms\",\"value\":%" PRIu32 "}\n", value);
}
}
// No tasks have started: initialize the legacy display snapshot as well.
g_cfg = initial;
s_desired.values = initial;
s_desired.revision = 1;
s_desired.applied_revision = 0;
if (restored) {
printf("{\"event\":\"cfg_restore\",\"duty_budget_ppm\":%" PRIu32 ","
"\"repeat_delay_ms\":%" PRIu32 "}\n",
initial.duty_budget_ppm, initial.repeat_delay_ms);
}
fflush(stdout);
}
void settings_get_snapshot(settings_snapshot_t *out)
{
if (!out) return;
portENTER_CRITICAL(&s_lock);
*out = s_desired;
portEXIT_CRITICAL(&s_lock);
}
settings_result_t settings_update(const settings_change_t *change,
uint32_t expected_revision,
settings_snapshot_t *out)
{
if (!valid_change(change)) {
settings_get_snapshot(out);
return SETTINGS_INVALID;
}
if (!s_writer || xSemaphoreTake(s_writer, pdMS_TO_TICKS(1000)) != pdTRUE) {
settings_get_snapshot(out);
return SETTINGS_BUSY;
}
settings_snapshot_t next;
settings_get_snapshot(&next);
settings_result_t result = SETTINGS_OK;
if (expected_revision && expected_revision != next.revision) {
result = SETTINGS_CONFLICT;
goto done;
}
// Never wrap into revision 0 (unconditional) or reuse a stale revision.
if (next.revision == UINT32_MAX) {
result = SETTINGS_BUSY;
goto done;
}
switch (change->key) {
case SETTINGS_REPEAT_DELAY_MS: next.values.repeat_delay_ms = (uint32_t)change->value; break;
case SETTINGS_TX_POWER: next.values.tx_power_dbm = (int8_t)change->value; break;
case SETTINGS_REPEAT_ENABLED: next.values.repeat_enabled = change->value != 0; break;
case SETTINGS_VERBOSE: next.values.verbose = change->value != 0; break;
case SETTINGS_FEM_RX_CSD: next.values.fem_rx_csd = change->value != 0; break;
case SETTINGS_PREAMBLE_BITS: next.values.preamble_bits = (uint8_t)change->value; break;
case SETTINGS_DUTY_BUDGET_PPM: next.values.duty_budget_ppm = (uint32_t)change->value; break;
case SETTINGS_TEST_LFIELD: next.values.test_lfield = (uint8_t)change->value; break;
case SETTINGS_BEACON_PERIOD_MS: next.values.beacon_period_ms = (uint32_t)change->value; break;
case SETTINGS_WHITELIST:
memset(next.values.whitelist, 0, sizeof(next.values.whitelist));
memcpy(next.values.whitelist, change->whitelist,
change->whitelist_len * sizeof(change->whitelist[0]));
next.values.whitelist_len = change->whitelist_len;
break;
default:
result = SETTINGS_INVALID;
goto done;
}
const char *store_key = change->key == SETTINGS_REPEAT_DELAY_MS ? CFG_KEY_DELAY_MS
: change->key == SETTINGS_DUTY_BUDGET_PPM ? CFG_KEY_DUTY_PPM
: NULL;
if (store_key && !cfg_store_save_u32(store_key, (uint32_t)change->value)) {
result = SETTINGS_STORAGE_ERROR;
goto done;
}
portENTER_CRITICAL(&s_lock);
s_desired.values = next.values;
s_desired.revision = next.revision + 1;
// applied_revision may have advanced while NVS was committing; retain it.
portEXIT_CRITICAL(&s_lock);
done:
settings_get_snapshot(out);
xSemaphoreGive(s_writer);
return result;
}
bool settings_radio_pending(void)
{
portENTER_CRITICAL(&s_lock);
bool pending = s_desired.revision != s_desired.applied_revision;
portEXIT_CRITICAL(&s_lock);
return pending;
}
bool settings_radio_apply(repeater_cfg_t *active)
{
portENTER_CRITICAL(&s_lock);
bool pending = s_desired.revision != s_desired.applied_revision;
if (pending) {
*active = s_desired.values;
// This acknowledges the coherent copy, not successful hardware/RF operation.
s_desired.applied_revision = s_desired.revision;
}
portEXIT_CRITICAL(&s_lock);
return pending;
}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "repeater.h"
typedef struct {
uint32_t revision;
uint32_t applied_revision;
repeater_cfg_t values;
} settings_snapshot_t;
typedef enum {
SETTINGS_REPEAT_DELAY_MS,
SETTINGS_TX_POWER,
SETTINGS_REPEAT_ENABLED,
SETTINGS_VERBOSE,
SETTINGS_FEM_RX_CSD,
SETTINGS_PREAMBLE_BITS,
SETTINGS_DUTY_BUDGET_PPM,
SETTINGS_TEST_LFIELD,
SETTINGS_WHITELIST,
SETTINGS_BEACON_PERIOD_MS,
} settings_key_t;
typedef struct {
settings_key_t key;
int32_t value;
uint32_t whitelist[8];
uint8_t whitelist_len;
} settings_change_t;
typedef enum {
SETTINGS_OK,
SETTINGS_INVALID,
SETTINGS_CONFLICT,
SETTINGS_STORAGE_ERROR,
SETTINGS_BUSY,
} settings_result_t;
// Boot only, after cfg_store_init and before starting any consumer tasks.
// Restores the two persisted keys after range validation, keeping defaults otherwise.
void settings_init(void);
void settings_get_snapshot(settings_snapshot_t *out);
// expected_revision == 0 is unconditional (local console); network callers use >= 1.
// On failure the accepted values and revision are unchanged; out may be NULL.
settings_result_t settings_update(const settings_change_t *change,
uint32_t expected_revision,
settings_snapshot_t *out);
// Radio owner only, at an RX/processing loop boundary. Never waits on NVS or a mutex.
bool settings_radio_pending(void);
bool settings_radio_apply(repeater_cfg_t *active);
+286
View File
@@ -0,0 +1,286 @@
// Settings transport: WPA2 AP access plus same-origin, per-AP CSRF protection.
// The settings coordinator owns validation, persistence and radio handoff.
#include "settings_http.h"
#include "settings.h"
#include "wifi_debug.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include "cJSON.h"
#include "esp_random.h"
static char s_boot[9];
static char s_token[33];
static void response_headers(httpd_req_t *req)
{
httpd_resp_set_type(req, "application/json");
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
httpd_resp_set_hdr(req, "X-Content-Type-Options", "nosniff");
httpd_resp_set_hdr(req, "Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'");
}
static esp_err_t error_response(httpd_req_t *req, const char *status, const char *message)
{
char body[256];
int n = snprintf(body, sizeof(body), "{\"error\":\"%s\"}", message);
response_headers(req);
httpd_resp_set_status(req, status);
httpd_resp_set_hdr(req, "Connection", "close");
if (n > 0 && (size_t)n < sizeof(body)) httpd_resp_send(req, body, n);
// Some failures precede reading the body. Close rather than leave unread
// bytes on a keep-alive connection or spend time draining an oversized body.
return ESP_FAIL;
}
static bool trusted_request(httpd_req_t *req, bool writing)
{
char value[80];
if (httpd_req_get_hdr_value_str(req, "Host", value, sizeof(value)) != ESP_OK ||
(strcmp(value, "192.168.4.1") && strcmp(value, "192.168.4.1:80"))) return false;
if (httpd_req_get_hdr_value_len(req, "Origin")) {
if (httpd_req_get_hdr_value_str(req, "Origin", value, sizeof(value)) != ESP_OK ||
(strcmp(value, "http://192.168.4.1") && strcmp(value, "http://192.168.4.1:80"))) return false;
}
if (httpd_req_get_hdr_value_len(req, "Sec-Fetch-Site")) {
if (httpd_req_get_hdr_value_str(req, "Sec-Fetch-Site", value, sizeof(value)) != ESP_OK ||
(strcmp(value, "same-origin") && strcmp(value, "none"))) return false;
}
if (!writing) return true;
if (httpd_req_get_hdr_value_str(req, "X-CSRF-Token", value, sizeof(value)) != ESP_OK ||
strcmp(value, s_token)) return false;
return true;
}
static esp_err_t send_snapshot(httpd_req_t *req, const settings_snapshot_t *snapshot)
{
const repeater_cfg_t *v = &snapshot->values;
char ids[88];
size_t used = 0;
ids[0] = 0;
for (int i = 0; i < v->whitelist_len; i++) {
int n = snprintf(ids + used, sizeof(ids) - used, "%s\"%08" PRIX32 "\"",
i ? "," : "", v->whitelist[i]);
if (n < 0 || (size_t)n >= sizeof(ids) - used) return ESP_FAIL;
used += (size_t)n;
}
char body[1024];
int n = snprintf(body, sizeof(body),
"{\"boot_id\":\"%s\",\"revision\":%" PRIu32 ",\"applied_revision\":%" PRIu32
",\"csrf_token\":\"%s\",\"settings\":{"
"\"repeat_delay_ms\":%" PRIu32 ",\"tx_power\":%d,\"repeat_enabled\":%s,"
"\"verbose\":%s,\"fem_rx_csd\":%s,\"preamble_bits\":%u,"
"\"duty_budget_ppm\":%" PRIu32 ",\"test_lfield\":%u,\"whitelist\":[%s],"
"\"beacon_period_ms\":%" PRIu32 "}}",
s_boot, snapshot->revision, snapshot->applied_revision, s_token,
v->repeat_delay_ms, (int)v->tx_power_dbm, v->repeat_enabled ? "true" : "false",
v->verbose ? "true" : "false", v->fem_rx_csd ? "true" : "false", v->preamble_bits,
v->duty_budget_ppm, v->test_lfield, ids, v->beacon_period_ms);
if (n < 0 || (size_t)n >= sizeof(body)) return ESP_FAIL;
response_headers(req);
return httpd_resp_send(req, body, n);
}
static esp_err_t get_settings(httpd_req_t *req)
{
if (!trusted_request(req, false))
return error_response(req, "403 Forbidden", "Einstellungen nur unter http://192.168.4.1 öffnen.");
settings_snapshot_t snapshot;
settings_get_snapshot(&snapshot);
return send_snapshot(req, &snapshot);
}
// cJSON is recursive. Valid requests need only a root object and a whitelist
// array, so reject deeper nesting before parsing. Embedded NUL escapes would
// otherwise make C-string comparisons accept truncated keys or values.
static bool shallow_json(const char *body, size_t len)
{
bool quoted = false;
int depth = 0;
for (size_t i = 0; i < len; i++) {
unsigned char c = (unsigned char)body[i];
if (!c) return false;
if (quoted) {
if (c < 0x20) return false;
if (c == '\\') {
if (++i >= len) return false;
if (body[i] == 'u' && i + 4 < len && !memcmp(body + i + 1, "0000", 4)) return false;
} else if (c == '"') quoted = false;
} else if (c == '"') quoted = true;
else if (c == '{' || c == '[') { if (++depth > 2) return false; }
else if (c == '}' || c == ']') { if (--depth < 0) return false; }
}
return !quoted && depth == 0;
}
static cJSON *receive_body(httpd_req_t *req)
{
char type[64];
if (httpd_req_get_hdr_value_str(req, "Content-Type", type, sizeof(type)) != ESP_OK ||
strncasecmp(type, "application/json", 16) || (type[16] && type[16] != ';')) {
error_response(req, "415 Unsupported Media Type", "Die Anfrage muss JSON enthalten.");
return NULL;
}
if (!req->content_len || req->content_len > 512 || httpd_req_get_hdr_value_len(req, "Transfer-Encoding")) {
error_response(req, "400 Bad Request", "Die Anfrage ist leer, zu groß oder nicht unterstützt.");
return NULL;
}
char body[513];
size_t received = 0;
while (received < req->content_len) {
int n = httpd_req_recv(req, body + received, req->content_len - received);
if (n <= 0) {
error_response(req, "408 Request Timeout", "Die Anfrage wurde nicht vollständig empfangen.");
return NULL;
}
received += (size_t)n;
}
body[received] = 0;
cJSON *root = shallow_json(body, received)
? cJSON_ParseWithLengthOpts(body, received + 1, NULL, true) : NULL;
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
error_response(req, "400 Bad Request", "Ungültige JSON-Anfrage.");
return NULL;
}
return root;
}
static bool exact_fields(const cJSON *root, const char *const *names, size_t count)
{
unsigned seen = 0;
for (const cJSON *item = root->child; item; item = item->next) {
size_t i = 0;
while (i < count && strcmp(item->string, names[i])) i++;
if (i == count || (seen & (1u << i))) return false;
seen |= 1u << i;
}
return seen == (1u << count) - 1;
}
static bool correct_boot(const cJSON *root)
{
const cJSON *boot = cJSON_GetObjectItemCaseSensitive(root, "boot_id");
return cJSON_IsString(boot) && !strcmp(boot->valuestring, s_boot);
}
typedef enum { VALUE_NUMBER, VALUE_BOOL, VALUE_IDS } value_kind_t;
static const struct {
const char *name;
settings_key_t key;
value_kind_t kind;
} keys[] = {
{"repeat_delay_ms", SETTINGS_REPEAT_DELAY_MS, VALUE_NUMBER},
{"tx_power", SETTINGS_TX_POWER, VALUE_NUMBER},
{"repeat_enabled", SETTINGS_REPEAT_ENABLED, VALUE_BOOL},
{"verbose", SETTINGS_VERBOSE, VALUE_BOOL},
{"fem_rx_csd", SETTINGS_FEM_RX_CSD, VALUE_BOOL},
{"preamble_bits", SETTINGS_PREAMBLE_BITS, VALUE_NUMBER},
{"duty_budget_ppm", SETTINGS_DUTY_BUDGET_PPM, VALUE_NUMBER},
{"test_lfield", SETTINGS_TEST_LFIELD, VALUE_NUMBER},
{"whitelist", SETTINGS_WHITELIST, VALUE_IDS},
{"beacon_period_ms", SETTINGS_BEACON_PERIOD_MS, VALUE_NUMBER},
};
static bool parse_change(const cJSON *root, settings_change_t *change)
{
const cJSON *key = cJSON_GetObjectItemCaseSensitive(root, "key");
const cJSON *value = cJSON_GetObjectItemCaseSensitive(root, "value");
if (!cJSON_IsString(key)) return false;
size_t i = 0;
while (i < sizeof(keys) / sizeof(keys[0]) && strcmp(keys[i].name, key->valuestring)) i++;
if (i == sizeof(keys) / sizeof(keys[0])) return false;
memset(change, 0, sizeof(*change));
change->key = keys[i].key;
if (keys[i].kind == VALUE_BOOL) {
if (!cJSON_IsBool(value)) return false;
change->value = cJSON_IsTrue(value);
return true;
}
if (keys[i].kind == VALUE_NUMBER) {
if (!cJSON_IsNumber(value) || !(value->valuedouble >= INT32_MIN && value->valuedouble <= INT32_MAX)) return false;
change->value = (int32_t)value->valuedouble;
return value->valuedouble == change->value;
}
if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) > 8) return false;
for (const cJSON *id = value->child; id; id = id->next) {
if (!cJSON_IsString(id) || strlen(id->valuestring) != 8) return false;
uint32_t parsed = 0;
for (const char *p = id->valuestring; *p; p++) {
unsigned digit;
if (*p >= '0' && *p <= '9') digit = *p - '0';
else if (*p >= 'a' && *p <= 'f') digit = *p - 'a' + 10;
else if (*p >= 'A' && *p <= 'F') digit = *p - 'A' + 10;
else return false;
parsed = (parsed << 4) | digit;
}
change->whitelist[change->whitelist_len++] = parsed;
}
return true;
}
static esp_err_t post_settings(httpd_req_t *req)
{
if (!trusted_request(req, true))
return error_response(req, "403 Forbidden", "Zugriff abgelehnt. Einstellungen neu laden.");
cJSON *root = receive_body(req);
if (!root) return ESP_FAIL;
static const char *const fields[] = {"boot_id", "revision", "key", "value"};
const cJSON *revision = cJSON_GetObjectItemCaseSensitive(root, "revision");
settings_change_t change;
bool valid = exact_fields(root, fields, 4) && cJSON_IsNumber(revision) &&
revision->valuedouble >= 1 && revision->valuedouble <= UINT32_MAX &&
revision->valuedouble == (uint32_t)revision->valuedouble && parse_change(root, &change);
bool boot_ok = correct_boot(root);
uint32_t expected = valid ? (uint32_t)revision->valuedouble : 0;
cJSON_Delete(root);
if (!valid) return error_response(req, "400 Bad Request", "Ungültige Einstellung, Kennung oder Wertart.");
if (!boot_ok) return error_response(req, "409 Conflict", "Das Gerät wurde neu gestartet. Einstellungen neu laden.");
settings_snapshot_t snapshot;
switch (settings_update(&change, expected, &snapshot)) {
case SETTINGS_OK: return send_snapshot(req, &snapshot);
case SETTINGS_INVALID: return error_response(req, "400 Bad Request", "Wert außerhalb des erlaubten Bereichs oder doppelte Kennung.");
case SETTINGS_CONFLICT: return error_response(req, "409 Conflict", "Einstellungen wurden inzwischen geändert. Neu laden und prüfen.");
case SETTINGS_STORAGE_ERROR: return error_response(req, "503 Service Unavailable", "Speichern fehlgeschlagen. Die Einstellung wurde nicht übernommen.");
case SETTINGS_BUSY: return error_response(req, "503 Service Unavailable", "Eine andere Änderung läuft. Neu laden und erneut versuchen.");
default: return error_response(req, "500 Internal Server Error", "Die Einstellung konnte nicht übernommen werden.");
}
}
static esp_err_t disable_wifi(httpd_req_t *req)
{
if (!trusted_request(req, true))
return error_response(req, "403 Forbidden", "Zugriff abgelehnt. Einstellungen neu laden.");
cJSON *root = receive_body(req);
if (!root) return ESP_FAIL;
static const char *const fields[] = {"boot_id"};
bool valid = exact_fields(root, fields, 1);
bool boot_ok = correct_boot(root);
cJSON_Delete(root);
if (!valid) return error_response(req, "400 Bad Request", "Ungültige WLAN-Anfrage.");
if (!boot_ok) return error_response(req, "409 Conflict", "Das Gerät wurde neu gestartet. Einstellungen neu laden.");
response_headers(req);
esp_err_t err = httpd_resp_send(req, "{\"ok\":true}", HTTPD_RESP_USE_STRLEN);
if (err == ESP_OK) wifi_debug_disable();
return err;
}
esp_err_t settings_http_register(httpd_handle_t server, uint32_t boot_id)
{
snprintf(s_boot, sizeof(s_boot), "%08" PRIx32, boot_id);
uint8_t random[16];
esp_fill_random(random, sizeof(random)); // Wi-Fi hardware entropy is active.
for (size_t i = 0; i < sizeof(random); i++) snprintf(s_token + i * 2, 3, "%02x", random[i]);
const httpd_uri_t routes[] = {
{.uri = "/api/settings", .method = HTTP_GET, .handler = get_settings},
{.uri = "/api/settings", .method = HTTP_POST, .handler = post_settings},
{.uri = "/api/wifi/disable", .method = HTTP_POST, .handler = disable_wifi},
};
for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) {
esp_err_t err = httpd_register_uri_handler(server, &routes[i]);
if (err != ESP_OK) return err;
}
return ESP_OK;
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <stdint.h>
#include "esp_http_server.h"
// Register after starting Wi-Fi so a fresh CSRF token has hardware entropy.
esp_err_t settings_http_register(httpd_handle_t server, uint32_t boot_id);
+36 -14
View File
@@ -55,8 +55,8 @@ static spi_device_handle_t s_spi;
static sx126x_irq_cb_t s_irq_cb; static sx126x_irq_cb_t s_irq_cb;
static uint8_t s_rx_payload_len = 255; static uint8_t s_rx_payload_len = 255;
static int8_t s_tx_dbm = -9; static int8_t s_tx_dbm = -9;
static bool s_tx_fdev_t1; // deviation currently programmed for T-mode TX
static SemaphoreHandle_t s_lock; // serializes SPI access across tasks static SemaphoreHandle_t s_lock; // serializes SPI access across tasks
static bool s_pa_low = true; // true = +10 dBm-optimal PA row (lowest output)
// Preamble detector length. Shorter = more sensitive but more false syncs, // Preamble detector length. Shorter = more sensitive but more false syncs,
// and every false sync costs one fixed-255-byte RX window (~12 ms). // and every false sync costs one fixed-255-byte RX window (~12 ms).
// SX126x codes: 0x00 off, 0x04 = 8 bits, 0x05 = 16, 0x06 = 24, 0x07 = 32. // SX126x codes: 0x00 off, 0x04 = 8 bits, 0x05 = 16, 0x06 = 24, 0x07 = 32.
@@ -308,15 +308,11 @@ bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len)
uint8_t f[4] = {frf >> 24, frf >> 16, frf >> 8, frf}; uint8_t f[4] = {frf >> 24, frf >> 16, frf >> 8, frf};
ok &= cmd(OP_SET_RF_FREQUENCY, f, 4); ok &= cmd(OP_SET_RF_FREQUENCY, f, 4);
// PA config. SX1262 datasheet table 13-21 documents optimal settings // SX1262 datasheet table 13-21: +14 dBm is the lowest valid optimal
// per target power; we deliberately use the +10 dBm-optimal row // PA row for SX1262. The superficially lower (0x01, 0x00) row is the
// (paDutyCycle=0x01, hpMax=0x00) because it yields the lowest output // +10 dBm SX1261 row and selecting it with deviceSel=SX1262 costs about
// this chip supports, and the external KCT8103L PA adds gain after it. // 32 dB on this board. The external KCT8103L supplies the remaining gain.
// s_pa_low=false selects the +14 dBm row for comparison experiments. ok &= cmd(OP_SET_PA_CONFIG, (uint8_t[]){0x02, 0x02, 0x00, 0x01}, 4);
ok &= s_pa_low
? cmd(OP_SET_PA_CONFIG, (uint8_t[]){0x01, 0x00, 0x00, 0x01}, 4)
: cmd(OP_SET_PA_CONFIG, (uint8_t[]){0x02, 0x02, 0x00, 0x01}, 4);
ok &= sx126x_set_tx_power(s_tx_dbm);
// OCP // OCP
uint8_t ocp = BOARD_SX1262_OCP; uint8_t ocp = BOARD_SX1262_OCP;
@@ -337,6 +333,7 @@ bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len)
0x00, 0xB8, 0x52, // fdev 0x00, 0xB8, 0x52, // fdev
}; };
ok &= cmd(OP_SET_MODULATION, mod, 8); ok &= cmd(OP_SET_MODULATION, mod, 8);
s_tx_fdev_t1 = false;
// Sync word = wM-Bus T/C access code 0x543D. The two C-mode "mode bytes" // Sync word = wM-Bus T/C access code 0x543D. The two C-mode "mode bytes"
// (54CD = frame A, 543D = frame B) are received/sent as payload so that // (54CD = frame A, 543D = frame B) are received/sent as payload so that
@@ -384,7 +381,7 @@ bool sx126x_restore_rx_payload_len(void)
bool sx126x_set_tx_power(int8_t dbm) bool sx126x_set_tx_power(int8_t dbm)
{ {
if (dbm < -9) dbm = -9; if (dbm < -9) dbm = -9;
if (dbm > 14) dbm = 14; // deliberately capped: external FEM adds gain if (dbm > 2) dbm = 2; // KCT8103L follows; known-good V4.3 firmware uses +2
s_tx_dbm = dbm; s_tx_dbm = dbm;
uint8_t tp[2] = {(uint8_t)dbm, 0x02}; // ramp 40 us uint8_t tp[2] = {(uint8_t)dbm, 0x02}; // ramp 40 us
return cmd(OP_SET_TX_PARAMS, tp, 2); return cmd(OP_SET_TX_PARAMS, tp, 2);
@@ -423,10 +420,32 @@ bool sx126x_set_rx(void)
return cmd(OP_SET_RX, (uint8_t[]){0xFF, 0xFF, 0xFF}, 3); return cmd(OP_SET_RX, (uint8_t[]){0xFF, 0xFF, 0xFF}, 3);
} }
bool sx126x_start_tx(const uint8_t *buf, uint8_t len) // C and T transmit differ only in FSK deviation: 45 kHz (C) vs 50 kHz (T).
// RX is unaffected (deviation is a TX-only GFSK parameter; the 234.3 kHz
// RX bandwidth covers both), so the swap is done lazily per TX.
static bool set_tx_deviation(bool t1)
{
if (t1 == s_tx_fdev_t1) return true;
// fdev(C) = 45e3 * 2^25 / 32e6 = 47186 = 0x00B852
// fdev(T) = 50e3 * 2^25 / 32e6 = 52429 = 0x00CCCD
uint8_t mod[8] = {
0x00, 0x28, 0x00, // bitrate 100 kbps
0x00, // no pulse shaping
0x0A, // RX BW 234.3 kHz
0x00,
t1 ? 0xCC : 0xB8,
t1 ? 0xCD : 0x52,
};
if (!cmd(OP_SET_MODULATION, mod, 8)) return false;
s_tx_fdev_t1 = t1;
return true;
}
bool sx126x_start_tx_mode(const uint8_t *buf, uint8_t len, bool t1_deviation)
{ {
if (!sx126x_standby()) return false; if (!sx126x_standby()) return false;
sx126x_clear_irq(SX126X_IRQ_ALL); sx126x_clear_irq(SX126X_IRQ_ALL);
if (!set_tx_deviation(t1_deviation)) return false;
if (!set_packet_params(len)) return false; if (!set_packet_params(len)) return false;
// WriteBuffer needs op + offset + payload in one transaction // WriteBuffer needs op + offset + payload in one transaction
@@ -445,6 +464,11 @@ bool sx126x_start_tx(const uint8_t *buf, uint8_t len)
return true; return true;
} }
bool sx126x_start_tx(const uint8_t *buf, uint8_t len)
{
return sx126x_start_tx_mode(buf, len, false);
}
uint16_t sx126x_get_irq(void) uint16_t sx126x_get_irq(void)
{ {
uint8_t st[2] = {0, 0}; uint8_t st[2] = {0, 0};
@@ -519,7 +543,5 @@ uint8_t sx126x_get_status(void)
return rx[1]; return rx[1];
} }
void sx126x_set_pa_low(bool low) { s_pa_low = low; }
void sx126x_set_preamble_detect(uint8_t code) { s_preamble_det = code; } void sx126x_set_preamble_detect(uint8_t code) { s_preamble_det = code; }
uint8_t sx126x_get_preamble_detect(void) { return s_preamble_det; }
+5 -4
View File
@@ -31,7 +31,7 @@ bool sx126x_init(sx126x_diag_t *diag);
// rx_payload_len is the fixed RX capture length (we truncate in software). // rx_payload_len is the fixed RX capture length (we truncate in software).
bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len); bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len);
bool sx126x_set_tx_power(int8_t dbm); // -9 .. +14 (PA config capped) bool sx126x_set_tx_power(int8_t dbm); // -9 .. +2 (external FEM follows)
bool sx126x_set_rx(void); // continuous RX, FEM to RX path bool sx126x_set_rx(void); // continuous RX, FEM to RX path
bool sx126x_standby(void); bool sx126x_standby(void);
bool sx126x_config_intact(void); // sync-word readback still correct bool sx126x_config_intact(void); // sync-word readback still correct
@@ -40,7 +40,9 @@ bool sx126x_inject_sleep(void); // fault injection: SLEEP, config lost
// Transmit buf as GFSK payload (sync word prepended by radio). // Transmit buf as GFSK payload (sync word prepended by radio).
// Handles FEM CTX switching. Blocking until commands issued; TX-done is // Handles FEM CTX switching. Blocking until commands issued; TX-done is
// signalled via DIO1/IRQ. timeout handled by caller. // signalled via DIO1/IRQ. timeout handled by caller.
bool sx126x_start_tx(const uint8_t *buf, uint8_t len); bool sx126x_start_tx(const uint8_t *buf, uint8_t len); // C-mode deviation
// t1_deviation = true selects 50 kHz FSK deviation (T-mode); C uses 45 kHz
bool sx126x_start_tx_mode(const uint8_t *buf, uint8_t len, bool t1_deviation);
// Restore fixed RX payload length after a TX (packet params are shared). // Restore fixed RX payload length after a TX (packet params are shared).
bool sx126x_restore_rx_payload_len(void); bool sx126x_restore_rx_payload_len(void);
@@ -59,10 +61,9 @@ bool sx126x_raw(uint8_t op, const uint8_t *args, size_t n_tx,
// FEM control (exposed for diagnostics) // FEM control (exposed for diagnostics)
void fem_set_tx(bool tx); void fem_set_tx(bool tx);
void fem_power(bool on); void fem_power(bool on);
// Desired FEM/preamble settings are mutated only by the radio owner at a loop boundary.
void fem_set_rx_csd(bool en); // LNA experiment: FEM CSD level in RX void fem_set_rx_csd(bool en); // LNA experiment: FEM CSD level in RX
void sx126x_set_pa_low(bool low); // PA table: true = lowest documented output
void sx126x_set_preamble_detect(uint8_t code); // 0x00 off, 0x04=8b, 0x05=16b, 0x06=24b, 0x07=32b void sx126x_set_preamble_detect(uint8_t code); // 0x00 off, 0x04=8b, 0x05=16b, 0x06=24b, 0x07=32b
uint8_t sx126x_get_preamble_detect(void);
// Registered by caller before init; invoked from DIO1 GPIO ISR. // Registered by caller before init; invoked from DIO1 GPIO ISR.
typedef void (*sx126x_irq_cb_t)(int64_t timestamp_us); typedef void (*sx126x_irq_cb_t)(int64_t timestamp_us);
+485
View File
@@ -0,0 +1,485 @@
// Local status UI: SSD1306 128x64 over I2C + PRG button.
// Implements docs/FUTURE_UI.md within its constraints:
// - separate low-priority task on core 0 (radio task is pinned to core 1);
// rendering can be starved without consequence
// - never touches the SX1262: reads g_stats / g_cfg / g_ui snapshots only
// - GPIO0 (BOOT strap) is sampled only after boot, debounced
// - Vext is driven once at init and never toggled; blanking uses the
// panel's display-off command
// - every button action that changes behaviour emits a JSON event so the
// serial log stays the source of truth
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_timer.h"
#include "driver/gpio.h"
#include "driver/i2c_master.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_panel_vendor.h"
#include "board.h"
#include "repeater.h"
#include "settings.h"
#include "duty_ledger.h"
#include "wifi_debug.h"
#include "wifi_qr.h"
#include "font5x7.h"
#define UI_W 128
#define UI_H 64
#define UI_COLS 21 // 128 / 6px cell
#define UI_ROWS 8 // 64 / 8px cell
#define UI_PAGES 6
#define UI_TICK_MS 20
#define UI_RENDER_TICKS 25 // 500 ms refresh
#define UI_DEBOUNCE_TICKS 2 // 40 ms
#define UI_LONG_PRESS_MS 1500
#define UI_SLEEP_US (180 * 1000000LL)
#define UI_BEACON_PERIOD_MS 3000 // long-press toggle value; 907 ppm at L=19
static esp_lcd_panel_handle_t s_panel;
static uint8_t s_fb[UI_W * UI_H / 8];
static char s_text[UI_ROWS][UI_COLS + 1];
static int s_page;
static bool s_on = true;
static int64_t s_last_activity;
static uint8_t s_wifi_qr[WIFI_QR_BYTES];
static bool s_qr_ready;
static bool s_show_qr;
static const char *s_settings_error;
static int64_t s_settings_error_until;
static void ui_log(const char *cmd, uint32_t value)
{
printf("{\"event\":\"ui_action\",\"cmd\":\"%s\",\"value\":%" PRIu32 "}\n",
cmd, value);
fflush(stdout);
}
// ------------------------------------------------------------- rendering
static void put(int row, const char *fmt, ...)
{
if (row < 0 || row >= UI_ROWS) return;
char buf[UI_COLS + 1];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
snprintf(s_text[row], sizeof(s_text[row]), "%s", buf);
}
static void blit(void)
{
memset(s_fb, 0, sizeof(s_fb));
for (int row = 0; row < UI_ROWS; row++) {
for (int col = 0; s_text[row][col] && col < UI_COLS; col++) {
unsigned c = (unsigned char)s_text[row][col];
if (c < FONT5X7_FIRST || c > FONT5X7_LAST) c = '?';
const uint8_t *g = font5x7[c - FONT5X7_FIRST];
uint8_t *dst = &s_fb[row * UI_W + col * 6];
for (int x = 0; x < FONT5X7_W; x++) dst[x] = g[x];
}
}
if (s_show_qr) {
for (int page = 0; page < WIFI_QR_SIDE / 8; page++)
memcpy(&s_fb[page * UI_W], &s_wifi_qr[page * WIFI_QR_SIDE], WIFI_QR_SIDE);
}
esp_lcd_panel_draw_bitmap(s_panel, 0, 0, UI_W, UI_H, s_fb);
}
static void fmt_age(int64_t ts_us, char *out, size_t n)
{
if (ts_us <= 0) {
snprintf(out, n, "--");
return;
}
int64_t s64 = (esp_timer_get_time() - ts_us) / 1000000LL;
unsigned s = s64 < 0 ? 0
: (s64 > 359999 ? 359999u : (unsigned)s64); // cap 99h
if (s < 100) snprintf(out, n, "%us", s);
else if (s < 6000) snprintf(out, n, "%um", s / 60);
else snprintf(out, n, "%uh", s / 3600);
}
static void fmt_uptime(char *out, size_t n)
{
int64_t s64 = esp_timer_get_time() / 1000000LL;
unsigned s = s64 > 3599999 ? 3599999u : (unsigned)s64; // cap 999h
if (s < 3600) snprintf(out, n, "%um%02us", s / 60, s % 60);
else snprintf(out, n, "%uh%02um", s / 3600, (s % 3600) / 60);
}
static const char *tx_result_text(const char *result)
{
if (strcmp(result, "ok") == 0) return "OK";
if (strcmp(result, "ok_polled") == 0) return "OK Abfrage";
if (strcmp(result, "start_failed") == 0) return "Startfehler";
if (strcmp(result, "radio_timeout") == 0) return "Zeitlimit";
if (strcmp(result, "irq_timeout") == 0) return "Kein Ende";
return "Unbekannt";
}
static void page_status(void)
{
char up[12], rx_age[8], tx_age[8];
fmt_uptime(up, sizeof(up));
fmt_age(g_ui.rx_ts_us, rx_age, sizeof(rx_age));
fmt_age(g_ui.tx_ts_us, tx_age, sizeof(tx_age));
put(0, "wM-Bus 868.95 MHz");
put(1, "Seit %-7s Wdh %s", up, g_cfg.repeat_enabled ? "EIN" : "AUS");
put(2, "RX %-5" PRIu32 " GUT %" PRIu32,
g_stats.rx_candidates, g_stats.rx_valid);
put(3, "TX %" PRIu32 "/%" PRIu32 " Test %" PRIu32,
g_stats.tx_success, g_stats.tx_attempts, g_cfg.beacon_period_ms);
if (g_ui.rx_ts_us) {
put(4, "Empf. %ddBm %s", (int)g_ui.rx_rssi_dbm, rx_age);
} else {
put(4, "Empf. --");
}
if (g_ui.tx_ts_us) {
put(5, "TX %s %s", tx_result_text(g_ui.tx_result), tx_age);
} else {
put(5, "TX --");
}
uint64_t budget = (uint64_t)g_cfg.duty_budget_ppm
* DUTY_LEDGER_WINDOW_US / 1000000ULL;
if (budget) {
uint64_t used = repeater_duty_used_us();
unsigned pct = (unsigned)(used * 100 / budget);
if (pct > 100) pct = 100;
char bar[10];
unsigned fill = pct * 9 / 100;
for (unsigned i = 0; i < 9; i++) bar[i] = i < fill ? '#' : ' ';
bar[9] = 0;
put(6, "Sende%3u%% [%s]", pct, bar);
} else {
put(6, "Sendelimit AUS");
}
if (g_ui.hb_ts_us) {
put(7, "Funk %s Konfig %s",
g_ui.chip_mode == 5 ? "RX" : "!!", g_ui.config_intact ? "OK" : "!!");
} else {
put(7, "Funk --");
}
}
static void page_health(void)
{
put(0, "FUNKZUSTAND");
put(1, "Erholt %" PRIu32 " Neu %" PRIu32,
g_stats.recoveries, g_stats.radio_reinit + g_stats.fem_reinit);
put(2, "CRC-Fehl %" PRIu32 " Lng %" PRIu32,
g_stats.rx_crc_fail, g_stats.rx_len_invalid);
put(3, "T1 %" PRIu32 " Kein-C1 %" PRIu32,
g_stats.rx_t1, g_stats.rx_not_c1);
put(4, "Doppelt %" PRIu32 " Limit %" PRIu32,
g_stats.tx_suppressed_dup, g_stats.tx_suppressed_duty);
put(5, "TX-Frist %" PRIu32 " Fehl %" PRIu32,
g_stats.tx_timeout, g_stats.tx_failures);
if (g_ui.hb_ts_us) put(6, "Pegel %ddBm", (int)g_ui.rssi_dbm);
else put(6, "Pegel --");
put(7, "Halten: Zaehler null");
}
static void page_last(void)
{
put(0, "LETZTES TELEGRAMM");
if (!g_ui.rx_ts_us) {
put(1, "Noch kein Empfang");
for (int i = 2; i < UI_ROWS; i++) put(i, "%s", "");
return;
}
char age[8];
fmt_age(g_ui.rx_ts_us, age, sizeof(age));
put(1, "Zaehler %08" PRIX32, g_ui.rx_meter_id);
put(2, "Laenge %d Format %c", (int)g_ui.rx_len, g_ui.rx_format);
put(3, "CRC %s %ddBm",
g_ui.rx_crc_ok ? "OK" : "FALSCH", (int)g_ui.rx_rssi_dbm);
put(4, "Kennwert %08" PRIx32, g_ui.rx_hash);
put(5, "Alter %s", age);
put(6, "TX: %s", g_ui.tx_ts_us ? tx_result_text(g_ui.tx_result) : "--");
put(7, "%s", "");
}
static void page_config(void)
{
put(0, "EINSTELLUNGEN");
put(1, "Warte %" PRIu32 "ms TX %d",
g_cfg.repeat_delay_ms, (int)g_cfg.tx_power_dbm);
put(2, "Funklimit %" PRIu32 "ppm", g_cfg.duty_budget_ppm);
if (g_cfg.beacon_period_ms) put(3, "Testsignal %" PRIu32 "ms", g_cfg.beacon_period_ms);
else put(3, "Testsignal AUS");
put(4, "Wiederholen %s", g_cfg.repeat_enabled ? "EIN" : "AUS");
put(5, "Erlaubte IDs %d", g_cfg.whitelist_len);
put(6, "%s", "");
put(7, "Halten: Test ein/aus");
}
static void page_wifi(void)
{
wifi_debug_status_t wifi;
wifi_debug_status(&wifi);
for (int i = 0; i < UI_ROWS; i++) put(i, "%s", "");
put(0, "WLAN-DIAGNOSE");
switch (wifi.state) {
case WIFI_DEBUG_ON:
put(1, "EIN - kein Internet");
put(2, "%s", wifi.ssid);
put(3, "Passwort %s", wifi.password);
put(4, "http://192.168.4.1");
put(6, "Weiter: WLAN-QR-Code");
put(7, "Halten: WLAN aus");
break;
case WIFI_DEBUG_STARTING:
put(2, "Startet...");
break;
case WIFI_DEBUG_STOPPING:
put(2, "Wird beendet...");
break;
case WIFI_DEBUG_ERROR:
put(2, "Fehler 0x%" PRIX32, (uint32_t)wifi.error);
put(7, "Halten: Neu versuchen");
break;
default:
put(2, "AUS");
put(4, "Diagnose per Handy");
put(7, "Halten: WLAN ein");
break;
}
}
static void page_wifi_qr(void)
{
wifi_debug_status_t wifi;
wifi_debug_status(&wifi);
if (wifi.state != WIFI_DEBUG_ON) {
page_wifi();
return;
}
// Credentials are generated once and cannot change through the UI/API.
if (!s_qr_ready) s_qr_ready = wifi_qr_bitmap(wifi.ssid, wifi.password, s_wifi_qr);
if (!s_qr_ready) {
page_wifi();
put(6, "QR defekt: Passwort");
return;
}
for (int i = 0; i < UI_ROWS; i++) put(i, "%s", "");
put(0, " WLAN: QR");
put(1, " scannen");
put(3, " Oeffnen:");
put(4, " 192.168.");
put(5, " 4.1");
put(7, " Halten:AUS");
s_show_qr = true;
}
static void render(void)
{
s_show_qr = false;
switch (s_page) {
case 0: page_status(); break;
case 1: page_health(); break;
case 2: page_last(); break;
case 3: page_config(); break;
case 4: page_wifi(); break;
default: page_wifi_qr(); break;
}
if (s_settings_error && esp_timer_get_time() < s_settings_error_until)
put(6, "%s", s_settings_error);
blit();
}
// --------------------------------------------------------------- actions
static void toggle_setting(settings_key_t key)
{
settings_result_t result = SETTINGS_CONFLICT;
settings_change_t change = {.key = key};
// Toggle the accepted state, not g_cfg (which may still be pending).
// Revision CAS prevents an intervening web/USB edit from being overwritten.
for (unsigned attempt = 0; attempt < 3; attempt++) {
settings_snapshot_t snapshot;
settings_get_snapshot(&snapshot);
change.value = key == SETTINGS_REPEAT_ENABLED
? !snapshot.values.repeat_enabled
: (snapshot.values.beacon_period_ms ? 0 : UI_BEACON_PERIOD_MS);
result = settings_update(&change, snapshot.revision, NULL);
if (result != SETTINGS_CONFLICT) break;
}
const char *command = key == SETTINGS_REPEAT_ENABLED
? "set repeat_enabled" : "set beacon_period_ms";
if (result == SETTINGS_OK) {
s_settings_error = NULL;
ui_log(command, (uint32_t)change.value);
return;
}
switch (result) {
case SETTINGS_CONFLICT: s_settings_error = "Geaendert: neu halten"; break;
case SETTINGS_STORAGE_ERROR: s_settings_error = "Speichern gescheitert"; break;
case SETTINGS_INVALID: s_settings_error = "Wert ungueltig"; break;
default: s_settings_error = "Belegt: neu halten"; break;
}
s_settings_error_until = esp_timer_get_time() + 5000000LL;
printf("{\"event\":\"ui_action\",\"cmd\":\"%s\",\"ok\":false,\"error\":\"%s\"}\n",
command, s_settings_error);
fflush(stdout);
}
static void long_action(void)
{
switch (s_page) {
case 0:
toggle_setting(SETTINGS_REPEAT_ENABLED);
break;
case 1:
memset(&g_stats, 0, sizeof(g_stats));
ui_log("clear_stats", 1);
break;
case 3:
toggle_setting(SETTINGS_BEACON_PERIOD_MS);
break;
case 4:
case 5:
ui_log("wifi_debug_toggle", 1);
wifi_debug_toggle();
break;
default:
break;
}
}
static void set_display(bool on)
{
if (on == s_on) return;
s_on = on;
esp_lcd_panel_disp_on_off(s_panel, on);
}
// ------------------------------------------------------------ bring-up
static bool hw_init(void)
{
// External rail on (active low), then let it settle before touching
// the panel. Never toggled again (docs/FUTURE_UI.md constraint 4).
gpio_config_t vext = {
.pin_bit_mask = 1ULL << BOARD_VEXT,
.mode = GPIO_MODE_OUTPUT,
};
if (gpio_config(&vext) != ESP_OK) return false;
gpio_set_level(BOARD_VEXT, 0);
vTaskDelay(pdMS_TO_TICKS(100));
gpio_config_t btn = {
.pin_bit_mask = 1ULL << BOARD_BTN_PRG,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
};
if (gpio_config(&btn) != ESP_OK) return false;
i2c_master_bus_config_t bus_cfg = {
.i2c_port = I2C_NUM_0,
.sda_io_num = BOARD_OLED_SDA,
.scl_io_num = BOARD_OLED_SCL,
.clk_source = I2C_CLK_SRC_DEFAULT,
.glitch_ignore_cnt = 7,
.flags.enable_internal_pullup = true,
};
i2c_master_bus_handle_t bus;
if (i2c_new_master_bus(&bus_cfg, &bus) != ESP_OK) return false;
esp_lcd_panel_io_i2c_config_t io_cfg = {
.dev_addr = 0x3C,
.scl_speed_hz = 400000,
.control_phase_bytes = 1,
.lcd_cmd_bits = 8,
.lcd_param_bits = 8,
.dc_bit_offset = 6,
};
esp_lcd_panel_io_handle_t io;
if (esp_lcd_new_panel_io_i2c(bus, &io_cfg, &io) != ESP_OK) return false;
esp_lcd_panel_ssd1306_config_t ssd_cfg = { .height = UI_H };
esp_lcd_panel_dev_config_t panel_cfg = {
.bits_per_pixel = 1,
.reset_gpio_num = BOARD_OLED_RST,
.vendor_config = &ssd_cfg,
};
if (esp_lcd_new_panel_ssd1306(io, &panel_cfg, &s_panel) != ESP_OK) return false;
if (esp_lcd_panel_reset(s_panel) != ESP_OK) return false;
if (esp_lcd_panel_init(s_panel) != ESP_OK) return false;
// Heltec mounts the module rotated 180 degrees; matches the vendor
// examples' flipScreenVertically().
esp_lcd_panel_mirror(s_panel, true, true);
return esp_lcd_panel_disp_on_off(s_panel, true) == ESP_OK;
}
// ---------------------------------------------------------------- task
static void ui_task(void *arg)
{
(void)arg;
// The radio task owns boot; give it time to bring the RF path up
// before the I2C bus starts drawing current and printing.
vTaskDelay(pdMS_TO_TICKS(500));
bool ok = hw_init();
printf("{\"event\":\"ui_init\",\"ok\":%s}\n", ok ? "true" : "false");
fflush(stdout);
if (!ok) vTaskDelete(NULL);
s_last_activity = esp_timer_get_time();
int render_div = 0;
int held_ticks = 0;
bool long_fired = false;
bool was_off_at_press = false;
render();
for (;;) {
vTaskDelay(pdMS_TO_TICKS(UI_TICK_MS));
bool pressed = gpio_get_level(BOARD_BTN_PRG) == 0;
if (pressed) {
if (held_ticks == 0) was_off_at_press = !s_on;
held_ticks++;
if (!long_fired
&& held_ticks * UI_TICK_MS >= UI_LONG_PRESS_MS) {
long_fired = true;
s_last_activity = esp_timer_get_time();
set_display(true);
if (!was_off_at_press) long_action();
render();
}
} else {
if (held_ticks >= UI_DEBOUNCE_TICKS && !long_fired) {
s_last_activity = esp_timer_get_time();
if (s_on && !was_off_at_press) {
s_page = (s_page + 1) % UI_PAGES;
}
set_display(true);
render();
}
held_ticks = 0;
long_fired = false;
}
if (s_on && esp_timer_get_time() - s_last_activity > UI_SLEEP_US) {
set_display(false);
}
if (s_on && ++render_div >= UI_RENDER_TICKS) {
render_div = 0;
render();
}
}
}
void ui_start(void)
{
xTaskCreatePinnedToCore(ui_task, "ui", 4096, NULL, 3, NULL, 0);
}
+6
View File
@@ -0,0 +1,6 @@
// Local SSD1306 + PRG-button status UI (docs/FUTURE_UI.md).
// Non-fatal: if the display is absent or I2C init fails, the task logs
// {"event":"ui_init","ok":false} and exits; the repeater is unaffected.
#pragma once
void ui_start(void);
+1022
View File
File diff suppressed because it is too large Load Diff
+385
View File
@@ -0,0 +1,385 @@
/*
* QR Code generator library (C)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* This library creates QR Code symbols, which is a type of two-dimension barcode.
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
* A QR Code structure is an immutable square grid of dark and light cells.
* The library provides functions to create a QR Code from text or binary data.
* The library covers the QR Code Model 2 specification, supporting all versions (sizes)
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
*
* Ways to create a QR Code object:
* - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary().
* - Low level: Custom-make the list of segments and call
* qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced().
* (Note that all ways require supplying the desired error correction level and various byte buffers.)
*/
/*---- Enum and struct types----*/
/*
* The error correction level in a QR Code symbol.
*/
enum qrcodegen_Ecc {
// Must be declared in ascending order of error protection
// so that an internal qrcodegen function works properly
qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords
qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords
qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords
};
/*
* The mask pattern used in a QR Code symbol.
*/
enum qrcodegen_Mask {
// A special value to tell the QR Code encoder to
// automatically select an appropriate mask pattern
qrcodegen_Mask_AUTO = -1,
// The eight actual mask patterns
qrcodegen_Mask_0 = 0,
qrcodegen_Mask_1,
qrcodegen_Mask_2,
qrcodegen_Mask_3,
qrcodegen_Mask_4,
qrcodegen_Mask_5,
qrcodegen_Mask_6,
qrcodegen_Mask_7,
};
/*
* Describes how a segment's data bits are interpreted.
*/
enum qrcodegen_Mode {
qrcodegen_Mode_NUMERIC = 0x1,
qrcodegen_Mode_ALPHANUMERIC = 0x2,
qrcodegen_Mode_BYTE = 0x4,
qrcodegen_Mode_KANJI = 0x8,
qrcodegen_Mode_ECI = 0x7,
};
/*
* A segment of character/binary/control data in a QR Code symbol.
* The mid-level way to create a segment is to take the payload data
* and call a factory function such as qrcodegen_makeNumeric().
* The low-level way to create a segment is to custom-make the bit buffer
* and initialize a qrcodegen_Segment struct with appropriate values.
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
* Moreover, the maximum allowed bit length is 32767 because
* the largest QR Code (version 40) has 31329 modules.
*/
struct qrcodegen_Segment {
// The mode indicator of this segment.
enum qrcodegen_Mode mode;
// The length of this segment's unencoded data. Measured in characters for
// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
// Always zero or positive. Not the same as the data's bit length.
int numChars;
// The data bits of this segment, packed in bitwise big endian.
// Can be null if the bit length is zero.
uint8_t *data;
// The number of valid data bits used in the buffer. Requires
// 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8.
// The character count (numChars) must agree with the mode and the bit buffer length.
int bitLength;
};
/*---- Macro constants and functions ----*/
#define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard
#define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard
// Calculates the number of bytes needed to store any QR Code up to and including the given version number,
// as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];'
// can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16).
// Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX.
#define qrcodegen_BUFFER_LEN_FOR_VERSION(n) ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1)
// The worst-case number of bytes needed to store one QR Code, up to and including
// version 40. This value equals 3918, which is just under 4 kilobytes.
// Use this more convenient value to avoid calculating tighter memory bounds for buffers.
#define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX)
/*---- Functions (high level) to generate QR Codes ----*/
/*
* Encodes the given text string to a QR Code, returning true if successful.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
*
* The input text must be encoded in UTF-8 and contain no NULs.
* Requires 1 <= minVersion <= maxVersion <= 40.
*
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
*
* About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion):
* - Before calling the function:
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The initial state of both ranges can be uninitialized
* because the function always writes before reading.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* If successful, the resulting QR Code may use numeric,
* alphanumeric, or byte mode to encode the text.
*
* In the most optimistic case, a QR Code at version 40 with low ECC
* can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string
* up to 4296 characters, or any digit string up to 7089 characters.
* These numbers represent the hard upper limit of the QR Code standard.
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*/
bool qrcodegen_encodeText(const char *text, uint8_t tempBuffer[], uint8_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
/*
* Encodes the given binary data to a QR Code, returning true if successful.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
*
* Requires 1 <= minVersion <= maxVersion <= 40.
*
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
*
* About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion):
* - Before calling the function:
* - The array ranges dataAndTemp[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The input array range dataAndTemp[0 : dataLen] should normally be
* valid UTF-8 text, but is not required by the QR Code standard.
* - The initial state of dataAndTemp[dataLen : len] and qrcode[0 : len]
* can be uninitialized because the function always writes before reading.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - dataAndTemp contains no useful data and should be treated as entirely uninitialized.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* If successful, the resulting QR Code will use byte mode to encode the data.
*
* In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte
* sequence up to length 2953. This is the hard upper limit of the QR Code standard.
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*/
bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
/*---- Functions (low level) to generate QR Codes ----*/
/*
* Encodes the given segments to a QR Code, returning true if successful.
* If the data is too long to fit in any version at the given ECC level,
* then false is returned.
*
* The smallest possible QR Code version is automatically chosen for
* the output. The ECC level of the result may be higher than the
* ecl argument if it can be done without increasing the version.
*
* About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX):
* - Before calling the function:
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The initial state of both ranges can be uninitialized
* because the function always writes before reading.
* - The input array segs can contain segments whose data buffers overlap with tempBuffer.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
* - Any segment whose data buffer overlaps with tempBuffer[0 : len]
* must be treated as having invalid values in that array.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
*/
bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]);
/*
* Encodes the given segments to a QR Code, returning true if successful.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
*
* Requires 1 <= minVersion <= maxVersion <= 40.
*
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
*
* About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX):
* - Before calling the function:
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The initial state of both ranges can be uninitialized
* because the function always writes before reading.
* - The input array segs can contain segments whose data buffers overlap with tempBuffer.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
* - Any segment whose data buffer overlaps with tempBuffer[0 : len]
* must be treated as having invalid values in that array.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
*/
bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]);
/*
* Tests whether the given string can be encoded as a segment in numeric mode.
* A string is encodable iff each character is in the range 0 to 9.
*/
bool qrcodegen_isNumeric(const char *text);
/*
* Tests whether the given string can be encoded as a segment in alphanumeric mode.
* A string is encodable iff each character is in the following set: 0 to 9, A to Z
* (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
bool qrcodegen_isAlphanumeric(const char *text);
/*
* Returns the number of bytes (uint8_t) needed for the data buffer of a segment
* containing the given number of characters using the given mode. Notes:
* - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or the internal
* calculation of the number of needed bits exceeds INT16_MAX (i.e. 32767).
* - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096.
* - It is okay for the user to allocate more bytes for the buffer than needed.
* - For byte mode, numChars measures the number of bytes, not Unicode code points.
* - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned.
* An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
*/
size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars);
/*
* Returns a segment representing the given binary data encoded in
* byte mode. All input byte arrays are acceptable. Any text string
* can be converted to UTF-8 bytes and encoded as a byte mode segment.
*/
struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]);
/*
* Returns a segment representing the given string of decimal digits encoded in numeric mode.
*/
struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]);
/*
* Returns a segment representing the given text string encoded in alphanumeric mode.
* The characters allowed are: 0 to 9, A to Z (uppercase only), space,
* dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]);
/*
* Returns a segment representing an Extended Channel Interpretation
* (ECI) designator with the given assignment value.
*/
struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]);
/*---- Functions to extract raw data from QR Codes ----*/
/*
* Returns the side length of the given QR Code, assuming that encoding succeeded.
* The result is in the range [21, 177]. Note that the length of the array buffer
* is related to the side length - every 'uint8_t qrcode[]' must have length at least
* qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1).
*/
int qrcodegen_getSize(const uint8_t qrcode[]);
/*
* Returns the color of the module (pixel) at the given coordinates, which is false
* for light or true for dark. The top left corner has the coordinates (x=0, y=0).
* If the given coordinates are out of bounds, then false (light) is returned.
*/
bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y);
#ifdef __cplusplus
}
#endif
+212
View File
@@ -0,0 +1,212 @@
/* Lokale Oberfläche ohne externe Schriften oder Ressourcen. */
:root {
color-scheme: light dark;
--page: #f2f5f5; --surface: #fff; --ink: #173039; --muted: #52666d;
--line: #d9e2e3; --accent: #126b69; --accent-soft: #e7f3ef;
--warn: #815211; --warn-bg: #fff5df; --bad: #a13034; --bad-bg: #fff0ef;
--header: #102f37; --focus: #007baf; --shade: #f7f9f9;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 16px; line-height: 1.5;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--page); color: var(--ink); }
button, input { font: inherit; color: inherit; }
button, input[type="search"], .file-picker { border: 1px solid var(--line); border-radius: 7px; background: var(--surface); }
button, .file-picker { cursor: pointer; min-height: 44px; padding: 9px 12px; font-size: .875rem; font-weight: 600; overflow-wrap: anywhere; }
button:hover:not(:disabled), .file-picker:hover { border-color: var(--accent); background: var(--accent-soft); }
button[aria-pressed="true"] { color: var(--warn); border-color: var(--warn); background: var(--warn-bg); }
button:disabled { cursor: not-allowed; opacity: .5; }
:focus-visible, .file-input:focus-visible + .file-picker { outline: 3px solid var(--focus); outline-offset: 3px; }
a { color: var(--accent); text-underline-offset: 3px; }
input[type="search"] { display: block; width: 100%; min-width: 0; min-height: 44px; padding: 9px 10px; }
input[type="checkbox"] { accent-color: var(--accent); width: 20px; height: 20px; margin: 0; flex: 0 0 auto; }
label { font-size: .875rem; font-weight: 600; }
h1, h2, h3, p, dl { margin: 0; }
h1 { font-size: clamp(1.5rem, 4vw, 2rem); letter-spacing: -.035em; line-height: 1.15; }
h2 { font-size: 1.08rem; letter-spacing: -.02em; }
h3 { font-size: .875rem; font-weight: 600; }
p, h2, h3, summary { overflow-wrap: anywhere; }
.shell { width: min(1200px, calc(100% - 40px)); margin: 0 auto; }
.masthead { background: var(--header); color: #f2faf9; padding: 16px 0; border-bottom: 3px solid #4caaa0; }
.heading-row, .section-heading, .table-meta, .footer { display: flex; justify-content: space-between; gap: 12px; align-items: center; }
.heading-row > *, .section-heading > *, .button-row > * { min-width: 0; max-width: 100%; }
.heading-with-help { display: flex; align-items: center; gap: 3px; min-width: 0; }
.heading-with-help > :first-child { min-width: 0; }
.eyebrow { color: #acd4ce; font-size: .68rem; letter-spacing: .1em; font-weight: 700; margin-bottom: 4px; }
.connection-box { display: flex; align-items: flex-end; flex-direction: column; gap: 4px; text-align: right; }
.connection-box .small { color: #bed1d5; }
main { padding-top: 12px; }
.small { font-size: .8rem; color: var(--muted); line-height: 1.5; }
.mono, .metric, .counters dd, .activity dd { font-variant-numeric: tabular-nums; }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; overflow-wrap: anywhere; }
.notice { padding: 10px 12px; border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: 6px; background: var(--surface); font-size: .85rem; margin-bottom: 12px; overflow-wrap: anywhere; }
.notice.warning { border-left-color: var(--warn); color: var(--warn); background: var(--warn-bg); }
.notice.danger { border-left-color: var(--bad); color: var(--bad); background: var(--bad-bg); }
.operation { padding: 0 2px 14px; }
#operation-state { font-weight: 600; font-size: .95rem; }
#operation-detail { margin-top: 2px; }
.section-heading { margin-bottom: 12px; flex-wrap: wrap; }
.health-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
.card { padding: 14px; background: var(--surface); border: 1px solid var(--line); border-radius: 9px; min-width: 0; }
.card h3 { color: var(--muted); }
.metric { font-size: 1.35rem; line-height: 1.25; font-weight: 650; letter-spacing: -.025em; margin: 4px 0 9px; }
.card .small + .small { margin-top: 3px; }
.good-text { color: var(--accent); }
.warning-text { color: var(--warn); }
.danger-text { color: var(--bad); }
progress { width: 100%; height: 7px; appearance: none; border: 0; border-radius: 6px; display: block; margin: 12px 0; background: var(--line); accent-color: var(--accent); overflow: hidden; }
progress::-webkit-progress-bar { background: var(--line); }
progress::-webkit-progress-value { background: var(--accent); border-radius: 6px; }
progress::-moz-progress-bar { background: var(--accent); border-radius: 6px; }
.activity { margin: 7px 0 12px; font-size: .85rem; }
.activity div { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 10px; margin-bottom: 6px; }
.activity dd { margin: 0; font-weight: 650; }
.activity dt { color: var(--muted); }
.counters-heading { margin: 14px 0 8px; }
.counters { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 10px; }
.counters > div { border-left: 2px solid var(--line); padding: 5px 10px; min-width: 0; overflow-wrap: anywhere; }
.counters dd { font-size: 1.35rem; font-weight: 650; margin: 0; }
.counters dt { font-size: .75rem; color: var(--muted); }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; margin-bottom: 16px; }
.panel-heading { padding: 10px 16px; border-bottom: 1px solid var(--line); }
.button-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.event-tools { padding: 10px 16px 0; }
.filters { display: flex; align-items: center; gap: 16px; padding: 10px 16px; }
.search-field { flex: 1; min-width: 0; }
.checkbox, .filter-errors { display: flex; align-items: center; gap: 8px; min-height: 44px; }
.checkbox { cursor: pointer; }
.filter-errors { gap: 0; flex: 0 0 auto; }
.panel > .notice { margin: 0 16px 10px; }
.table-meta { font-size: .75rem; color: var(--muted); padding: 0 16px 8px; flex-wrap: wrap; overflow-wrap: anywhere; }
.table-wrap { width: 100%; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; text-align: left; }
th { color: var(--muted); font-size: .75rem; background: var(--shade); font-weight: 650; overflow-wrap: anywhere; }
th, td { padding: 10px 16px; vertical-align: top; border-top: 1px solid var(--line); }
th { vertical-align: middle; }
th.time-col { width: 16%; }
th.radio-col { width: 18%; }
th:last-child { width: 27%; }
td { font-size: .85rem; overflow-wrap: anywhere; }
td .sub { display: block; font-size: .75rem; color: var(--muted); margin-top: 3px; }
td .mobile-radio { display: none; }
.sender-label { display: block; font-weight: 650; white-space: pre-wrap; overflow-wrap: anywhere; margin-bottom: 3px; }
.sender-id { font-size: .9rem; font-weight: 600; }
.badge { display: inline-block; max-width: 100%; border: 1px solid transparent; padding: 3px 7px; border-radius: 5px; font-size: .75rem; font-weight: 650; line-height: 1.4; overflow-wrap: anywhere; }
.badge.good { color: var(--accent); background: var(--accent-soft); }
.badge.warning { color: var(--warn); background: var(--warn-bg); }
.badge.danger { color: var(--bad); background: var(--bad-bg); }
.badge.neutral { color: var(--muted); background: var(--shade); border-color: var(--line); }
.row-flag { color: var(--warn) !important; }
.detail-toggle { display: block; min-height: 44px; max-width: 100%; padding: 6px 0; margin-top: 3px; background: transparent; border: 0; font-size: .75rem; color: var(--accent); text-decoration: underline; text-underline-offset: 3px; text-align: left; }
.detail-toggle:hover:not(:disabled) { background: transparent; }
.detail-row > td { padding: 14px 16px; background: var(--shade); border-top-style: dashed; }
.detail-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 13px 20px; }
.detail-grid > div { min-width: 0; }
.detail-grid dt { color: var(--muted); font-size: .75rem; margin-bottom: 3px; }
.detail-grid dd { margin: 0; white-space: pre-wrap; font-size: .8rem; overflow-wrap: anywhere; }
.detail-row .notice { margin: 12px 0 0; }
.detail-explanation { margin: 13px 0 0; }
.empty { text-align: center; padding: 28px 16px; font-size: .9rem; color: var(--muted); }
.panel-footer { border-top: 1px solid var(--line); background: var(--shade); padding: 10px 16px; border-radius: 0 0 10px 10px; }
.diagnostic-content, .label-content { padding: 12px 16px 16px; }
.label-content p { margin-top: 8px; }
.label-content .button-row { margin-top: 12px; }
#label-result { white-space: pre-wrap; }
.settings-content { padding: 12px 16px 16px; }
.settings-draft-note { margin-top: 6px; }
#settings-status { margin: 12px 0 6px; }
#settings-revision { overflow-wrap: anywhere; }
.settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 14px; }
.setting-field { min-width: 0; border: 1px solid var(--line); border-radius: 8px; padding: 12px; }
.setting-field .heading-with-help { justify-content: space-between; }
.setting-field h3 { font-size: 1rem; }
.setting-storage { margin-bottom: 8px; }
.setting-accepted { margin: 8px 0; font-size: .875rem; white-space: pre-wrap; overflow-wrap: anywhere; }
.setting-field label:not(.checkbox) { display: block; margin: 8px 0 4px; }
.setting-input { width: 100%; min-width: 0; min-height: 44px; padding: 9px 10px; border: 1px solid var(--line); border-radius: 7px; background: var(--surface); color: var(--ink); font: inherit; font-size: 16px; }
textarea.setting-input { resize: vertical; min-height: 100px; }
.setting-input[aria-invalid="true"] { border-color: var(--bad); }
.setting-field .button-row { margin-top: 10px; }
.setting-field .button-row > button { flex: 1 1 150px; }
.setting-draft, .setting-message { margin-top: 8px; overflow-wrap: anywhere; }
.setting-review { padding: 8px; margin-top: 8px; border: 1px solid var(--warn); border-radius: 6px; background: var(--warn-bg); color: var(--warn); }
.settings-expert { margin-top: 16px; border: 1px solid var(--line); border-radius: 8px; }
.settings-expert-content { padding: 12px; }
.settings-expert-content > .notice { margin-bottom: 0; }
.settings-wifi { margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--line); }
.settings-wifi > button { margin-top: 12px; }
.settings-wifi > .small { margin-top: 6px; }
.danger-action { border-color: var(--bad); color: var(--bad); }
summary { cursor: pointer; min-height: 48px; padding: 12px 16px; font-size: .9rem; font-weight: 600; }
details[open] > summary { border-bottom: 1px solid var(--line); }
.about { font-size: .8rem; color: var(--muted); margin-bottom: 12px; }
.about summary { color: var(--ink); padding-left: 2px; }
.about p { margin-bottom: 12px; max-width: 95ch; }
.about > div { padding: 10px 2px; }
.footer { border-top: 1px solid var(--line); padding: 14px 0 20px; color: var(--muted); font-size: .75rem; flex-wrap: wrap; }
.help-button { display: inline-flex; justify-content: center; align-items: center; flex: 0 0 44px; width: 44px; min-width: 44px; min-height: 44px; padding: 0; border-color: transparent; background: transparent; color: var(--accent); font-size: .9rem; }
.help-button::first-letter { font-weight: 700; }
.help-button[aria-expanded="true"] { border-color: var(--accent); background: var(--accent-soft); }
.help-popover { position: fixed; z-index: 20; right: max(12px, env(safe-area-inset-right)); bottom: max(12px, env(safe-area-inset-bottom)); width: min(26rem, calc(100% - 24px)); max-height: 60vh; max-height: 60dvh; overflow-y: auto; border: 2px solid var(--accent); border-radius: 10px; background: var(--surface); color: var(--ink); padding: 12px 16px 16px; box-shadow: 0 8px 35px #0005; }
.help-heading { display: flex; gap: 8px; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; position: sticky; top: -12px; background: var(--surface); padding-bottom: 4px; }
.help-heading h2 { font-size: 1rem; padding-top: 9px; }
.help-heading button { flex: 0 0 auto; color: var(--accent); }
#help-text { font-size: .9rem; line-height: 1.6; white-space: pre-line; }
.skip-link { position: absolute; top: -100px; left: 12px; min-height: 44px; padding: 10px; z-index: 30; background: var(--surface); }
.skip-link:focus { top: 10px; }
.about a { display: inline-flex; align-items: center; min-height: 44px; max-width: 100%; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
[hidden] { display: none !important; }
@media (max-width: 900px) {
.health-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.counters { grid-template-columns: repeat(3, minmax(0, 1fr)); }
th, td { padding: 10px; }
.detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 560px) {
.shell { width: calc(100% - 20px); }
.masthead { padding: 12px 0; }
.heading-row { gap: 8px; }
.connection-box { max-width: 54%; }
.connection-box .small { font-size: .7rem; }
.card { padding: 10px; }
.health-grid { gap: 8px; }
.metric { font-size: 1.15rem; }
.activity { font-size: .8rem; }
.counters > div { padding: 3px 7px; }
.counters dd { font-size: 1.2rem; }
.panel-heading, .diagnostic-content, .label-content, .settings-content { padding-right: 10px; padding-left: 10px; }
.event-tools { padding: 8px 10px 0; }
.event-tools .button-row { gap: 2px; }
.event-tools button:not(.help-button) { font-size: .75rem; padding: 8px 7px; }
.filters { align-items: stretch; flex-direction: column; gap: 0; padding: 8px 10px; }
.panel > .notice { margin-right: 10px; margin-left: 10px; }
.table-meta { padding: 0 10px 8px; gap: 3px; }
#display-boot { display: none; }
.radio-col { display: none; }
td .mobile-radio { display: block; }
th, td { padding: 8px 6px; }
th.time-col { width: 19%; }
th:last-child { width: 32%; }
.sender-id { font-size: .78rem; }
td { font-size: .8rem; }
.badge { padding: 3px 5px; font-size: .7rem; }
.detail-row > td { padding: 12px 10px; }
.detail-grid { grid-template-columns: minmax(0, 1fr); gap: 10px; }
.detail-grid dt { display: flex; align-items: center; }
.panel-footer { padding: 10px; }
.settings-grid { grid-template-columns: minmax(0, 1fr); }
.setting-field, .settings-expert-content { padding: 10px; }
.settings-expert summary { padding: 12px 10px; }
.help-popover { right: 10px; width: calc(100% - 20px); padding: 10px 12px 14px; }
.footer { gap: 4px; }
}
@media (max-width: 350px) {
.health-grid { grid-template-columns: minmax(0, 1fr); }
.event-tools .button-row { display: grid; grid-template-columns: minmax(0, 1fr) 44px; gap: 4px; }
.event-tools button:not(.help-button) { text-align: left; }
th .heading-with-help { flex-wrap: wrap; gap: 0; }
}
@media (prefers-color-scheme: dark) {
:root { --page: #101b20; --surface: #17262c; --ink: #dce8e9; --muted: #a6b9be; --line: #32444b; --accent: #89d2c5; --accent-soft: #193d39; --warn: #efc27b; --warn-bg: #3b3020; --bad: #ffabab; --bad-bg: #44282d; --shade: #1a2b31; --focus: #8cd4ff; }
}
File diff suppressed because it is too large Load Diff
+89
View File
@@ -0,0 +1,89 @@
/*
* Independent header-only identification; no third-party decoder code.
* Factual medium/type codes and documented TCH exceptions cross-referenced
* against wmbusmeters src/wmbus.cc, mediaType(), retrieved 2026-09-09:
* https://github.com/wmbusmeters/wmbusmeters/blob/master/src/wmbus.cc
* That reference project is GPL-3.0-or-later (Fredrik Öhrström and contributors);
* no implementation is copied here. No payload, driver or model decoding.
* FLAG/company registration facts are sourced separately in manufacturers.js.
*/
import { manufacturers } from './manufacturers.js';
export function hex(value, width = 2) {
return Number.isInteger(value) && value >= 0
? `0x${value.toString(16).toUpperCase().padStart(width, '0')}` : 'nicht verfügbar';
}
export function manufacturerInfo(value) {
if (!Number.isInteger(value) || value < 0 || value > 0xFFFF) {
return { code: '', name: 'Hersteller nicht verfügbar', raw: hex(value, 4), warning: 'Kein gültiges Herstellerfeld vorhanden' };
}
const letters = [(value >> 10) & 31, (value >> 5) & 31, value & 31];
const valid = letters.every(letter => letter >= 1 && letter <= 26);
const code = valid ? String.fromCharCode(...letters.map(letter => letter + 64)) : '';
return {
code,
name: code ? (manufacturers[code] || 'Nicht registrierter / unbekannter Hersteller') : 'Ungültiger Herstellercode',
raw: hex(value, 4),
warning: !valid ? 'Das Herstellerfeld enthält keine gültige Kennung aus drei Buchstaben (A–Z)'
: value & 0x8000 ? 'Das höchste Bit im Herstellerfeld ist gesetzt; die Suche im FLAG-Herstellerverzeichnis nutzt nur die unteren 15 Bits' : '',
};
}
const media = {
0x00: 'Sonstiges', 0x01: 'Ölzähler', 0x02: 'Stromzähler', 0x03: 'Gaszähler',
0x04: 'Wärmezähler', 0x05: 'Dampfzähler', 0x06: 'Warmwasserzähler (30–90 °C)',
0x07: 'Wasserzähler', 0x08: 'Heizkostenverteiler', 0x09: 'Druckluftzähler',
0x0A: 'Kältevolumen am Auslass', 0x0B: 'Kältevolumen am Einlass',
0x0C: 'Wärmevolumen am Einlass', 0x0D: 'Wärme- / Kältelastzähler',
0x0E: 'Bus- / Systemkomponente', 0x0F: 'Unbekanntes Messmedium',
0x15: 'Heißwasserzähler (≥90 °C)', 0x16: 'Kaltwasserzähler',
0x17: 'Heiß- / Kaltwasserzähler', 0x18: 'Druckmesser', 0x19: 'Analog-Digital-Wandler',
0x1A: 'Rauchmelder', 0x1B: 'Raumtemperatur- / Luftfeuchtesensor',
0x1C: 'Gasmelder', 0x20: 'Stromschalter', 0x21: 'Gas- / Wasserventil',
0x25: 'Kundenanzeige', 0x28: 'Abwasser', 0x29: 'Abfall',
0x2A: 'Für Kohlendioxid reserviert', 0x31: 'Für Kommunikationssteuerungen reserviert',
0x32: 'Für Einweg-Funkweiterleiter reserviert', 0x33: 'Für Zweiweg-Funkweiterleiter reserviert',
0x36: 'Funkkonverter (Systemseite)', 0x37: 'Funkkonverter (Zählerseite)',
};
const techemMedia = {
0x43: 'Wärmezähler', 0x62: 'Warmwasser', 0x72: 'Kaltwasser',
0x80: 'Heizkostenverteiler', 0xC3: 'Wärmezähler', 0xF0: 'Rauchmelder',
};
export function mediumInfo(value, manufacturer) {
const raw = hex(value);
if (!Number.isInteger(value) || value < 0 || value > 255) {
return { name: 'Gerätetyp nicht verfügbar', raw, scoped: false };
}
let name = media[value];
// Only this exact manufacturer has these documented non-standard meanings.
const scoped = manufacturer === 0x5068 && Object.hasOwn(techemMedia, value);
if (scoped) name = techemMedia[value];
if (!name) {
if (value >= 0x1D && value <= 0x1F) name = 'Für Sensoren reserviert';
else if (value >= 0x22 && value <= 0x24) name = 'Für Schaltgeräte reserviert';
else if (value >= 0x26 && value <= 0x27) name = 'Für Kundengeräte reserviert';
else if (value >= 0x2B && value <= 0x2F) name = 'Für Umweltmessgeräte reserviert';
else if (value >= 0x30 && value <= 0x3F) name = 'Für Systemgeräte reserviert';
else name = 'Unbekannter / reservierter Gerätetyp';
}
return { name, raw, scoped };
}
export function senderIdentity(row) {
const rawId = typeof row.meter_id === 'string' ? row.meter_id : '';
const id = /^[0-9A-Fa-f]{8}$/.test(rawId) ? rawId.toUpperCase() : '';
const trusted = row.source === 'rx' && row.crc_ok === true && row.reception === 'ok';
const manufacturer = manufacturerInfo(row.manufacturer);
const medium = mediumInfo(row.device_type, row.manufacturer);
const warnings = [];
if (!trusted) warnings.push('Keine empfangene Kennung mit gültiger CRC-Prüfsumme; eigene Namen und Geräteerkennung werden nicht verwendet');
if (rawId && !id) warnings.push('Ungültige ID: erwartet werden genau acht Hexadezimalstellen (0–9, A–F)');
if (id && !/^[0-9]{8}$/.test(id)) warnings.push('ID nicht im BCD-Ziffernformat: Die Hexadezimalkennung bleibt unverändert. Sie darf nicht als dezimale Zählernummer gelesen werden');
if (trusted && manufacturer.warning) warnings.push(manufacturer.warning);
return {
id, rawId, trusted, labelEligible: trusted && Boolean(id), manufacturer, medium, warnings,
key: `${id}/${row.manufacturer}/${row.version}/${row.device_type}`,
};
}
+115
View File
@@ -0,0 +1,115 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<meta name="theme-color" content="#102f37">
<title>Heltec · Zählerfunk</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/dashboard.css">
<script type="module" src="/dashboard.js"></script>
</head>
<body>
<a class="skip-link" href="#events">Zu den Funknachrichten</a>
<header class="masthead">
<div class="shell heading-row">
<div><p class="eyebrow">HELTEC / wM-Bus</p><h1>Zählerfunk</h1></div>
<div class="connection-box"><span id="connection" class="badge neutral" role="status">Verbindung wird aufgebaut</span><span id="connection-age" class="small">Warte auf das Gerät</span></div>
</div>
</header>
<main class="shell">
<noscript><p class="notice danger">Diese Seite benötigt JavaScript, aber kein Internet.</p></noscript>
<p id="connection-notice" class="notice" role="status">Verbindung zum Gerät wird aufgebaut.</p>
<section class="operation" aria-labelledby="operation-title">
<div class="heading-with-help"><h2 id="operation-title">Jetzt am Gerät</h2><button type="button" class="help-button" data-help="flow" aria-label="Hilfe: Empfangen und Weiterleiten" aria-controls="help-popover" aria-expanded="false">?</button></div>
<p id="operation-state">Warte auf den Gerätestatus.</p>
<p id="operation-detail" class="small">Noch keine Daten verfügbar.</p>
</section>
<section id="events" class="panel" aria-labelledby="events-title">
<div class="panel-heading"><div class="heading-with-help"><h2 id="events-title">Letzte Funknachrichten</h2><button type="button" class="help-button" data-help="history" aria-label="Hilfe: Verlauf und Neustart" aria-controls="help-popover" aria-expanded="false">?</button></div><p class="small">Neueste zuerst · je ein Signal mit abschließendem Ergebnis</p></div>
<div class="event-tools"><div class="button-row"><button id="pause" type="button" aria-pressed="false">Nur Anzeige pausieren</button><button type="button" class="help-button" data-help="pause" aria-label="Hilfe: Nur die Anzeige pausieren" aria-controls="help-popover" aria-expanded="false">?</button><button id="download-events" type="button" disabled>Verlauf als CSV</button><button type="button" class="help-button" data-help="export" aria-label="Hilfe: Verlauf herunterladen" aria-controls="help-popover" aria-expanded="false">?</button></div></div>
<div class="filters"><div class="search-field"><label class="sr-only" for="filter">Nach Kennung, eigenem Namen oder Hersteller filtern</label><input id="filter" type="search" placeholder="Kennung, Name oder Hersteller suchen" autocomplete="off" maxlength="200"></div><div class="filter-errors"><label class="checkbox" for="failures"><input id="failures" type="checkbox">Nur Fehler</label><button type="button" class="help-button" data-help="outcomes" aria-label="Hilfe: Fehler und ausgelassene Signale" aria-controls="help-popover" aria-expanded="false">?</button></div></div>
<p id="pause-notice" class="notice warning" hidden></p>
<p id="ambiguity-notice" class="notice warning" role="status" hidden></p>
<div class="table-meta"><span id="row-count">0 Funknachrichten</span><span id="display-boot" class="mono"></span></div>
<div class="table-wrap"><table id="event-table"><caption class="sr-only">Empfangene Funknachrichten und Sendeergebnisse, neueste zuerst. Unter Einzelheiten stehen die vollständige Absenderkennung, Rohwerte und Zeitangaben.</caption><thead><tr><th scope="col" class="time-col">Zeit</th><th scope="col"><span class="heading-with-help">Absender<button type="button" class="help-button" data-help="identity" aria-label="Hilfe: Absender und Zählerkennung" aria-controls="help-popover" aria-expanded="false">?</button></span></th><th scope="col" class="radio-col"><span class="heading-with-help">Funk<button type="button" class="help-button" data-help="signal" aria-label="Hilfe: Signalstärke und Funkformat" aria-controls="help-popover" aria-expanded="false">?</button></span></th><th scope="col">Ergebnis</th></tr></thead><tbody id="event-rows"></tbody></table></div>
<p id="empty-state" class="empty">Warte auf den ersten Verlauf …</p>
<div class="panel-footer"><p id="retention" class="small">Bis zu 256 abgeschlossene Funknachrichten seit dem Gerätestart.</p></div>
</section>
<details id="diagnostics" class="panel diagnostics">
<summary>Diagnose: Summen und Funkstatus</summary>
<div class="diagnostic-content">
<div class="section-heading"><div class="heading-with-help"><h2 id="health-title">Gerät im Detail</h2><button type="button" class="help-button" data-help="diagnostics" aria-label="Hilfe: Aktualität der Diagnose" aria-controls="help-popover" aria-expanded="false">?</button></div><span id="uptime" class="small">Laufzeit —</span></div>
<div class="health-grid">
<article class="card"><div class="heading-with-help"><h3>Funkzustand</h3><button type="button" class="help-button" data-help="diagnostics" aria-label="Hilfe: Funkzustand und Prüfintervall" aria-controls="help-popover" aria-expanded="false">?</button></div><p id="radio-state" class="metric">—</p><p id="radio-detail" class="small">Warte auf Messdaten</p><p id="heartbeat" class="small">Funkprüfung —</p></article>
<article class="card"><div class="heading-with-help"><h3>Weiterleiten</h3><button type="button" class="help-button" data-help="policy" aria-label="Hilfe: Regeln fürs Weiterleiten" aria-controls="help-popover" aria-expanded="false">?</button></div><p id="repeat-state" class="metric">—</p><p id="repeat-detail" class="small">Wartezeit —</p><p id="recovery-detail" class="small">Funk-Reparaturversuche —</p></article>
<article class="card"><div class="heading-with-help"><h3>Sendezeit</h3><button type="button" class="help-button" data-help="duty" aria-label="Hilfe: Zulässige Sendezeit" aria-controls="help-popover" aria-expanded="false">?</button></div><p id="duty-state" class="metric">—</p><progress id="duty-meter" max="100" value="0" aria-label="Anteil des verbrauchten Sendezeitbudgets"></progress><p id="duty-detail" class="small">Warte auf Messdaten</p></article>
<article class="card"><div class="heading-with-help"><h3>Letzte Aktivität</h3><button type="button" class="help-button" data-help="activity" aria-label="Hilfe: Empfang und abgeschlossenes Senden" aria-controls="help-popover" aria-expanded="false">?</button></div><dl class="activity"><div><dt>Lesbar empfangen</dt><dd id="last-rx">—</dd></div><div><dt>Senden beendet</dt><dd id="last-tx">—</dd></div></dl></article>
</div>
<div class="heading-with-help counters-heading"><h3>Summen seit Gerätestart</h3><button type="button" class="help-button" data-help="counters" aria-label="Hilfe: Empfangs- und Sendezähler" aria-controls="help-popover" aria-expanded="false">?</button></div>
<dl class="counters">
<div><dd id="count-rx">—</dd><dt>Lesbar empfangen</dt></div><div><dd id="count-rejected">—</dd><dt>Nicht lesbar</dt></div><div><dd id="count-repeats">—</dd><dt>Weitergesendet</dt></div><div><dd id="count-skipped">—</dd><dt>Ausgelassen</dt></div><div><dd id="count-failed">—</dd><dt>Sendefehler</dt></div><div><dd id="count-recoveries">—</dd><dt>Funk-Reparaturversuche</dt></div>
</dl>
</div>
</details>
<details id="settings-panel" class="panel">
<summary>Einstellungen am Heltec-Gerät ändern</summary>
<div class="settings-content">
<div class="section-heading">
<div class="heading-with-help"><h2>Geräteeinstellungen</h2><button type="button" class="help-button" data-help="settings" aria-label="Hilfe: Einstellungen, Entwürfe und Speicherung" aria-controls="help-popover" aria-expanded="false">?</button></div>
<button id="settings-reload" type="button">Gerätewerte neu laden</button>
</div>
<p class="small">Jedes Feld wird einzeln und erst mit „Übernehmen“ an das Heltec-Gerät gesendet. Gerätewert und lokaler Entwurf sind getrennt. Nur Wartezeit und Sendezeitbudget bleiben nach einem Geräteneustart erhalten; alle anderen Werte gelten nur im Arbeitsspeicher (RAM).</p>
<p class="small settings-draft-note">Ungesendete Entwürfe bleiben beim Nachladen erhalten, aber nicht beim Neuladen oder Schließen dieses Browser-Tabs.</p>
<p id="settings-status" class="notice" role="status">Noch keine Einstellungen geladen. Zum Laden diesen Bereich öffnen.</p>
<p id="settings-revision" class="small"></p>
<div id="settings-common" class="settings-grid"></div>
<details id="settings-expert" class="settings-expert">
<summary>Experteneinstellungen: Funkexperimente und eigene Signale</summary>
<div class="settings-expert-content">
<p class="notice warning">FEM-CSD und Präambelerkennung sind Empfangsexperimente und können den Empfang verschlechtern. Kennungssignale erzeugen zusätzlichen Funkverkehr. Im Zweifel die vorhandenen Werte beibehalten.</p>
<div id="settings-advanced" class="settings-grid"></div>
</div>
</details>
<section class="settings-wifi" aria-labelledby="settings-wifi-title">
<div class="heading-with-help"><h3 id="settings-wifi-title">WLAN des Heltec-Geräts</h3><button type="button" class="help-button" data-help="settings_wifi" aria-label="Hilfe: Heltec-WLAN ausschalten" aria-controls="help-popover" aria-expanded="false">?</button></div>
<p class="small">Ausschalten trennt diese Verbindung. Die Funkweiterleitung läuft gemäß ihren Einstellungen weiter. Das WLAN kann danach nicht über diese Seite wieder eingeschaltet werden.</p>
<button id="settings-wifi-disable" type="button" class="danger-action" disabled>Heltec-WLAN ausschalten …</button>
<p id="settings-wifi-result" class="small" role="status"></p>
</section>
</div>
</details>
<details id="labels" class="panel">
<summary>Optional: eigene Namen für Zähler</summary>
<div class="label-content">
<div class="section-heading"><div class="heading-with-help"><h2 id="labels-title">Eigene Zählernamen</h2><button type="button" class="help-button" data-help="labels" aria-label="Hilfe: Eigene Namen und Absenderkennung" aria-controls="help-popover" aria-expanded="false">?</button></div><span id="label-count" class="badge neutral">0 Namen</span></div>
<p id="label-help" class="small">Nur für diesen Browser-Tab. Die Datei bleibt auf deinem Gerät.</p>
<div class="button-row"><input id="label-file" class="file-input sr-only" type="file" accept=".csv,text/csv" aria-label="CSV-Datei mit eigenen Zählernamen auswählen" aria-describedby="label-help label-result"><label class="file-picker" for="label-file">CSV-Datei auswählen</label><button type="button" class="help-button" data-help="csv" aria-label="Hilfe: CSV-Datei und führende Nullen" aria-controls="help-popover" aria-expanded="false">?</button><button id="sample-labels" type="button">Vorlage herunterladen</button><button id="export-labels" type="button" disabled>Kennungen und Namen als CSV</button><button id="clear-labels" type="button" disabled>Namen entfernen</button></div>
<p id="label-result" class="small" role="status">Keine Namen geladen. Neuladen oder Schließen der Seite entfernt alle eigenen Namen.</p>
</div>
</details>
<details class="about">
<summary>Datenschutz, Zuordnung und Quellen</summary>
<div>
<div class="heading-with-help"><h2>Wie wird ein Absender erkannt?</h2><button type="button" class="help-button" data-help="identity" aria-label="Hilfe: Grenzen der Absenderzuordnung" aria-controls="help-popover" aria-expanded="false">?</button></div>
<p>Hersteller und Gerätetyp werden im Browser zugeordnet. Nutzdaten werden weder entschlüsselt noch als Zählerstände ausgewertet. Die Versionsnummer dient nicht zur Erkennung eines Modells oder Treibers.</p>
<p>Alle Skripte, Stile und Herstellerdaten liegen auf dem Heltec-Gerät. Bestätigte Einstellungsänderungen werden an dieses Gerät gesendet; das Ausschalten seines WLANs trennt die Verbindung. CSV-Dateien und eigene Zählernamen werden dagegen nur im Browser verarbeitet: ohne Hochladen, Cookies oder dauerhafte Browser-Speicherung. Dateien werden nur auf deinen Wunsch heruntergeladen.</p>
<p id="registry-note">Herstellernamen: mitgelieferter Stand des offiziellen FLAG-ID-Verzeichnisses der DLMS User Association.</p>
<p>Quellen (nur das Öffnen dieser Links benötigt Internet): <a href="https://www.dlms.com/flag-id-directory/" target="_blank" rel="noreferrer noopener">Offizielles DLMS-Verzeichnis</a> · <a href="https://github.com/wmbusmeters/wmbusmeters/blob/master/src/wmbus.cc" target="_blank" rel="noreferrer noopener">Gerätetyp-Codes bei wmbusmeters</a>.</p>
<p>Die Zuordnungslogik ist eigenständig implementiert. Bedeutungen der Gerätetyp-Codes und dokumentierte Herstellerausnahmen wurden mit wmbusmeters abgeglichen (GPL-3.0-or-later, Fredrik Öhrström und Mitwirkende); dessen Dekodierung ist nicht enthalten. Die Verzeichnisdaten stammen von der DLMS User Association. JavaScript, HTML und CSS werden als nicht minimierter Quelltext ausgeliefert.</p>
</div>
</details>
<footer class="footer"><span>Heltec-Funkweiterleitung</span><span>Lokal am Gerät · ohne Cloud</span></footer>
</main>
<aside id="help-popover" class="help-popover" role="dialog" aria-modal="false" aria-labelledby="help-title" aria-describedby="help-text" hidden>
<div class="help-heading"><h2 id="help-title"></h2><button id="help-close" type="button" aria-label="Hilfe schließen">Schließen</button></div>
<p id="help-text"></p>
</aside>
</body>
</html>
File diff suppressed because it is too large Load Diff
+346
View File
@@ -0,0 +1,346 @@
// On-demand debug AP. Only this task owns Wi-Fi/HTTP lifecycle; the OLED
// and settings endpoint request transitions without stopping their own server.
#include "wifi_debug.h"
#include "debug_history.h"
#include "settings_http.h"
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_event.h"
#include "esp_http_server.h"
#include "esp_mac.h"
#include "esp_netif.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include "esp_wifi_default.h"
#include "bootloader_random.h"
#include "nvs.h"
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static wifi_debug_status_t s_status;
static TaskHandle_t s_task;
static esp_netif_t *s_ap;
static httpd_handle_t s_http;
static bool s_wifi_initialized;
static bool s_network_initialized;
static debug_snapshot_t *s_snapshot;
static uint32_t s_boot_id;
#define REQUEST_TOGGLE 1u
#define REQUEST_DISABLE 2u
void wifi_debug_status(wifi_debug_status_t *out)
{
portENTER_CRITICAL(&s_lock);
*out = s_status;
portEXIT_CRITICAL(&s_lock);
}
static void publish(wifi_debug_state_t state, esp_err_t error)
{
portENTER_CRITICAL(&s_lock);
s_status.state = state;
s_status.error = error;
portEXIT_CRITICAL(&s_lock);
// Credentials are displayed physically, never included in serial telemetry.
printf("{\"event\":\"wifi_debug\",\"state\":%d,\"error\":%d}\n", state, error);
fflush(stdout);
}
static esp_err_t credentials(void)
{
uint8_t mac[6];
esp_err_t err = esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
if (err != ESP_OK) return err;
wifi_debug_status_t status;
wifi_debug_status(&status);
snprintf(status.ssid, sizeof(status.ssid), "Heltec-Repeater-%02X%02X", mac[4], mac[5]);
nvs_handle_t nvs;
err = nvs_open("wifi_debug", NVS_READWRITE, &nvs);
if (err != ESP_OK) return err;
size_t len = sizeof(status.password);
err = nvs_get_str(nvs, "password", status.password, &len);
if (err == ESP_ERR_NVS_NOT_FOUND) {
// No Wi-Fi/ADC is running here. Enable the hardware entropy source,
// rather than derive a publicly guessable password from the MAC.
uint8_t random[12];
static const char alphabet[] = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
_Static_assert(sizeof(alphabet) == 33, "password alphabet must have 32 symbols");
bootloader_random_enable();
esp_fill_random(random, sizeof(random));
bootloader_random_disable();
for (size_t i = 0; i < sizeof(random); i++) status.password[i] = alphabet[random[i] & 31];
status.password[12] = 0;
err = nvs_set_str(nvs, "password", status.password);
if (err == ESP_OK) err = nvs_commit(nvs);
} else if (err == ESP_OK && (len != sizeof(status.password) || strlen(status.password) != 12)) {
err = ESP_ERR_INVALID_SIZE;
}
nvs_close(nvs);
if (err != ESP_OK) return err;
portENTER_CRITICAL(&s_lock);
memcpy(s_status.ssid, status.ssid, sizeof(status.ssid));
memcpy(s_status.password, status.password, sizeof(status.password));
portEXIT_CRITICAL(&s_lock);
return ESP_OK;
}
#define ASSET(name, symbol) \
extern const uint8_t symbol##_start[] asm("_binary_" name "_start"); \
extern const uint8_t symbol##_end[] asm("_binary_" name "_end")
ASSET("index_html_gz", index_html);
ASSET("dashboard_css_gz", dashboard_css);
ASSET("dashboard_js_gz", dashboard_js);
ASSET("identity_js_gz", identity_js);
ASSET("manufacturers_js_gz", manufacturers_js);
typedef struct {
const uint8_t *start;
const uint8_t *end;
const char *type;
} asset_t;
static const asset_t s_assets[] = {
{index_html_start, index_html_end, "text/html; charset=utf-8"},
{dashboard_css_start, dashboard_css_end, "text/css; charset=utf-8"},
{dashboard_js_start, dashboard_js_end, "text/javascript; charset=utf-8"},
{identity_js_start, identity_js_end, "text/javascript; charset=utf-8"},
{manufacturers_js_start, manufacturers_js_end, "text/javascript; charset=utf-8"},
};
static void headers(httpd_req_t *req)
{
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
httpd_resp_set_hdr(req, "X-Content-Type-Options", "nosniff");
httpd_resp_set_hdr(req, "Content-Security-Policy",
"default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; "
"object-src 'none'; base-uri 'none'; frame-ancestors 'none'");
httpd_resp_set_hdr(req, "Referrer-Policy", "no-referrer");
}
static esp_err_t asset_handler(httpd_req_t *req)
{
const asset_t *asset = req->user_ctx;
headers(req);
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
httpd_resp_set_type(req, asset->type);
return httpd_resp_send(req, (const char *)asset->start, asset->end - asset->start);
}
static esp_err_t events_handler(httpd_req_t *req)
{
uint32_t after = 0;
size_t query_len = httpd_req_get_url_query_len(req);
if (query_len) {
char query[64], value[16];
if (query_len >= sizeof(query) ||
httpd_req_get_url_query_str(req, query, sizeof(query)) != ESP_OK ||
httpd_query_key_value(query, "after", value, sizeof(value)) != ESP_OK || !value[0]) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Expected after=unsigned integer");
}
uint64_t parsed = 0;
for (const char *p = value; *p; p++) {
if (*p < '0' || *p > '9') return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid cursor");
parsed = parsed * 10 + (unsigned)(*p - '0');
if (parsed > UINT32_MAX) return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid cursor");
}
after = (uint32_t)parsed;
}
debug_history_snapshot(after, s_snapshot);
const debug_status_t *s = &s_snapshot->status;
headers(req);
httpd_resp_set_type(req, "application/json");
char chunk[1400];
int n = snprintf(chunk, sizeof(chunk),
"{\"boot_id\":\"%08" PRIx32 "\",\"cursor\":%" PRIu32 ",\"oldest_id\":%" PRIu32
",\"evicted\":%" PRIu32 ",\"reset\":%s,\"now_us\":%lld,\"capacity\":%u,\"status\":{"
"\"sampled_at_us\":%lld,\"heartbeat_us\":%lld,\"last_rx_us\":%lld,\"last_tx_us\":%lld,"
"\"rx_valid\":%llu,\"rx_rejected\":%llu,\"repeats_completed\":%llu,\"tx_failed\":%llu,"
"\"skipped\":%llu,\"duty_used_us\":%llu,\"duty_budget_us\":%llu,\"recoveries\":%" PRIu32
",\"repeat_delay_ms\":%" PRIu32 ",\"chip_mode\":%u,\"config_intact\":%s,\"repeat_enabled\":%s},\"rows\":[",
s_boot_id, s_snapshot->cursor, s_snapshot->oldest_id, s_snapshot->evicted,
s_snapshot->reset ? "true" : "false", (long long)esp_timer_get_time(), DEBUG_HISTORY_CAPACITY,
(long long)s->sampled_at_us, (long long)s->heartbeat_us,
(long long)s->last_rx_us, (long long)s->last_tx_us,
(unsigned long long)s->rx_valid, (unsigned long long)s->rx_rejected,
(unsigned long long)s->repeats_completed, (unsigned long long)s->tx_failed,
(unsigned long long)s->skipped, (unsigned long long)s->duty_used_us,
(unsigned long long)s->duty_budget_us, s->recoveries, s->repeat_delay_ms,
s->chip_mode, s->config_intact ? "true" : "false", s->repeat_enabled ? "true" : "false");
if (n < 0 || n >= sizeof(chunk)) return ESP_FAIL;
esp_err_t err = httpd_resp_send_chunk(req, chunk, n);
for (size_t i = 0; err == ESP_OK && i < s_snapshot->count; i++) {
const debug_record_t *r = &s_snapshot->rows[i];
char meter[12] = "null", manufacturer[8] = "null", version[8] = "null", type[8] = "null";
if (r->identity_present) {
snprintf(meter, sizeof(meter), "\"%08" PRIX32 "\"", r->meter_id);
snprintf(manufacturer, sizeof(manufacturer), "%u", r->manufacturer);
snprintf(version, sizeof(version), "%u", r->version);
snprintf(type, sizeof(type), "%u", r->device_type);
}
n = snprintf(chunk, sizeof(chunk),
"%s{\"id\":%" PRIu32 ",\"timestamp_us\":%lld,\"tx_start_us\":%lld,\"tx_done_us\":%lld,"
"\"meter_id\":%s,\"hash\":\"%08" PRIx32 "\",\"manufacturer\":%s,\"length\":%u,"
"\"version\":%s,\"device_type\":%s,\"rssi_dbm\":%d,\"crc_ok\":%s,"
"\"source\":\"%s\",\"mode\":\"%s\",\"format\":\"%s\",\"reception\":\"%s\",\"outcome\":\"%s\"}",
i ? "," : "", r->id, (long long)r->timestamp_us,
(long long)r->tx_start_us, (long long)r->tx_done_us,
meter, r->hash, manufacturer, r->length, version, type, r->rssi_dbm,
r->crc_ok ? "true" : "false", r->source, r->mode, r->format, r->reception, r->outcome);
if (n < 0 || n >= sizeof(chunk)) return ESP_FAIL;
err = httpd_resp_send_chunk(req, chunk, n);
}
if (err == ESP_OK) err = httpd_resp_send_chunk(req, "]}", 2);
if (err == ESP_OK) err = httpd_resp_send_chunk(req, NULL, 0);
return err;
}
static esp_err_t start_http(void)
{
s_snapshot = calloc(1, sizeof(*s_snapshot));
if (!s_snapshot) return ESP_ERR_NO_MEM;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.core_id = 0;
config.task_priority = 2;
config.stack_size = 6144;
config.max_open_sockets = 3;
config.max_uri_handlers = 10;
config.lru_purge_enable = true;
config.recv_wait_timeout = 2;
config.send_wait_timeout = 2;
esp_err_t err = httpd_start(&s_http, &config);
if (err != ESP_OK) return err;
static const char *paths[] = {"/", "/dashboard.css", "/dashboard.js", "/identity.js", "/manufacturers.js"};
for (size_t i = 0; i < sizeof(s_assets) / sizeof(s_assets[0]); i++) {
const httpd_uri_t uri = {.uri = paths[i], .method = HTTP_GET, .handler = asset_handler, .user_ctx = (void *)&s_assets[i]};
err = httpd_register_uri_handler(s_http, &uri);
if (err != ESP_OK) return err;
}
const httpd_uri_t index = {.uri = "/index.html", .method = HTTP_GET, .handler = asset_handler, .user_ctx = (void *)&s_assets[0]};
err = httpd_register_uri_handler(s_http, &index);
if (err != ESP_OK) return err;
const httpd_uri_t events = {.uri = "/api/events", .method = HTTP_GET, .handler = events_handler};
err = httpd_register_uri_handler(s_http, &events);
if (err != ESP_OK) return err;
return settings_http_register(s_http, s_boot_id);
}
static esp_err_t stop_network(void)
{
if (s_http) {
esp_err_t err = httpd_stop(s_http);
if (err != ESP_OK) return err;
s_http = NULL;
}
free(s_snapshot);
s_snapshot = NULL;
if (s_wifi_initialized) {
esp_err_t err = esp_wifi_stop();
if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_STARTED) return err;
err = esp_wifi_deinit();
if (err != ESP_OK) return err;
s_wifi_initialized = false;
}
if (s_ap) {
esp_netif_destroy_default_wifi(s_ap);
s_ap = NULL;
}
return ESP_OK;
}
static esp_err_t start_network(void)
{
esp_err_t err = credentials();
if (err != ESP_OK) return err;
if (!s_network_initialized) {
err = esp_netif_init();
if (err != ESP_OK) return err;
err = esp_event_loop_create_default();
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) return err;
s_network_initialized = true;
}
// The convenience create_default helper aborts on allocation/attach
// failure. Debug networking must fail without resetting the repeater.
esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_WIFI_AP();
s_ap = esp_netif_new(&netif_config);
if (!s_ap) return ESP_ERR_NO_MEM;
err = esp_netif_attach_wifi_ap(s_ap);
if (err != ESP_OK) return err;
err = esp_wifi_set_default_wifi_ap_handlers();
if (err != ESP_OK) return err;
wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT();
err = esp_wifi_init(&init);
if (err != ESP_OK) return err;
s_wifi_initialized = true;
err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
if (err != ESP_OK) return err;
wifi_debug_status_t status;
wifi_debug_status(&status);
wifi_config_t config = {0};
memcpy(config.ap.ssid, status.ssid, strlen(status.ssid));
config.ap.ssid_len = strlen(status.ssid);
memcpy(config.ap.password, status.password, strlen(status.password));
config.ap.channel = 1;
config.ap.max_connection = 2;
config.ap.authmode = WIFI_AUTH_WPA2_PSK;
config.ap.pmf_cfg.capable = true;
err = esp_wifi_set_mode(WIFI_MODE_AP);
if (err == ESP_OK) err = esp_wifi_set_config(WIFI_IF_AP, &config);
if (err == ESP_OK) err = esp_wifi_start();
if (err == ESP_OK) err = start_http();
return err;
}
static void control_task(void *arg)
{
(void)arg;
for (;;) {
uint32_t requests;
xTaskNotifyWait(0, UINT32_MAX, &requests, portMAX_DELAY);
wifi_debug_status_t status;
wifi_debug_status(&status);
if ((requests & REQUEST_DISABLE) && status.state == WIFI_DEBUG_OFF) continue;
if ((requests & REQUEST_DISABLE) || status.state == WIFI_DEBUG_ON) {
publish(WIFI_DEBUG_STOPPING, ESP_OK);
esp_err_t err = stop_network();
publish(err == ESP_OK ? WIFI_DEBUG_OFF : WIFI_DEBUG_ERROR, err);
} else {
publish(WIFI_DEBUG_STARTING, ESP_OK);
esp_err_t err = stop_network(); // also cleans a previous partial failure
if (err == ESP_OK) err = start_network();
if (err != ESP_OK) {
esp_err_t cleanup = stop_network();
if (cleanup != ESP_OK) err = cleanup;
}
publish(err == ESP_OK ? WIFI_DEBUG_ON : WIFI_DEBUG_ERROR, err);
}
}
}
void wifi_debug_toggle(void)
{
wifi_debug_status_t status;
wifi_debug_status(&status);
if (s_task && status.state != WIFI_DEBUG_STARTING && status.state != WIFI_DEBUG_STOPPING) {
xTaskNotify(s_task, REQUEST_TOGGLE, eSetBits);
}
}
void wifi_debug_disable(void)
{
if (s_task) xTaskNotify(s_task, REQUEST_DISABLE, eSetBits);
}
void wifi_debug_init(void)
{
s_boot_id = esp_random(); // Session discriminator, not a secret.
if (xTaskCreatePinnedToCore(control_task, "wifi_debug", 6144, NULL, 2, &s_task, 0) != pdPASS) {
publish(WIFI_DEBUG_ERROR, ESP_ERR_NO_MEM);
}
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <stdint.h>
typedef enum {
WIFI_DEBUG_OFF,
WIFI_DEBUG_STARTING,
WIFI_DEBUG_ON,
WIFI_DEBUG_STOPPING,
WIFI_DEBUG_ERROR,
} wifi_debug_state_t;
typedef struct {
wifi_debug_state_t state;
char ssid[22];
char password[13];
int32_t error;
} wifi_debug_status_t;
// Starts only the control task. Wi-Fi remains off until an OLED request.
void wifi_debug_init(void);
void wifi_debug_toggle(void);
void wifi_debug_disable(void); // idempotent, queued outside the HTTP task
void wifi_debug_status(wifi_debug_status_t *out);
+60
View File
@@ -0,0 +1,60 @@
#include "wifi_qr.h"
#include "vendor/qrcodegen.h"
#include <stddef.h>
#include <string.h>
// Nayuki QR Code generator v1.8.0, vendored unchanged under its MIT license.
// https://github.com/nayuki/QR-Code-generator/tree/v1.8.0/c
#define MAX_VERSION 5
static bool append_field(char **dst, const char *end, const char *text)
{
for (; *text; text++) {
// ZXing/iOS Wi-Fi join syntax escapes special field characters.
if (strchr("\\;,:\"", *text)) {
if (*dst == end) return false;
*(*dst)++ = '\\';
}
if (*dst == end) return false;
*(*dst)++ = *text;
}
return true;
}
bool wifi_qr_bitmap(const char *ssid, const char *password, uint8_t out[WIFI_QR_BYTES])
{
char payload[96] = "WIFI:T:WPA;S:";
char *dst = payload + strlen(payload);
const char *end = payload + sizeof(payload) - 1;
if (!append_field(&dst, end, ssid) || end - dst < 3) return false;
memcpy(dst, ";P:", 3);
dst += 3;
if (!append_field(&dst, end, password) || end - dst < 2) return false;
*dst++ = ';';
*dst++ = ';';
*dst = 0;
uint8_t work[qrcodegen_BUFFER_LEN_FOR_VERSION(MAX_VERSION)];
uint8_t qr[qrcodegen_BUFFER_LEN_FOR_VERSION(MAX_VERSION)];
if (!qrcodegen_encodeText(payload, work, qr, qrcodegen_Ecc_LOW,
1, MAX_VERSION, qrcodegen_Mask_AUTO, true)) return false;
const int size = qrcodegen_getSize(qr);
const int scale = WIFI_QR_SIDE / (size + 8);
if (scale < 1) return false;
const int origin = (WIFI_QR_SIDE - size * scale) / 2;
// OLED lit pixels are the light modules. Do not invert the QR or truncate
// its quiet zone just to fit a 2x scale on this 64-pixel-high panel.
memset(out, 0xff, WIFI_QR_BYTES);
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
if (!qrcodegen_getModule(qr, x, y)) continue;
for (int dy = 0; dy < scale; dy++) {
int py = origin + y * scale + dy;
for (int dx = 0; dx < scale; dx++) {
int px = origin + x * scale + dx;
out[(py / 8) * WIFI_QR_SIDE + px] &= (uint8_t)~(1u << (py % 8));
}
}
}
}
return true;
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#define WIFI_QR_SIDE 64
#define WIFI_QR_BYTES (WIFI_QR_SIDE * WIFI_QR_SIDE / 8)
// Standard WIFI: WPA join payload, rendered as SSD1306 page-order pixels.
// Bright background, dark modules, integer scaling and >=4-module quiet zone.
// Called only when credentials change, never from the radio task.
bool wifi_qr_bitmap(const char *ssid, const char *password, uint8_t out[WIFI_QR_BYTES]);
+164
View File
@@ -103,6 +103,81 @@ bool wmbus_check_crc(wmbus_frame_fmt_t fmt, const uint8_t *frame, int total_len)
return false; return false;
} }
// Map a CRC-free logical byte offset to its position in the raw frame.
// Header fields can straddle a format A block boundary.
static int raw_offset(wmbus_frame_fmt_t fmt, int offset)
{
if (fmt == WMBUS_FRAME_A)
return offset < 10 ? offset : offset + 2 + 2 * ((offset - 10) / 16);
return offset + 2 * (offset / 126);
}
bool wmbus_mark_repeated(wmbus_frame_fmt_t fmt, uint8_t *frame, int total_len)
{
if (total_len < 12 || wmbus_frame_total_len(fmt, frame[0]) != total_len)
return false;
if (fmt == WMBUS_FRAME_B && total_len % 128 != 0 && total_len % 128 < 3)
return false;
int data_len = fmt == WMBUS_FRAME_A ? frame[0] + 1
: total_len - 2 * ((total_len + 127) / 128);
if (data_len <= 10 || (frame[1] != 0x44 && frame[1] != 0x46))
return false;
uint8_t ci = frame[raw_offset(fmt, 10)];
int control;
uint8_t hop_mask;
if (ci == 0x8C || ci == 0x8E) {
// Require the complete ELL and a following CI. Its contents remain
// opaque: this link control field is outside the secured payload.
int header_len = ci == 0x8C ? 3 : 11;
if (data_len <= 10 + header_len) return false;
control = raw_offset(fmt, 11);
hop_mask = 0x10;
} else {
int header_len;
switch (ci) {
// OMS uplink CI values with short / long transport headers.
case 0x67: case 0x6E: case 0x74: case 0x7A: case 0x7D:
case 0x7F: case 0x88: case 0x8A: case 0x9E: case 0xC1:
case 0xC4:
header_len = 5;
break;
case 0x68: case 0x6F: case 0x72: case 0x75: case 0x7C:
case 0x7E: case 0x87: case 0x8B: case 0x9F: case 0xC2:
case 0xC5:
header_len = 13;
break;
default:
// Do not guess through unknown or secured encapsulations.
return false;
}
if (data_len < 10 + header_len) return false;
int cf = 10 + header_len - 2;
uint8_t mode = frame[raw_offset(fmt, cf + 1)] & 0x1F;
if (mode != 0 && mode != 5) return false;
control = raw_offset(fmt, cf);
hop_mask = 0x01;
}
// Modern OMS has separate H and R bits, not a two-bit hop count.
if (frame[control] & (hop_mask | 0x02)) return false;
frame[control] |= hop_mask;
int start, count;
if (fmt == WMBUS_FRAME_A) {
start = 12 + 18 * ((control - 12) / 18);
count = total_len - start - 2;
if (count > 16) count = 16;
} else {
start = 128 * (control / 128);
count = total_len - start - 2;
if (count > 126) count = 126;
}
uint16_t crc = wmbus_crc16(frame + start, (size_t)count);
frame[start + count] = crc >> 8;
frame[start + count + 1] = crc & 0xFF;
return true;
}
uint32_t wmbus_hash(const uint8_t *data, size_t len) uint32_t wmbus_hash(const uint8_t *data, size_t len)
{ {
uint32_t h = 2166136261u; uint32_t h = 2166136261u;
@@ -161,3 +236,92 @@ int wmbus_build_test_frame(uint8_t *out, size_t maxlen, uint8_t access_nr,
} }
return total; return total;
} }
// ---- T-mode "3 of 6" codec --------------------------------------------
// nibble -> 6-bit code (EN 13757-4 table 3; inverse of the rtl-wmbus
// LOW_NIBBLE_3OUTOF6 lookup)
static const uint8_t enc3of6[16] = {
0x16, 0x0D, 0x0E, 0x0B, 0x1C, 0x19, 0x1A, 0x13,
0x2C, 0x25, 0x26, 0x23, 0x34, 0x31, 0x32, 0x29,
};
// 6-bit code -> nibble, 0xFF invalid (rtl-wmbus LOW_NIBBLE_3OUTOF6)
static const uint8_t dec3of6[64] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x03, 0xFF, 0x01, 0x02, 0xFF,
0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0x00, 0xFF,
0xFF, 0x05, 0x06, 0xFF, 0x04, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x0B, 0xFF, 0x09, 0x0A, 0xFF,
0xFF, 0x0F, 0xFF, 0xFF, 0x08, 0xFF, 0xFF, 0xFF,
0xFF, 0x0D, 0x0E, 0xFF, 0x0C, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
int wmbus_3of6_coded_len(int total_len)
{
return (total_len * 12 + 7) / 8;
}
static unsigned get6(const uint8_t *b, size_t len, size_t bitpos)
{
size_t byte = bitpos >> 3;
unsigned shift = (unsigned)(bitpos & 7);
unsigned w = (unsigned)b[byte] << 8;
if (byte + 1 < len) w |= b[byte + 1];
return (w >> (10 - shift)) & 0x3F;
}
int wmbus_3of6_decode(const uint8_t *coded, size_t coded_len,
uint8_t *out, int total_len)
{
if (total_len < 0 || (size_t)total_len * 12 > coded_len * 8) return -1;
int bad = 0;
size_t bit = 0;
for (int i = 0; i < total_len; i++) {
uint8_t hi = dec3of6[get6(coded, coded_len, bit)];
uint8_t lo = dec3of6[get6(coded, coded_len, bit + 6)];
bit += 12;
if (hi == 0xFF) { hi = 0; bad++; }
if (lo == 0xFF) { lo = 0; bad++; }
out[i] = (uint8_t)((hi << 4) | lo);
}
return bad;
}
int wmbus_3of6_first_byte(const uint8_t *coded, size_t coded_len)
{
if (coded_len < 2) return -1;
uint8_t hi = dec3of6[get6(coded, coded_len, 0)];
uint8_t lo = dec3of6[get6(coded, coded_len, 6)];
if (hi == 0xFF || lo == 0xFF) return -1;
return (hi << 4) | lo;
}
int wmbus_3of6_encode(const uint8_t *data, int total_len,
uint8_t *coded, size_t maxlen)
{
int coded_len = wmbus_3of6_coded_len(total_len);
if (total_len < 0 || (size_t)coded_len > maxlen) return -1;
uint32_t acc = 0;
int acc_bits = 0;
size_t pos = 0;
for (int i = 0; i < 2 * total_len; i++) {
uint8_t nib = (i & 1) ? (data[i >> 1] & 0x0F)
: (data[i >> 1] >> 4);
acc = (acc << 6) | enc3of6[nib];
acc_bits += 6;
while (acc_bits >= 8) {
coded[pos++] = (uint8_t)(acc >> (acc_bits - 8));
acc_bits -= 8;
}
}
if (acc_bits > 0) {
// pad the tail to the byte boundary with 01 postamble chips
uint8_t tail = (uint8_t)(acc << (8 - acc_bits));
tail |= (uint8_t)(0x55 & (0xFF >> acc_bits));
coded[pos++] = tail;
}
return (int)pos;
}
+34 -1
View File
@@ -1,4 +1,4 @@
// Wireless M-Bus C-mode frame helpers (EN 13757-4). // Wireless M-Bus C/T-mode frame helpers (EN 13757-4).
#pragma once #pragma once
#include <stdint.h> #include <stdint.h>
@@ -28,6 +28,13 @@ bool wmbus_check_crc(wmbus_frame_fmt_t fmt, const uint8_t *frame, int total_len)
// CRC-16 EN 13757 (poly 0x3D65, init 0, complemented result). // CRC-16 EN 13757 (poly 0x3D65, init 0, complemented result).
uint16_t wmbus_crc16(const uint8_t *data, size_t len); uint16_t wmbus_crc16(const uint8_t *data, size_t len);
// Mark an eligible OMS uplink as repeated in place, repairing its block CRC.
// Caller must first validate all CRCs. Supports ELL 8C/8E or a direct short/
// long uplink TPL header in security mode 0/5. ELL takes precedence.
// Returns false, leaving frame unchanged, for unsupported/malformed headers,
// non-SND_NR/SND_IR C-fields, H=1 or R=1. No payload decryption is performed.
bool wmbus_mark_repeated(wmbus_frame_fmt_t fmt, uint8_t *frame, int total_len);
// Build a valid C-mode format A test frame with our test manufacturer/ID. // Build a valid C-mode format A test frame with our test manufacturer/ID.
// Returns total frame length written to out (>= 12), or -1 if payload_len // Returns total frame length written to out (>= 12), or -1 if payload_len
// does not fit. out[0] = L-field. // does not fit. out[0] = L-field.
@@ -36,3 +43,29 @@ int wmbus_build_test_frame(uint8_t *out, size_t maxlen, uint8_t access_nr,
// 32-bit FNV-1a hash used to correlate RX/TX events in the logs. // 32-bit FNV-1a hash used to correlate RX/TX events in the logs.
uint32_t wmbus_hash(const uint8_t *data, size_t len); uint32_t wmbus_hash(const uint8_t *data, size_t len);
// ---- T-mode "3 of 6" codec (EN 13757-4) -------------------------------
// Chips travel MSB-first: the first received chip is bit 7 of coded[0].
// T1 shares the 0x543D access code with C-mode; after it, T1 sends coded
// data directly (no mode bytes). Tables verified against rtl-wmbus
// t1_c1_packet_decoder.h (HIGH/LOW_NIBBLE_3OUTOF6).
// Coded on-air byte count for a decoded byte count: ceil(total * 12 / 8).
int wmbus_3of6_coded_len(int total_len);
// Decode total_len bytes (2 * total_len six-bit codes) from coded[].
// Invalid codes decode as 0x0 nibbles so the CRC can still judge the
// frame. Returns the number of invalid codes (0 = clean), or -1 if
// coded_len holds fewer than total_len * 12 bits.
int wmbus_3of6_decode(const uint8_t *coded, size_t coded_len,
uint8_t *out, int total_len);
// Decode only the first byte (the T1 L-field). Returns 0..255, or -1 if
// either 6-bit code is invalid or fewer than 2 bytes are available.
int wmbus_3of6_first_byte(const uint8_t *coded, size_t coded_len);
// Encode total_len bytes into 3-of-6 chips, padding the final partial
// byte with 01 postamble chips. Returns coded byte count, or -1 if it
// does not fit maxlen.
int wmbus_3of6_encode(const uint8_t *data, int total_len,
uint8_t *coded, size_t maxlen);
+4
View File
@@ -19,3 +19,7 @@ CONFIG_ESP_TASK_WDT_PANIC=y
# Keep bootloader/app log noise low; all HIL-relevant output is JSON lines # Keep bootloader/app log noise low; all HIL-relevant output is JSON lines
CONFIG_LOG_DEFAULT_LEVEL_WARN=y CONFIG_LOG_DEFAULT_LEVEL_WARN=y
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
# Keep network processing off the timing-sensitive radio task's core.
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y
CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0=y
+19
View File
@@ -14,3 +14,22 @@ trap 'rm -rf "$OUT"' EXIT
-o "$OUT/test_wmbus" test_wmbus.c ../main/wmbus.c -o "$OUT/test_wmbus" test_wmbus.c ../main/wmbus.c
"$OUT/test_wmbus" "$OUT/test_wmbus"
"$CC" -std=c11 -O1 -g -Wall -Wextra -Werror \
-fsanitize=address,undefined -fno-omit-frame-pointer \
-I../main -o "$OUT/test_duty_ledger" \
test_duty_ledger.c ../main/duty_ledger.c
"$OUT/test_duty_ledger"
"$CC" -std=c11 -O1 -g -Wall -Wextra -Werror \
-fsanitize=address,undefined -fno-omit-frame-pointer \
-I../main -o "$OUT/test_t1_long" \
test_t1_long.c ../main/wmbus.c
"$OUT/test_t1_long"
"$CC" -std=c11 -O1 -g -Wall -Wextra -Werror \
-I../main -o "$OUT/test_font_render" test_font_render.c
"$OUT/test_font_render" | tail -1
+58
View File
@@ -0,0 +1,58 @@
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "duty_ledger.h"
static void test_accumulates_without_event_limit(void)
{
duty_ledger_t ledger = {0};
for (int i = 0; i < 10000; i++) {
duty_ledger_record(&ledger, 1000000, 100);
}
assert(duty_ledger_used(&ledger, 2000000) == 1000000);
}
static void test_retains_every_overlapping_minute(void)
{
duty_ledger_t ledger = {0};
for (int minute = 0; minute <= 60; minute++) {
duty_ledger_record(&ledger, (int64_t)minute * DUTY_LEDGER_BUCKET_US, 100);
}
// The oldest partially overlapping minute is deliberately included.
assert(duty_ledger_used(&ledger,
60 * DUTY_LEDGER_BUCKET_US + DUTY_LEDGER_BUCKET_US / 2) == 6100);
// Reusing the ring slot at minute 61 cannot discard in-window airtime.
duty_ledger_record(&ledger, 61 * DUTY_LEDGER_BUCKET_US, 200);
assert(duty_ledger_used(&ledger, 61 * DUTY_LEDGER_BUCKET_US) == 6200);
}
static void test_expires_whole_old_buckets(void)
{
duty_ledger_t ledger = {0};
duty_ledger_record(&ledger, 0, 123);
assert(duty_ledger_used(&ledger, DUTY_LEDGER_WINDOW_US) == 123);
assert(duty_ledger_used(&ledger,
DUTY_LEDGER_WINDOW_US + DUTY_LEDGER_BUCKET_US) == 0);
}
static void test_rejects_invalid_records(void)
{
duty_ledger_t ledger = {0};
duty_ledger_record(&ledger, -1, 100);
duty_ledger_record(&ledger, 1, 0);
assert(duty_ledger_used(&ledger, 1) == 0);
assert(duty_ledger_used(&ledger, -1) == 0);
}
int main(void)
{
test_accumulates_without_event_limit();
test_retains_every_overlapping_minute();
test_expires_whole_old_buckets();
test_rejects_invalid_records();
puts("duty ledger tests: PASS");
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
// Host-side visual check of the 5x7 font: renders representative UI text
// as ASCII art so the glyph table can be reviewed without hardware, and
// asserts basic structural invariants.
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "font5x7.h"
static void render_line(const char *text)
{
char rows[FONT5X7_H][128];
int cols = 0;
memset(rows, 0, sizeof(rows));
for (const char *p = text; *p && cols + 6 < 120; p++) {
unsigned c = (unsigned char)*p;
if (c < FONT5X7_FIRST || c > FONT5X7_LAST) c = '?';
const uint8_t *g = font5x7[c - FONT5X7_FIRST];
for (int x = 0; x < FONT5X7_W; x++) {
for (int y = 0; y < FONT5X7_H; y++) {
rows[y][cols + x] = (g[x] >> y) & 1 ? '#' : ' ';
}
}
for (int y = 0; y < FONT5X7_H; y++) rows[y][cols + 5] = ' ';
cols += 6;
}
for (int y = 0; y < FONT5X7_H; y++) {
rows[y][cols] = 0;
printf("|%s|\n", rows[y]);
}
printf("\n");
}
int main(void)
{
// Every printable glyph except space must have at least one pixel.
for (int c = FONT5X7_FIRST + 1; c <= FONT5X7_LAST; c++) {
int bits = 0;
for (int x = 0; x < FONT5X7_W; x++) {
const uint8_t *g = font5x7[c - FONT5X7_FIRST];
for (int y = 0; y < FONT5X7_H; y++) bits += (g[x] >> y) & 1;
assert((g[x] & 0x80) == 0); // 7 rows only
}
assert(bits > 0);
}
render_line("WMBUS RPT 868.95 C1");
render_line("RX 389 TX 381 OK");
render_line("DUTY [####-] 0.09%");
render_line("0123456789 +-/:=.#%");
render_line("ABCDEFGHIJKLM");
render_line("NOPQRSTUVWXYZ");
puts("font render test: PASS (inspect art above)");
return 0;
}
+130
View File
@@ -0,0 +1,130 @@
// T-mode 3-of-6 codec + long-frame CRC path tests (host, sanitizers).
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "wmbus.h"
static void test_codec_roundtrip_all_values(void)
{
uint8_t data[256], coded[512], back[256];
for (int i = 0; i < 256; i++) data[i] = (uint8_t)i;
int clen = wmbus_3of6_encode(data, 256, coded, sizeof(coded));
assert(clen == wmbus_3of6_coded_len(256));
assert(clen == 384); // 256 * 1.5
assert(wmbus_3of6_decode(coded, (size_t)clen, back, 256) == 0);
assert(memcmp(data, back, 256) == 0);
assert(wmbus_3of6_first_byte(coded, (size_t)clen) == 0x00);
}
static void test_codec_detects_any_single_chip_flip(void)
{
// 3-of-6 codes have constant weight 3: one flipped chip changes the
// weight, so every single-bit corruption inside the coded payload
// must surface as an invalid code.
uint8_t data[32], coded[64], back[32];
for (int i = 0; i < 32; i++) data[i] = (uint8_t)(i * 37 + 5);
int clen = wmbus_3of6_encode(data, 32, coded, sizeof(coded));
assert(clen == 48);
for (int bit = 0; bit < 32 * 12; bit++) {
coded[bit >> 3] ^= (uint8_t)(0x80u >> (bit & 7));
assert(wmbus_3of6_decode(coded, (size_t)clen, back, 32) > 0);
coded[bit >> 3] ^= (uint8_t)(0x80u >> (bit & 7));
}
assert(wmbus_3of6_decode(coded, (size_t)clen, back, 32) == 0);
}
static void test_codec_bounds(void)
{
uint8_t coded[8] = {0};
uint8_t out[8];
assert(wmbus_3of6_decode(coded, 2, out, 2) == -1); // 24 bits > 16
assert(wmbus_3of6_first_byte(coded, 1) == -1);
assert(wmbus_3of6_first_byte(coded, 2) == -1); // 000000 invalid
uint8_t d[4] = {0};
assert(wmbus_3of6_encode(d, 4, coded, 5) == -1); // needs 6
}
static void test_t1_frame_roundtrip(void)
{
uint8_t frame[256], coded[512], back[256];
int total = wmbus_build_test_frame(frame, sizeof(frame), 42, 100);
assert(total > 0);
int clen = wmbus_3of6_encode(frame, total, coded, sizeof(coded));
assert(clen == wmbus_3of6_coded_len(total));
assert(wmbus_3of6_first_byte(coded, (size_t)clen) == frame[0]);
assert(wmbus_3of6_decode(coded, (size_t)clen, back, total) == 0);
assert(memcmp(frame, back, total) == 0);
assert(wmbus_check_crc(WMBUS_FRAME_A, back, total));
}
static void build_b_frame(uint8_t *out, uint8_t lfield)
{
int total = 1 + lfield;
out[0] = lfield;
for (int i = 1; i < total; i++) out[i] = (uint8_t)(i * 73 + 11);
if (total > 128) {
// two chunks: CRC over first 126 at [126..127], rest at the tail
int rem = total - 128;
assert(rem >= 3);
uint16_t c = wmbus_crc16(out, 126);
out[126] = c >> 8; out[127] = c & 0xFF;
c = wmbus_crc16(out + 128, rem - 2);
out[total - 2] = c >> 8; out[total - 1] = c & 0xFF;
} else {
uint16_t c = wmbus_crc16(out, total - 2);
out[total - 2] = c >> 8; out[total - 1] = c & 0xFF;
}
}
static void test_format_b_long(void)
{
uint8_t f[256];
// > 128 bytes: two CRC chunks
build_b_frame(f, 200);
assert(wmbus_frame_total_len(WMBUS_FRAME_B, 200) == 201);
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 201));
// corruption in either chunk must fail
f[50] ^= 1;
assert(!wmbus_check_crc(WMBUS_FRAME_B, f, 201));
f[50] ^= 1;
f[150] ^= 1;
assert(!wmbus_check_crc(WMBUS_FRAME_B, f, 201));
f[150] ^= 1;
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 201));
// exactly one full chunk
build_b_frame(f, 127);
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 128));
// short frame
build_b_frame(f, 20);
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 21));
// maximum that fits the radio payload
build_b_frame(f, 252);
assert(wmbus_frame_total_len(WMBUS_FRAME_B, 252) == 253);
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 253));
}
static void test_format_a_long(void)
{
uint8_t frame[256];
int total = wmbus_build_test_frame(frame, sizeof(frame), 7, 200);
assert(total == 227); // 1 + 200 + 2 * (1 + ceil(191/16))
assert(wmbus_check_crc(WMBUS_FRAME_A, frame, total));
frame[220] ^= 1;
assert(!wmbus_check_crc(WMBUS_FRAME_A, frame, total));
// beyond the fixed radio capture: must be rejected, not truncated
assert(wmbus_frame_total_len(WMBUS_FRAME_A, 255) == -1);
}
int main(void)
{
test_codec_roundtrip_all_values();
test_codec_detects_any_single_chip_flip();
test_codec_bounds();
test_t1_frame_roundtrip();
test_format_b_long();
test_format_a_long();
puts("t1 + long-frame tests: PASS");
return 0;
}
+210 -1
View File
@@ -162,9 +162,213 @@ static void test_builder_roundtrip(void)
"builder must refuse a buffer that cannot hold the frame"); "builder must refuse a buffer that cannot hold the frame");
} }
// Pack cooked bytes independently of the production raw-frame walker. Only
// the CRC primitive is shared (anchored by the captured known-answer test).
static int pack_hop_frame(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len,
uint8_t *raw)
{
assert(len >= 10 && len <= 200);
int total = fmt == WMBUS_FRAME_A
? len + 2 * (1 + (len - 10 + 15) / 16)
: len + (len > 126 ? 4 : 2);
cooked[0] = (uint8_t)(fmt == WMBUS_FRAME_A ? len - 1 : total - 1);
int src = 0, dst = 0;
while (src < len) {
int block = fmt == WMBUS_FRAME_A ? (src == 0 ? 10 : 16) : 126;
if (block > len - src) block = len - src;
memcpy(raw + dst, cooked + src, (size_t)block);
uint16_t crc = wmbus_crc16(cooked + src, (size_t)block);
raw[dst + block] = (uint8_t)(crc >> 8);
raw[dst + block + 1] = (uint8_t)crc;
src += block;
dst += block + 2;
}
assert(dst == total);
return total;
}
static void init_hop_frame(uint8_t *cooked, int len, uint8_t ci)
{
for (int i = 0; i < len; i++) cooked[i] = (uint8_t)(i * 73 + 11);
cooked[1] = 0x44;
cooked[10] = ci;
}
static void check_hop_mark(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len,
int h_offset, uint8_t h_mask)
{
uint8_t raw[300], expected[300];
memset(raw, 0xA5, sizeof(raw));
memset(expected, 0xA5, sizeof(expected));
int total = pack_hop_frame(fmt, cooked, len, raw);
CHECK(wmbus_check_crc(fmt, raw, total), "invalid hop input fixture");
cooked[h_offset] |= h_mask;
pack_hop_frame(fmt, cooked, len, expected);
cooked[h_offset] &= (uint8_t)~h_mask;
CHECK(wmbus_mark_repeated(fmt, raw, total),
"fmt=%d CI=%02X: unmarked frame refused", fmt, cooked[10]);
CHECK(memcmp(raw, expected, sizeof(raw)) == 0,
"fmt=%d CI=%02X: bytes other than H and its CRC changed",
fmt, cooked[10]);
CHECK(wmbus_check_crc(fmt, raw, total), "marked frame has invalid CRC");
CHECK(!wmbus_mark_repeated(fmt, raw, total), "second hop accepted");
CHECK(memcmp(raw, expected, sizeof(raw)) == 0,
"refused second hop changed frame");
if (fmt == WMBUS_FRAME_A) {
uint8_t coded[450], decoded[300];
int coded_len = wmbus_3of6_encode(raw, total, coded, sizeof(coded));
CHECK(coded_len > 0, "marked T1 frame did not encode");
if (coded_len > 0) {
CHECK(wmbus_3of6_first_byte(coded, (size_t)coded_len) == raw[0],
"marked T1 frame lost L-field");
CHECK(wmbus_3of6_decode(coded, (size_t)coded_len, decoded, total) == 0,
"marked T1 frame did not decode");
CHECK(memcmp(decoded, expected, (size_t)total) == 0,
"T1 roundtrip lost hop mark or changed payload");
CHECK(wmbus_check_crc(fmt, decoded, total),
"decoded marked T1 frame has invalid CRC");
}
}
}
static void check_hop_refused(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len)
{
uint8_t raw[300], before[300];
memset(raw, 0xA5, sizeof(raw));
int total = pack_hop_frame(fmt, cooked, len, raw);
memcpy(before, raw, sizeof(raw));
CHECK(wmbus_check_crc(fmt, raw, total), "invalid refusal fixture");
CHECK(!wmbus_mark_repeated(fmt, raw, total),
"fmt=%d CI=%02X: unsupported/repeated frame accepted",
fmt, cooked[10]);
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
"refused frame changed bytes");
}
static void test_hop_tpl(void)
{
static const uint8_t short_ci[] = {
0x67, 0x6E, 0x74, 0x7A, 0x7D, 0x7F, 0x88, 0x8A, 0x9E, 0xC1, 0xC4,
};
static const uint8_t long_ci[] = {
0x68, 0x6F, 0x72, 0x75, 0x7C, 0x7E, 0x87, 0x8B, 0x9F, 0xC2, 0xC5,
};
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
for (int long_header = 0; long_header <= 1; long_header++) {
const uint8_t *cis = long_header ? long_ci : short_ci;
int cf = long_header ? 21 : 13;
uint8_t cooked[200];
for (size_t i = 0; i < sizeof(short_ci); i++) {
// Long bodies cross A's 16-byte blocks and B's 126-byte
// first block; exact comparison protects all ciphertext.
for (int mode = 0; mode <= 5; mode += 5) {
init_hop_frame(cooked, sizeof(cooked), cis[i]);
cooked[1] = i % 2 ? 0x46 : 0x44;
cooked[cf] = 0xA4;
cooked[cf + 1] = (uint8_t)(0xE0 | mode);
check_hop_mark(fmt, cooked, sizeof(cooked), cf, 0x01);
}
}
init_hop_frame(cooked, sizeof(cooked), cis[0]);
cooked[cf] = 0xA4;
cooked[cf + 1] = 7;
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[cf + 1] = 5;
cooked[cf] |= 0x01;
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[cf] = 0xA6;
check_hop_refused(fmt, cooked, sizeof(cooked));
// A complete transport header needs no application payload,
// but every shorter prefix must be refused without mutation.
cooked[cf] = 0xA4;
cooked[1] = 0x54; // not a masked variant of SND_NR
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[1] = 0x44;
check_hop_mark(fmt, cooked, cf + 2, cf, 0x01);
for (int len = 11; len < cf + 2; len++)
check_hop_refused(fmt, cooked, len);
}
}
}
static void test_hop_ell(void)
{
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
for (int long_header = 0; long_header <= 1; long_header++) {
uint8_t cooked[200];
int inner = long_header ? 21 : 13;
init_hop_frame(cooked, sizeof(cooked), long_header ? 0x8E : 0x8C);
cooked[11] = 0xE5; // preserve every non-H/R CC bit
cooked[inner] = 0x72;
cooked[inner + 11] = 0x03; // inner TPL already H=R=1
cooked[inner + 12] = 7; // encrypted/authenticated inner TPL
check_hop_mark(fmt, cooked, sizeof(cooked), 11, 0x10);
// Exactly full and one-byte-over CRC blocks. For long ELL the
// inner TPL crosses A's block boundary; it must remain opaque.
int boundary = fmt == WMBUS_FRAME_A ? 26 : 126;
check_hop_mark(fmt, cooked, boundary, 11, 0x10);
check_hop_mark(fmt, cooked, boundary + 1, 11, 0x10);
cooked[inner] = 0x90; // AFL is opaque beneath a usable ELL
check_hop_mark(fmt, cooked, sizeof(cooked), 11, 0x10);
cooked[inner] = 0x78;
cooked[1] = 0x46;
check_hop_mark(fmt, cooked, inner + 1, 11, 0x10);
for (int len = 11; len <= inner; len++)
check_hop_refused(fmt, cooked, len);
cooked[11] |= 0x10;
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[11] = 0xE7;
check_hop_refused(fmt, cooked, sizeof(cooked));
}
}
}
static void test_hop_invalid_headers(void)
{
static const uint8_t unsupported_ci[] = {0x78, 0x8D, 0x8F, 0x90, 0x00, 0xFF};
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
uint8_t cooked[40], raw[300], before[300];
for (size_t i = 0; i < sizeof(unsupported_ci); i++) {
init_hop_frame(cooked, sizeof(cooked), unsupported_ci[i]);
cooked[11] = 0;
check_hop_refused(fmt, cooked, sizeof(cooked));
}
init_hop_frame(cooked, sizeof(cooked), 0x8C);
cooked[11] = 0;
// Only these two exact C-fields are valid, not masked variants.
for (int c = 0; c <= 255; c++) {
if (c == 0x44 || c == 0x46) continue;
cooked[1] = (uint8_t)c;
check_hop_refused(fmt, cooked, sizeof(cooked));
}
cooked[1] = 0x44;
check_hop_refused(fmt, cooked, 10); // no CI; A has only block 1
memset(raw, 0xA5, sizeof(raw));
int total = pack_hop_frame(fmt, cooked, sizeof(cooked), raw);
memcpy(before, raw, sizeof(raw));
for (int len = -1; len <= total + 1; len++) {
if (len == total) continue;
CHECK(!wmbus_mark_repeated(fmt, raw, len),
"mismatched raw length %d accepted (actual %d)", len, total);
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
"invalid raw length changed frame");
}
CHECK(!wmbus_mark_repeated(WMBUS_FRAME_UNKNOWN, raw, total),
"unknown format accepted");
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
"unknown format changed frame");
}
}
// Adversarial input: random bytes with a length that disagrees with the // Adversarial input: random bytes with a length that disagrees with the
// L-field, exactly what a corrupted reception looks like. Under ASan this // L-field, exactly what a corrupted reception looks like. Under ASan this
// proves the CRC walk never indexes outside the buffer. // proves the CRC and hop-header walks never index outside the buffer.
static void test_fuzz_bounds(void) static void test_fuzz_bounds(void)
{ {
srand(12345); srand(12345);
@@ -183,8 +387,10 @@ static void test_fuzz_bounds(void)
int total = wmbus_frame_total_len(fmt, buf[0]); int total = wmbus_frame_total_len(fmt, buf[0]);
if (total > 0 && total <= n) { if (total > 0 && total <= n) {
(void)wmbus_check_crc(fmt, buf, total); (void)wmbus_check_crc(fmt, buf, total);
(void)wmbus_mark_repeated(fmt, buf, total);
} }
(void)wmbus_check_crc(fmt, buf, n); (void)wmbus_check_crc(fmt, buf, n);
(void)wmbus_mark_repeated(fmt, buf, n);
(void)wmbus_hash(buf, (size_t)n); (void)wmbus_hash(buf, (size_t)n);
free(buf); free(buf);
} }
@@ -211,6 +417,9 @@ int main(void)
test_length_formulas(); test_length_formulas();
test_frame_format_detection(); test_frame_format_detection();
test_builder_roundtrip(); test_builder_roundtrip();
test_hop_tpl();
test_hop_ell();
test_hop_invalid_headers();
test_fuzz_bounds(); test_fuzz_bounds();
if (failures) { if (failures) {
+38
View File
@@ -0,0 +1,38 @@
// Host tool: feed captured post-sync payload bytes (hex on argv[1]) through
// the firmware's T1 classification/decode path exactly as handle_rx does.
// Prints the decode result for cross-checking against a known transmitted
// frame. Not part of run_tests.sh; used by ad-hoc RF verification.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wmbus.h"
int main(int argc, char **argv)
{
if (argc != 2) { fprintf(stderr, "usage: %s HEXBYTES\n", argv[0]); return 2; }
size_t hexlen = strlen(argv[1]);
static uint8_t buf[512];
size_t n = hexlen / 2;
if (n > sizeof(buf)) n = sizeof(buf);
for (size_t i = 0; i < n; i++) {
unsigned v;
if (sscanf(argv[1] + 2 * i, "%2x", &v) != 1) return 2;
buf[i] = (uint8_t)v;
}
int lfield = wmbus_3of6_first_byte(buf, n);
printf("lfield=%d\n", lfield);
if (lfield < 9) return 1;
int total = wmbus_frame_total_len(WMBUS_FRAME_A, (uint8_t)lfield);
printf("total=%d coded_len=%d have=%zu\n",
total, total > 0 ? wmbus_3of6_coded_len(total) : -1, n);
if (total < 0 || wmbus_3of6_coded_len(total) > (int)n) return 1;
static uint8_t frame[512];
int bad = wmbus_3of6_decode(buf, n, frame, total);
int crc = wmbus_check_crc(WMBUS_FRAME_A, frame, total);
printf("bad_codes=%d crc_ok=%d\nframe=", bad, crc);
for (int i = 0; i < total; i++) printf("%02X", frame[i]);
printf("\n");
return crc ? 0 : 1;
}
+24 -5
View File
@@ -22,19 +22,38 @@ for i in $(seq 1 "$SEGS"); do
./result-py/bin/python3 hil/dut_cmd.py "$P" --listen $((DUR + 4)) \ ./result-py/bin/python3 hil/dut_cmd.py "$P" --listen $((DUR + 4)) \
> "$D/serial.log" 2>&1 > "$D/serial.log" 2>&1
wait wait
SZ=$(stat -c%s "$D/iq.raw" 2>/dev/null || echo 0)
if [ "$SZ" -lt $((DUR * 3200000 * 8 / 10)) ]; then
echo "{\"seg\":$i,\"error\":\"short_capture\",\"bytes\":$SZ,\"t\":$(date +%s)}" >> "$OUT/soak.jsonl"
rm -f "$D/iq.raw"
usbreset 0bda:2838 >/dev/null 2>&1
sleep 10
continue
fi
V=$(./result-py/bin/python3 hil/meter_anchored.py \ V=$(./result-py/bin/python3 hil/meter_anchored.py \
--iq "$D/iq.raw" --serial "$D/serial.log" --json 2>/dev/null) --iq "$D/iq.raw" --serial "$D/serial.log" --json 2>"$D/verdict.err")
RC=$? RC=$?
STATE=""
if [ -n "$V" ]; then if [ -n "$V" ]; then
echo "$V" | ./result-py/bin/python3 -c \ STATE=$(printf '%s\n' "$V" | ./result-py/bin/python3 -c \
"import json,sys; print(json.load(sys.stdin).get('rf_state','unknown'))")
printf '%s\n' "$V" | ./result-py/bin/python3 -c \
"import json,sys,time; d=json.load(sys.stdin); d['seg']=$i; d['rc']=$RC; d['t']=int(time.time()); print(json.dumps(d))" \ "import json,sys,time; d=json.load(sys.stdin); d['seg']=$i; d['rc']=$RC; d['t']=int(time.time()); print(json.dumps(d))" \
>> "$OUT/soak.jsonl" >> "$OUT/soak.jsonl"
else else
echo "{\"seg\":$i,\"rc\":$RC,\"error\":\"no_verdict\",\"t\":$(date +%s)}" >> "$OUT/soak.jsonl" echo "{\"seg\":$i,\"rc\":$RC,\"error\":\"no_verdict\",\"t\":$(date +%s)}" >> "$OUT/soak.jsonl"
fi fi
# keep disk bounded: drop IQ after verdict, keep serial # Strong segments are summarized and discarded. Retain every weak,
rm -f "$D/iq.raw" # absent, or unclassified segment so a hardware conclusion is auditable.
if [ "$RC" = "3" ]; then if [ "$STATE" = "strong" ] && [ "$RC" = "0" ]; then
rm -f "$D/iq.raw"
else
echo "{\"seg\":$i,\"note\":\"iq_retained\",\"rf_state\":\"$STATE\",\"t\":$(date +%s)}" >> "$OUT/soak.jsonl"
fi
if grep -q "lost at least" "$D/rtl_sdr.err" 2>/dev/null; then
echo "{\"seg\":$i,\"note\":\"sample_drops\",\"t\":$(date +%s)}" >> "$OUT/soak.jsonl"
fi
if [ "$RC" != "0" ] && [ "$RC" != "1" ]; then
usbreset 0bda:2838 >/dev/null 2>&1 usbreset 0bda:2838 >/dev/null 2>&1
sleep 8 sleep 8
fi fi
+55 -13
View File
@@ -10,8 +10,8 @@ Output: JSON report on stdout.
Correlation model (developer repeat delay ~50 ms): Correlation model (developer repeat delay ~50 ms):
SDR original <-> Heltec RX : same cooked bytes, |dt| < rx_window SDR original <-> Heltec RX : same cooked bytes, |dt| < rx_window
Heltec RX <-> Heltec TX : same hash (firmware log) Heltec RX <-> Heltec TX : same hash (firmware log)
Heltec TX <-> SDR repeat : same cooked bytes, dt in [min_delay, max_delay] SDR original <-> SDR repeat : only H changes 0 -> 1 on a supported header,
after the SDR original dt in [min_delay, max_delay]
The Heltec logs raw over-the-air frames (with CRCs); rtl_wmbus prints The Heltec logs raw over-the-air frames (with CRCs); rtl_wmbus prints
"cooked" frames (CRCs stripped). cook() below mirrors rtl-wmbus. "cooked" frames (CRCs stripped). cook() below mirrors rtl-wmbus.
@@ -69,6 +69,42 @@ def cook_b(frame: bytes):
return bytes(out) return bytes(out)
def expected_repeat(cooked: bytes):
"""Return the H-marked counterpart of a supported CRC-stripped original.
Both format A and rtl-wmbus-normalized format B use L = cooked length - 1.
ELL hop control takes precedence over any encapsulated transport header.
Unsupported layouts, H=1 and R=1 cannot originate a received repeat.
"""
if len(cooked) < 11 or cooked[0] != len(cooked) - 1:
return None
if cooked[1] not in (0x44, 0x46):
return None
ci = cooked[10]
if ci in (0x8c, 0x8e):
# CI + CC + ACC, optionally eight address bytes, then another CI.
if len(cooked) < (14 if ci == 0x8c else 22):
return None
pos, h_mask = 11, 0x10
else:
if ci in (0x67, 0x6e, 0x74, 0x7a, 0x7d, 0x7f, 0x88, 0x8a,
0x9e, 0xc1, 0xc4):
pos = 13
elif ci in (0x68, 0x6f, 0x72, 0x75, 0x7c, 0x7e, 0x87, 0x8b,
0x9f, 0xc2, 0xc5):
pos = 21
else:
return None
if len(cooked) <= pos + 1 or cooked[pos + 1] & 0x1f not in (0, 5):
return None
h_mask = 0x01
if cooked[pos] & (h_mask | 0x02):
return None
marked = bytearray(cooked)
marked[pos] |= h_mask
return bytes(marked)
def parse_serial(path): def parse_serial(path):
"""Heltec JSON-lines -> (rx_events, tx_events, other).""" """Heltec JSON-lines -> (rx_events, tx_events, other)."""
rx, tx, other = [], [], [] rx, tx, other = [], [], []
@@ -133,31 +169,37 @@ def main():
heltec_rx, heltec_tx, other = parse_serial(args.serial) heltec_rx, heltec_tx, other = parse_serial(args.serial)
sdr = parse_sdr(args.sdr) sdr = parse_sdr(args.sdr)
sdr_c1 = [s for s in sdr if s["mode"] == "C1" and s["crc_ok"]] sdr_frames = [s for s in sdr if s["mode"] in ("C1", "T1") and s["crc_ok"]]
# rtl_wmbus runs two demodulator algorithms concurrently; a single burst # rtl_wmbus runs two demodulator algorithms concurrently; a single burst
# can be reported twice within ~1 ms. Collapse identical bytes < 5 ms apart. # can be reported twice within ~1 ms. Collapse identical bytes < 5 ms apart.
deduped = [] deduped = []
for s in sorted(sdr_c1, key=lambda x: x["t"]): for s in sorted(sdr_frames, key=lambda x: x["t"]):
if deduped and deduped[-1]["cooked"] == s["cooked"] \ if deduped and deduped[-1]["mode"] == s["mode"] \
and deduped[-1]["cooked"] == s["cooked"] \
and s["t"] - deduped[-1]["t"] < 0.005: and s["t"] - deduped[-1]["t"] < 0.005:
continue continue
deduped.append(s) deduped.append(s)
sdr_c1 = deduped sdr_frames = deduped
expected = [expected_repeat(s["cooked"]) for s in sdr_frames]
# --- classify SDR frames into originals vs repeats --------------------- # --- classify SDR frames into originals vs repeats ---------------------
# A repeat is an SDR frame with identical cooked bytes to an earlier SDR # A repeat changes only H from 0 to 1 on a supported original header
# frame within [min_delay, max_delay]. Everything else is an original. # within [min_delay, max_delay]. Same-H duplicates are not repeats.
originals, repeats = [], [] originals, repeats = [], []
for i, s in enumerate(sdr_c1): used_originals = set()
for i, s in enumerate(sdr_frames):
matched = None matched = None
for j in range(i - 1, -1, -1): for j in range(i - 1, -1, -1):
prev = sdr_c1[j] prev = sdr_frames[j]
dt = s["t"] - prev["t"] dt = s["t"] - prev["t"]
if dt > args.max_delay: if dt > args.max_delay:
break break
if prev["cooked"] == s["cooked"] and args.min_delay <= dt <= args.max_delay: if (j not in used_originals and prev["mode"] == s["mode"]
and expected[j] == s["cooked"]
and args.min_delay <= dt <= args.max_delay):
matched = (j, dt) matched = (j, dt)
used_originals.add(j)
break break
if matched is not None: if matched is not None:
repeats.append({"idx": i, "orig_idx": matched[0], "dt": matched[1], **s}) repeats.append({"idx": i, "orig_idx": matched[0], "dt": matched[1], **s})
@@ -197,7 +239,6 @@ def main():
verified_repeats = 0 verified_repeats = 0
for rep in repeats: for rep in repeats:
orig = sdr_c1[rep["orig_idx"]]
o_entry = next((o for o in originals if o["idx"] == rep["orig_idx"]), None) o_entry = next((o for o in originals if o["idx"] == rep["orig_idx"]), None)
hr = o_entry.get("heltec_rx") if o_entry else None hr = o_entry.get("heltec_rx") if o_entry else None
if hr and hr.get("hash") in tx_by_hash: if hr and hr.get("hash") in tx_by_hash:
@@ -213,7 +254,8 @@ def main():
report = { report = {
"sdr_frames_total": len(sdr), "sdr_frames_total": len(sdr),
"sdr_c1_crc_ok": len(sdr_c1), "sdr_c1_crc_ok": sum(s["mode"] == "C1" for s in sdr_frames),
"sdr_t1_crc_ok": sum(s["mode"] == "T1" for s in sdr_frames),
"sdr_originals": len(originals), "sdr_originals": len(originals),
"sdr_repeats": len(repeats), "sdr_repeats": len(repeats),
"heltec_rx": len(heltec_rx), "heltec_rx": len(heltec_rx),
+108 -16
View File
@@ -9,10 +9,10 @@ The only trustworthy way we have found to verify DUT transmissions in IQ:
3. Report ambient meter levels alongside -- they are the in-band health 3. Report ambient meter levels alongside -- they are the in-band health
control for the observer (deaf dongle => meters compressed => run void). control for the observer (deaf dongle => meters compressed => run void).
Why not fit the clock on TX events (hil/verify_repeats_iq.py, single-burst Why not fit the clock on TX events (the removed verify_repeats_iq.py did):
mode): repeats fire RX + delay by construction, so an offset shifted by repeats fire RX + delay by construction, so an offset shifted by -delay
-delay "matches" every repeat to its own original's burst. That artifact "matches" every repeat to its own original's burst. That artifact produced
produced fake "7/7 at +37 dB" confirmations. See docs/FINDINGS.md. fake "7/7 at +37 dB" confirmations. See docs/FINDINGS.md.
Usage: meter_anchored.py --iq FILE --serial FILE [--json] Usage: meter_anchored.py --iq FILE --serial FILE [--json]
""" """
@@ -71,6 +71,62 @@ def fit_clock(bursts, anchors_ms, span_ms):
best = (off, m, e) best = (off, m, e)
return best # offset, matched, median_err return best # offset, matched, median_err
def fsk_spectral_excess(path, db, floor, event_times_ms):
"""Return event-correlated 45 kHz FSK excess over nearby control windows."""
nfft = 2048
fft_window = np.hanning(nfft)
raw = np.memmap(path, dtype=np.uint8, mode="r")
sample_count = raw.size // 2
event_times = np.asarray(event_times_ms, dtype=float)
event_psd, control_psd = [], []
def spectrum(center):
lo = center - nfft // 2
hi = lo + nfft
if lo < 0 or hi > sample_count:
return None
values = raw[2 * lo:2 * hi].astype(np.float32) - 127.5
iq = values[0::2] + 1j * values[1::2]
return np.abs(np.fft.fftshift(np.fft.fft(iq * fft_window))) ** 2
for ts_ms in event_times:
a0, a1 = int(ts_ms) - 2, int(ts_ms) + 12
if not (0 <= a0 < a1 < len(db)):
continue
peak_bin = a0 + int(np.argmax(db[a0:a1] - floor))
event = spectrum(peak_bin * WIN + WIN // 2)
if event is None:
continue
control = None
for delta_ms in (100, 200, -100, -200):
control_bin = peak_bin + delta_ms
if not (0 <= control_bin < len(db)):
continue
if np.any(np.abs(event_times - control_bin) < 25):
continue
control = spectrum(control_bin * WIN + WIN // 2)
if control is not None:
break
if control is None:
continue
event_psd.append(event)
control_psd.append(control)
if len(event_psd) < 5:
return None, len(event_psd)
event_med = np.median(np.stack(event_psd), axis=0)
control_med = np.median(np.stack(control_psd), axis=0)
freq = np.fft.fftshift(np.fft.fftfreq(nfft, 1 / FS))
signal = (np.abs(freq) >= 20000) & (np.abs(freq) < 80000)
wide = (np.abs(freq) >= 250000) & (np.abs(freq) < 700000)
signal_db = 10 * np.log10(event_med[signal].sum()
/ control_med[signal].sum())
wide_db = 10 * np.log10(event_med[wide].sum()
/ control_med[wide].sum())
return float(signal_db - wide_db), len(event_psd)
def main(): def main():
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
@@ -81,7 +137,12 @@ def main():
ap.add_argument("--json", action="store_true") ap.add_argument("--json", action="store_true")
args = ap.parse_args() args = ap.parse_args()
db, floor = envelope(args.iq) try:
db, floor = envelope(args.iq)
except (FileNotFoundError, ValueError):
print("IQ file missing or unreadable -- capture never started",
file=sys.stderr)
sys.exit(3)
bursts = bursts_of(db, floor) bursts = bursts_of(db, floor)
rx, tx = parse_serial(args.serial) rx, tx = parse_serial(args.serial)
strong = [r for r in rx strong = [r for r in rx
@@ -98,6 +159,13 @@ def main():
anchors = np.array([r["timestamp_us"] / 1000.0 for r in strong]) anchors = np.array([r["timestamp_us"] / 1000.0 for r in strong])
span = len(db) span = len(db)
off, matched, err = fit_clock(bursts, anchors, span) off, matched, err = fit_clock(bursts, anchors, span)
# A broken clock (sample drops, dongle stalls) makes every TX window
# meaningless. Reject rather than emit garbage.
if matched < max(5, len(strong) * 0.6) or err > 5.0:
print(f"clock fit unusable: {matched}/{len(strong)} anchors, "
f"median err {err:.1f} ms -- IQ stream integrity suspect",
file=sys.stderr)
sys.exit(3)
bst = np.array([b[0] for b in bursts], dtype=float) bst = np.array([b[0] for b in bursts], dtype=float)
meter_lv = [] meter_lv = []
@@ -112,19 +180,35 @@ def main():
return None return None
return float((db[a0:a1] - floor).max()) return float((db[a0:a1] - floor).max())
events = [] events, mapped_tx = [], []
for t in tx: for t in tx:
w = winmax(t["timestamp_us"] / 1000.0 - off) mapped = t["timestamp_us"] / 1000.0 - off
w = winmax(mapped)
if w is None: if w is None:
continue continue
mapped_tx.append(mapped)
events.append({"event": t.get("event", "wmbus_tx"), events.append({"event": t.get("event", "wmbus_tx"),
"result": t.get("result"), "result": t.get("result"),
"window_db": round(w, 1), "window_db": round(w, 1),
"rf": bool(w >= 6)}) "above_6db": bool(w >= 6)})
meter_med = float(np.median(meter_lv)) if meter_lv else 0.0 meter_med = float(np.median(meter_lv)) if meter_lv else 0.0
observer = "ok" if meter_med >= 15 else ("degraded" if meter_med >= 8 else "deaf") observer = "ok" if meter_med >= 15 else ("degraded" if meter_med >= 8 else "deaf")
n_rf = sum(1 for e in events if e["rf"]) n_above = sum(1 for e in events if e["above_6db"])
levels = [e["window_db"] for e in events]
tx_med = float(np.median(levels)) if levels else None
controls = [winmax(t + 100) for t in mapped_tx]
controls = [v for v in controls if v is not None]
control_med = float(np.median(controls)) if controls else None
fsk_db, fsk_windows = fsk_spectral_excess(
args.iq, db, floor, mapped_tx)
if not events:
rf_state = "no_events"
elif fsk_db is not None and fsk_db >= 3.0:
rf_state = "strong" if tx_med >= 6.0 else "weak"
else:
rf_state = "not_observed"
report = { report = {
"clock_matched": f"{matched}/{len(strong)}", "clock_matched": f"{matched}/{len(strong)}",
"clock_err_ms": round(err, 1), "clock_err_ms": round(err, 1),
@@ -132,23 +216,31 @@ def main():
"meter_median_db": round(meter_med, 1), "meter_median_db": round(meter_med, 1),
"observer": observer, "observer": observer,
"tx_events": len(events), "tx_events": len(events),
"tx_with_rf": n_rf, "tx_above_6db": n_above,
"tx_levels_db": [e["window_db"] for e in events], "tx_median_db": round(tx_med, 1) if tx_med is not None else None,
"control_median_db": (round(control_med, 1)
if control_med is not None else None),
"fsk_excess_db": round(fsk_db, 1) if fsk_db is not None else None,
"fsk_windows": fsk_windows,
"rf_state": rf_state,
"tx_levels_db": levels,
} }
if args.json: if args.json:
print(json.dumps(report, indent=2)) print(json.dumps(report))
else: else:
print(f"clock: {report['clock_matched']} anchors, err {report['clock_err_ms']} ms") print(f"clock: {report['clock_matched']} anchors, err {report['clock_err_ms']} ms")
print(f"observer: {observer} (meter median +{report['meter_median_db']} dB, " print(f"observer: {observer} (meter median +{report['meter_median_db']} dB, "
f"floor {report['floor_db']})") f"floor {report['floor_db']})")
print(f"TX with RF: {n_rf}/{len(events)}") print(f"TX state: {rf_state}; median +{report['tx_median_db']} dB, "
f"FSK excess {report['fsk_excess_db']} dB")
for e in events: for e in events:
print(f" {e['event']:>9} {e['result'] or '':>10} " print(f" {e['event']:>9} {e['result'] or '':>10} "
f"+{e['window_db']:>5.1f} dB {'RF' if e['rf'] else '--'}") f"+{e['window_db']:>5.1f} dB "
# exit 3 = observer unusable, 1 = TX dead while observer ok f"{'>=6dB' if e['above_6db'] else 'weak'}")
# exit 3 = observer unusable, 1 = no event-correlated FSK while observer ok
if observer == "deaf": if observer == "deaf":
sys.exit(3) sys.exit(3)
sys.exit(0 if (n_rf or not events) else 1) sys.exit(0 if rf_state in ("strong", "weak", "no_events") else 1)
if __name__ == "__main__": if __name__ == "__main__":
+23 -21
View File
@@ -20,7 +20,7 @@ ap.add_argument("--tx-power", default="?")
ap.add_argument("--repeat-delay", default="?") ap.add_argument("--repeat-delay", default="?")
ap.add_argument("--sdr-streamed", default="?") ap.add_argument("--sdr-streamed", default="?")
ap.add_argument("--tx-proof", default=None) ap.add_argument("--tx-proof", default=None)
ap.add_argument("--iq-proof", default=None) ap.add_argument("--rf-proof", default=None)
ap.add_argument("--sdr-sensitivity", default="?") ap.add_argument("--sdr-sensitivity", default="?")
args = ap.parse_args() args = ap.parse_args()
@@ -38,7 +38,7 @@ def load_json(path):
proof = load_json(args.tx_proof) proof = load_json(args.tx_proof)
iqp = load_json(args.iq_proof) rfp = load_json(args.rf_proof)
def fmt(v, unit=""): def fmt(v, unit=""):
@@ -63,11 +63,13 @@ if fw.get("boots", 0) > 1:
if proof is not None and proof.get("bursts_with_sdr_decode", 0) == 0: if proof is not None and proof.get("bursts_with_sdr_decode", 0) == 0:
fail.append("SDR could not decode any Heltec C1 transmission") fail.append("SDR could not decode any Heltec C1 transmission")
# A decoded repeat is preferred, but a decode-independent RF observation of # Decoded H=0 -> H=1 transitions are preferred. Meter-anchored, spectrally
# a repeat at the configured delay also satisfies "the observer # classified FSK at firmware repeat times is an independent RF proof when
# independently saw the retransmission" (see docs/RF_FRONTEND_TESTS.md for # the nearby transmission overloads the decoder.
# why decoding our own TX is bench-limited). rf_confirmed = (rfp is not None
if iqp is not None and iqp.get("tx_events_with_rf", 0) > 0: and rfp.get("rf_state") in ("strong", "weak")
and rfp.get("tx_events", 0) >= args.min_repeats)
if rf_confirmed:
fail = [f for f in fail if not f.startswith("SDR-verified repeats")] fail = [f for f in fail if not f.startswith("SDR-verified repeats")]
verdict = "PASS" if not fail else "FAIL" verdict = "PASS" if not fail else "FAIL"
@@ -99,25 +101,25 @@ TX DECODABILITY PROOF (synthetic C1, independent of meters):
SDR decoded as C1: {proof.get('bursts_with_sdr_decode')} SDR decoded as C1: {proof.get('bursts_with_sdr_decode')}
both airings decoded: {proof.get('bursts_with_both_airings_decoded')}""") both airings decoded: {proof.get('bursts_with_both_airings_decoded')}""")
if iqp is not None: if rfp is not None:
print(f""" print(f"""
RF-LEVEL TX PROOF (same stream's raw IQ, decode-independent): RF-LEVEL TX PROOF (meter-anchored IQ + non-TX controls):
IQ analysed: {iqp.get('iq_seconds')} s clock anchors: {rfp.get('clock_matched')}
clipped samples: {iqp.get('clipped_sample_pct')} % clock median error: {rfp.get('clock_err_ms')} ms
bursts in window: {iqp.get('bursts_total')} observer state: {rfp.get('observer')}
firmware TX ok: {iqp.get('firmware_tx_ok')} meter level over floor: {rfp.get('meter_median_db')} dB
TX events in IQ window: {iqp.get('tx_events_in_iq_window')} firmware TX events: {rfp.get('tx_events')}
TX events with RF: {iqp.get('tx_events_with_rf')} ({iqp.get('tx_rf_confirmed_pct')} %) RF state: {rfp.get('rf_state')}
alignment error: {iqp.get('align_error_ms')} ms TX median over floor: {rfp.get('tx_median_db')} dB
airtime error: {iqp.get('burst_duration_error_ms')} ms control median: {rfp.get('control_median_db')} dB
our TX over floor: {iqp.get('our_tx_peak_db_over_floor')} dB FSK-selective excess: {rfp.get('fsk_excess_db')} dB
meter bursts over floor: {iqp.get('other_burst_peak_db_over_floor')} dB spectral windows: {rfp.get('fsk_windows')}""")
firmware repeat delay: {iqp.get('firmware_repeat_delay_ms')} ms""")
print(f""" print(f"""
SDR (independent observer): SDR (independent observer):
decode lines: {r.get('sdr_frames_total')} decode lines: {r.get('sdr_frames_total')}
C1 CRC-ok bursts: {r.get('sdr_c1_crc_ok')} C1 CRC-ok bursts: {r.get('sdr_c1_crc_ok')}
T1 CRC-ok bursts: {r.get('sdr_t1_crc_ok', 0)}
classified originals: {r.get('sdr_originals')} classified originals: {r.get('sdr_originals')}
classified repeats: {r.get('sdr_repeats')} classified repeats: {r.get('sdr_repeats')}
unique meters: {len(r.get('per_meter') or {})} unique meters: {len(r.get('per_meter') or {})}
@@ -133,7 +135,7 @@ HELTEC TX:
reported success: {r.get('heltec_tx_ok')} reported success: {r.get('heltec_tx_ok')}
SDR-VERIFIED REPEATS: SDR-VERIFIED REPEATS:
byte-identical pairs: {r.get('sdr_repeats')} H=0 -> H=1 pairs: {r.get('sdr_repeats')}
fully correlated: {r.get('fully_correlated_repeats')} fully correlated: {r.get('fully_correlated_repeats')}
vs TX attempts: {fmt(r.get('repeat_success_rate_pct'), ' %')} vs TX attempts: {fmt(r.get('repeat_success_rate_pct'), ' %')}
+23 -10
View File
@@ -37,6 +37,11 @@ while [ $# -gt 0 ]; do
esac esac
done done
if ! [[ "$TXPOW" =~ ^-?[0-9]+$ ]] || (( TXPOW < -9 || TXPOW > 2 )); then
echo "--tx-power must be an integer in -9..2" >&2
exit 2
fi
PY=./result-py/bin/python3 PY=./result-py/bin/python3
[ -x "$PY" ] || { echo "run 'nix build .#hil-python -o result-py' first" >&2; exit 2; } [ -x "$PY" ] || { echo "run 'nix build .#hil-python -o result-py' first" >&2; exit 2; }
@@ -154,21 +159,29 @@ cat "$RUN_DIR/final_stats.log" >> "$RUN_DIR/serial.log"
# --- RF-level repeat proof from the same stream's IQ ---------------------- # --- RF-level repeat proof from the same stream's IQ ----------------------
if [ -s "$IQ" ]; then if [ -s "$IQ" ]; then
echo "RF-level repeat proof from captured IQ" echo "RF-level repeat proof from meter-anchored IQ"
$PY hil/verify_repeats_iq.py --iq "$IQ" --serial "$RUN_DIR/serial.log" \ RF_RC=0
--delay-ms "$DELAY" > "$RUN_DIR/iq_proof.txt" 2>&1 || true if ! $PY hil/meter_anchored.py --iq "$IQ" \
$PY hil/verify_repeats_iq.py --iq "$IQ" --serial "$RUN_DIR/serial.log" \ --serial "$RUN_DIR/serial.log" --json \
--delay-ms "$DELAY" --json > "$RUN_DIR/iq_proof.json" 2>&1 || true > "$RUN_DIR/rf_proof.json" 2> "$RUN_DIR/rf_proof.err"; then
cat "$RUN_DIR/iq_proof.txt" RF_RC=$?
# IQ is large: keep it only when the proof failed, for offline inspection fi
if grep -q '"tx_events_with_rf": [1-9]' "$RUN_DIR/iq_proof.json" 2>/dev/null; then if [ -s "$RUN_DIR/rf_proof.json" ]; then
cat "$RUN_DIR/rf_proof.json"
else
cat "$RUN_DIR/rf_proof.err"
fi
# Preserve weak, absent and unclassifiable RF for offline audit.
if [ "$RF_RC" = "0" ] \
&& grep -q '"rf_state": "strong"' "$RUN_DIR/rf_proof.json" 2>/dev/null; then
rm -f "$IQ" rm -f "$IQ"
fi fi
fi fi
# --- 13-14. correlate ------------------------------------------------------ # --- 13-14. correlate ------------------------------------------------------
MAXDELAY=$(awk "BEGIN{printf \"%.3f\", ($DELAY + 200) / 1000}")
$PY hil/correlate.py --serial "$RUN_DIR/serial.log" --sdr "$RUN_DIR/rtlwmbus.log" \ $PY hil/correlate.py --serial "$RUN_DIR/serial.log" --sdr "$RUN_DIR/rtlwmbus.log" \
--min-delay 0.010 --max-delay 0.400 > "$RUN_DIR/report.json" --min-delay 0.010 --max-delay "$MAXDELAY" > "$RUN_DIR/report.json"
# --- 15. lockup / reset detection ----------------------------------------- # --- 15. lockup / reset detection -----------------------------------------
HB=$(grep -c '"event":"heartbeat"' "$RUN_DIR/serial.log" || true) HB=$(grep -c '"event":"heartbeat"' "$RUN_DIR/serial.log" || true)
@@ -189,7 +202,7 @@ $PY hil/report.py "$RUN_DIR/report.json" \
--sdr-streamed "$STREAMED" \ --sdr-streamed "$STREAMED" \
--sdr-sensitivity "${SENS:-unknown}" \ --sdr-sensitivity "${SENS:-unknown}" \
--tx-proof "$RUN_DIR/tx_proof.json" \ --tx-proof "$RUN_DIR/tx_proof.json" \
--iq-proof "$RUN_DIR/iq_proof.json" \ --rf-proof "$RUN_DIR/rf_proof.json" \
| tee "$RUN_DIR/report.txt" | tee "$RUN_DIR/report.txt"
RC=${PIPESTATUS[0]} RC=${PIPESTATUS[0]}
echo "artifacts: $RUN_DIR" echo "artifacts: $RUN_DIR"
+2 -2
View File
@@ -69,8 +69,8 @@ if not tx:
print("TX: no repeat events recorded") print("TX: no repeat events recorded")
print(f" result breakdown: {dict(results)}") print(f" result breakdown: {dict(results)}")
print(f" repeat delay: {s(delays, ' ms')}") print(f" TX-routine delay: {s(delays, ' ms')}")
print(f" TX airtime: {s(air, ' ms')}") print(f" computed RF airtime: {s(air, ' ms')}")
print(f""" print(f"""
HEALTH: HEALTH:
radio recoveries: {len(rec)} radio recoveries: {len(rec)}
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bash
# Overnight segmented RF soak for a STANDALONE repeater (no serial link).
# Per segment: bounded rtl_sdr capture -> offline rtl_wmbus decode ->
# hil/verify_standalone.py verdict appended to soak.jsonl.
#
# Designed around the known observer faults (docs/HARDWARE.md): bounded
# segments, usbreset recovery on short captures, and a deaf-observer
# heuristic -- the neighbouring meter rails the dongle at a steady rate,
# so consecutive near-empty segments mean a dead receiver, not a quiet
# night. Disk is bounded: confirmed segments drop their IQ; only the two
# newest unconfirmed segments keep raw IQ for offline audit.
#
# Run via the devshell so usbreset is on PATH:
# nix develop --command ./hil/standalone_soak.sh 0855 300
#
# Usage: standalone_soak.sh [END_HHMM] [SEG_SECONDS] [DELAY_MS]
# standalone_soak.sh 0855 300 500
set -u
cd "$(dirname "$0")/.."
END_HHMM=${1:-0855}
SEG=${2:-300}
DELAY_MS=${3:-500} # must match the DUT's persisted repeat_delay_ms
PY=./result-py/bin/python3
WMBUS=./result-rtl-wmbus/bin/rtl_wmbus
[ -x "$PY" ] || { echo "run 'nix build .#hil-python -o result-py' first" >&2; exit 2; }
[ -x "$WMBUS" ] || { echo "missing result-rtl-wmbus" >&2; exit 2; }
OUT="captures/$(date +%Y-%m-%dT%H-%M-%S)-standalone-soak"
mkdir -p "$OUT"
END_EPOCH=$(date -d "$END_HHMM" +%s 2>/dev/null) || { echo "bad end time: $END_HHMM" >&2; exit 2; }
if [ "$END_EPOCH" -le "$(date +%s)" ]; then
END_EPOCH=$(date -d "tomorrow $END_HHMM" +%s)
fi
echo "soak until $(date -d "@$END_EPOCH" '+%F %T'), segment ${SEG}s -> $OUT"
command -v usbreset >/dev/null || echo "WARNING: usbreset not on PATH; dongle recovery disabled" >&2
low_bursts=0
short_caps=0
i=0
while [ $(( $(date +%s) + SEG )) -le "$END_EPOCH" ]; do
i=$((i + 1))
D="$OUT/seg$i"
mkdir -p "$D"
timeout $((SEG + 60)) rtl_sdr -f 868950000 -s 1600000 -g 42.1 \
-n $((SEG * 1600000)) "$D/iq.raw" 2> "$D/rtl_sdr.err"
SZ=$(stat -c %s "$D/iq.raw" 2>/dev/null || echo 0)
T=$(date +%s)
if [ "$SZ" -lt $((SEG * 3200000 * 8 / 10)) ]; then
echo "{\"seg\":$i,\"error\":\"short_capture\",\"bytes\":$SZ,\"t\":$T}" >> "$OUT/soak.jsonl"
rm -f "$D/iq.raw"
usbreset 0bda:2838 >/dev/null 2>&1
short_caps=$((short_caps + 1))
# A de-enumerated dongle (needs physical replug) is unrecoverable
# from software: back off instead of hammering, keep probing in
# case it re-appears.
if [ "$short_caps" -ge 5 ]; then sleep 300; else sleep 20; fi
continue
fi
short_caps=0
V=$($PY hil/verify_standalone.py --iq "$D/iq.raw" --delay-ms "$DELAY_MS" \
--decodes "$D/decodes.log" --json 2> "$D/verdict.err")
RC=$?
if [ -n "$V" ]; then
printf '%s\n' "$V" | $PY -c \
"import json,sys; d=json.load(sys.stdin); d['seg']=$i; d['rc']=$RC; d['t']=$T; print(json.dumps(d))" \
>> "$OUT/soak.jsonl"
else
echo "{\"seg\":$i,\"rc\":$RC,\"error\":\"no_verdict\",\"t\":$T}" >> "$OUT/soak.jsonl"
fi
if grep -q "lost at least" "$D/rtl_sdr.err" 2>/dev/null; then
echo "{\"seg\":$i,\"note\":\"sample_drops\",\"t\":$T}" >> "$OUT/soak.jsonl"
fi
B=$(printf '%s\n' "$V" | $PY -c \
"import json,sys; print(json.load(sys.stdin).get('bursts_total',0))" \
2>/dev/null || echo 0)
if [ "${B:-0}" -lt 3 ]; then low_bursts=$((low_bursts + 1)); else low_bursts=0; fi
if [ "$low_bursts" -ge 2 ]; then
echo "{\"seg\":$i,\"note\":\"observer_suspect_reset\",\"t\":$(date +%s)}" >> "$OUT/soak.jsonl"
usbreset 0bda:2838 >/dev/null 2>&1
low_bursts=0
fi
if printf '%s' "$V" | grep -q '"verdict": "confirmed"'; then
rm -f "$D/iq.raw"
fi
ls -1t "$OUT"/seg*/iq.raw 2>/dev/null | tail -n +3 | xargs -r rm -f
sleep 15
done
echo "soak complete: $OUT/soak.jsonl"
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""Verify standalone beacon TX from RF evidence alone (no serial log).
Use case: DUT on battery/wall power with no USB host, transmitting the
synthetic OMS beacon every N ms. Two independent lines of evidence from
one recorded IQ stream:
1. Content: rtl_wmbus decodes of the known beacon frame
(mfr 0x4D8E "SLN", ID 00000001). Decode timestamps are clustered into
airings (two demodulators emit 1-2 lines per airing).
2. Timing: short bursts in the IQ envelope forming a comb at the beacon
period. The effective period is fitted from the data, because the
firmware schedules the next beacon after the previous TX completes
(configured period + a few ms), and a beacon can be delayed by RX
activity.
Ambient (non-beacon) decodes and long bursts are reported as the observer
health control.
Usage:
verify_beacon_standalone.py --iq iq.raw --decodes decodes.log \
--period-ms 3000 [--rate 1600000] [--json]
Exit: 0 = beacon TX confirmed, 1 = not observed, 2 = insufficient data.
"""
import argparse
import json
import re
import sys
import numpy as np
BEACON_HEX = "448e4d010000000107" # C + mfr + ID + ver + type, L-agnostic
DECODE_RE = re.compile(
r"^(?P<mode>[TC]1);\d+;\d+;(?P<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+);"
r".*0x(?P<hex>[0-9a-fA-F]+)")
def parse_decodes(path):
# Distinct airings are counted by distinct payload: the beacon's
# access number increments per airing, so each airing has unique hex,
# while rtl_wmbus's two demodulators emitting 1-2 lines per airing
# collapse to one. Timestamp-independent, so it works for both live
# captures and offline `rtl_wmbus < iq.raw` (compressed wall clock).
# acc wraps at 256: valid for captures up to 256 beacon periods.
beacon_hex, beacon_lines, ambient = set(), 0, 0
for line in open(path, errors="replace"):
m = DECODE_RE.match(line.strip())
if not m:
continue
if BEACON_HEX in m.group("hex").lower():
beacon_hex.add(m.group("hex").lower())
beacon_lines += 1
else:
ambient += 1
return len(beacon_hex), beacon_lines, ambient
def envelope_bursts(path, rate):
win = rate // 1000 # 1 ms bins
env = []
with open(path, "rb") as f:
while True:
raw = f.read(rate * 2)
if len(raw) < win * 2:
break
u8 = np.frombuffer(raw, dtype=np.uint8)
b = u8.astype(np.float32) - 127.5
iq = b[0::2] + 1j * b[1::2]
p = np.abs(iq) ** 2
p = p[: (len(p) // win) * win].reshape(-1, win).mean(axis=1)
env.append(p)
if not env:
return None, 0.0, []
db = 10 * np.log10(np.concatenate(env) + 1e-9)
floor = float(np.median(db))
idx = np.where(db > floor + 6.0)[0]
bursts = []
if len(idx):
start = prev = idx[0]
for i in idx[1:]:
if i > prev + 3:
bursts.append((int(start), int(prev - start + 1),
float(db[start:prev + 1].max() - floor)))
start = i
prev = i
bursts.append((int(start), int(prev - start + 1),
float(db[start:prev + 1].max() - floor)))
return db, floor, bursts
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--iq", required=True)
ap.add_argument("--decodes")
ap.add_argument("--period-ms", type=float, required=True,
help="configured beacon_period_ms")
ap.add_argument("--rate", type=int, default=1_600_000)
ap.add_argument("--json", action="store_true")
args = ap.parse_args()
db, floor, bursts = envelope_bursts(args.iq, args.rate)
if db is None:
print("IQ empty or unreadable", file=sys.stderr)
sys.exit(2)
# Beacon candidates: short bursts (L=19 beacon airtime is 2.7 ms;
# envelope smearing widens that). Longer bursts are ambient meters.
cand = [b for b in bursts if b[1] <= 8]
long_bursts = [b for b in bursts if b[1] > 8]
# Fit the effective period from consecutive candidate intervals near
# the configured period, then count on-grid intervals (a missed or
# RX-delayed slot shows up as ~2x the period and is counted as a gap).
starts = np.array([b[0] for b in cand], dtype=float)
iv = np.diff(starts)
p = args.period_ms
near = iv[(iv > 0.8 * p) & (iv < 1.35 * p)]
fitted = float(np.median(near)) if len(near) else None
on_grid = int(len(near))
gaps = int(np.count_nonzero((iv > 1.6 * p) & (iv < 2.6 * p)))
cand_levels = [b[2] for b in cand]
airings, beacon_lines, ambient_decodes = 0, 0, 0
if args.decodes:
airings, beacon_lines, ambient_decodes = parse_decodes(args.decodes)
decode_ok = airings >= 5
comb_ok = on_grid >= 5 and fitted is not None
if decode_ok or comb_ok:
verdict = "confirmed"
rc = 0
elif len(cand) or airings:
verdict = "insufficient"
rc = 2
else:
verdict = "not_observed"
rc = 1
report = {
"iq_seconds": round(len(db) / 1000.0, 1),
"noise_floor_db": round(floor, 1),
"beacon_candidate_bursts": len(cand),
"candidate_median_db": (round(float(np.median(cand_levels)), 1)
if cand_levels else None),
"period_configured_ms": p,
"period_fitted_ms": round(fitted, 1) if fitted else None,
"intervals_on_grid": on_grid,
"missed_slot_gaps": gaps,
"beacon_decoded_airings": airings,
"beacon_decode_lines": beacon_lines,
"ambient_decodes": ambient_decodes,
"ambient_long_bursts": len(long_bursts),
"verdict": verdict,
}
if args.json:
print(json.dumps(report))
else:
print(f"IQ: {report['iq_seconds']} s, floor {report['noise_floor_db']} dB")
print(f"beacon bursts: {len(cand)} (median "
f"+{report['candidate_median_db']} dB), period fitted "
f"{report['period_fitted_ms']} ms vs configured {p:.0f} ms, "
f"{on_grid} intervals on grid, {gaps} missed-slot gaps")
print(f"decoded beacon airings: {airings} ({beacon_lines} lines); "
f"ambient decodes: {ambient_decodes}; "
f"ambient long bursts: {len(long_bursts)}")
print(f"VERDICT: {verdict}")
sys.exit(rc)
if __name__ == "__main__":
main()
-223
View File
@@ -1,223 +0,0 @@
#!/usr/bin/env python3
"""Verify repeater transmissions from raw IQ, independent of packet decoding.
Why this exists: on this bench the Heltec transmission arrives at the SDR
far stronger than real meter traffic, and the dongle's own sensitivity
drifts by ~17 dB over minutes. rtl-wmbus therefore often receives our
repeat with a couple of byte errors (CRC fails) even though the RF is
present and correctly timed. Burst-envelope analysis is immune to that.
Method: extract RF bursts from the IQ envelope, then find the single clock
offset between the firmware's monotonic microsecond timestamps and the IQ
timeline that maximises the number of firmware TX events landing on a
burst. No amplitude threshold is assumed for attribution -- the alignment
itself is the evidence, and a wrong alignment cannot match many events.
Reports:
- how many firmware TX events have corresponding RF in the IQ
- the measured original -> repeat spacing for repeats whose source RX
event is known, compared against the configured delay
- the received level of our transmissions vs meter traffic
Usage:
verify_repeats_iq.py --iq iq.raw --serial serial.log --delay-ms 200
[--rate 1600000] [--tol-ms 15] [--json]
"""
import argparse
import json
import sys
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument("--iq", required=True)
ap.add_argument("--serial", required=True)
ap.add_argument("--delay-ms", type=float, required=True)
ap.add_argument("--rate", type=int, default=1_600_000)
ap.add_argument("--tol-ms", type=float, default=15.0)
ap.add_argument("--json", action="store_true")
args = ap.parse_args()
WIN = args.rate // 1000 # 1 ms resolution
# ---------------------------------------------------------------- IQ bursts
def load_envelope(path):
env, clipped = [], 0
with open(path, "rb") as f:
while True:
raw = f.read(args.rate * 2)
if len(raw) < WIN * 2:
break
u8 = np.frombuffer(raw, dtype=np.uint8)
clipped += int(np.count_nonzero((u8 == 0) | (u8 == 255)))
b = u8.astype(np.float32) - 127.5
iq = b[0::2] + 1j * b[1::2]
p = np.abs(iq) ** 2
p = p[: (len(p) // WIN) * WIN].reshape(-1, WIN).mean(axis=1)
env.append(p)
if not env:
return None, 0
return np.concatenate(env), clipped
power, clipped_samples = load_envelope(args.iq)
if power is None:
msg = {"error": "iq too short"}
print(json.dumps(msg) if args.json else "ERROR: iq too short")
sys.exit(3)
db = 10 * np.log10(power + 1e-9)
floor = float(np.median(db))
idx = np.where(db > floor + 6.0)[0]
bursts = []
if len(idx):
start = prev = idx[0]
for i in idx[1:]:
if i > prev + 3:
bursts.append((start, prev))
start = i
prev = i
bursts.append((start, prev))
burst_start = np.array([s for s, _ in bursts], dtype=np.int64)
burst_info = [{
"t_ms": int(s),
"duration_ms": int(e - s + 1),
"peak_db": float(db[s:e + 1].max() - floor),
} for s, e in bursts]
# ------------------------------------------------------------ firmware log
tx_events, rx_events = [], []
for line in open(args.serial, errors="replace"):
line = line.strip()
if not line.startswith("{"):
continue
try:
ev = json.loads(line)
except json.JSONDecodeError:
continue
if ev.get("event") == "wmbus_tx" and str(ev.get("result", "")).startswith("ok"):
tx_events.append(ev)
elif ev.get("event") == "wmbus_rx" and ev.get("crc_ok"):
rx_events.append(ev)
if not tx_events or not bursts:
result = {
"iq_seconds": round(len(db) / 1000.0, 1),
"noise_floor_db": round(floor, 1),
"bursts_total": len(burst_info),
"firmware_tx_ok": len(tx_events),
"tx_events_with_rf": 0,
"note": "no TX events or no bursts in this window",
}
print(json.dumps(result, indent=2) if args.json
else f"IQ_REPEAT_PROOF: no TX events or no bursts "
f"(tx={len(tx_events)} bursts={len(burst_info)})")
sys.exit(1)
tx_ms = np.array([ev["timestamp_us"] / 1000.0 for ev in tx_events])
# ------------------------------------------------- align firmware to IQ
# Candidate offsets: every (burst - tx_event) difference. The true offset
# appears once per genuinely observed transmission, so it wins by count.
cands = np.subtract.outer(burst_start.astype(float), tx_ms).ravel()
best_off, best_hits = 0.0, -1
for off in cands:
d = np.abs(burst_start[:, None] - (tx_ms + off)[None, :])
hits = int(np.count_nonzero(d.min(axis=0) <= args.tol_ms))
if hits > best_hits:
best_hits, best_off = hits, float(off)
# Match each TX event to its nearest burst under the winning offset.
# The IQ may cover only part of the serial log (bounded IQ segments, or a
# tuner fault mid-run), so TX events whose aligned time falls outside the
# IQ timeline are "not observable" rather than "not observed" -- counting
# them as failures would understate the result.
iq_span_ms = len(db)
matched, our_peaks, in_window = [], [], 0
for ev, t in zip(tx_events, tx_ms):
target = t + best_off
if target < 0 or target > iq_span_ms:
continue
in_window += 1
if not len(burst_start):
continue
j = int(np.argmin(np.abs(burst_start - target)))
err = float(burst_start[j] - target)
if abs(err) <= args.tol_ms:
matched.append({
"hash": ev.get("hash"),
"frame_len": ev.get("length"),
"iq_t_ms": int(burst_start[j]),
"align_error_ms": round(err, 1),
"burst_duration_ms": burst_info[j]["duration_ms"],
"burst_peak_db": round(burst_info[j]["peak_db"], 1),
"delay_us": ev.get("delay_us"),
})
our_peaks.append(burst_info[j]["peak_db"])
ours_t = {m["iq_t_ms"] for m in matched}
other_peaks = [b["peak_db"] for b in burst_info if b["t_ms"] not in ours_t]
# expected airtime: (frame + 2 mode bytes) * 80 us + preamble/sync ~0.64 ms
def expected_ms(n):
return ((n + 2) * 80 + 640) / 1000.0 if n else None
dur_err = [m["burst_duration_ms"] - expected_ms(m["frame_len"])
for m in matched if m["frame_len"]]
delays = sorted(m["delay_us"] / 1000.0 for m in matched
if m.get("delay_us"))
def stat(v):
if not v:
return {"min": None, "median": None, "max": None}
v = sorted(v)
return {"min": round(v[0], 1),
"median": round(v[len(v) // 2], 1),
"max": round(v[-1], 1)}
result = {
"iq_seconds": round(len(db) / 1000.0, 1),
"noise_floor_db": round(floor, 1),
"clipped_sample_pct": round(100.0 * clipped_samples /
max(1, len(db) * WIN * 2), 4),
"bursts_total": len(burst_info),
"firmware_tx_ok": len(tx_events),
"firmware_rx_crc_ok": len(rx_events),
"tx_events_in_iq_window": in_window,
"tx_events_with_rf": len(matched),
"tx_rf_confirmed_pct": round(100.0 * len(matched) / in_window, 1) if in_window else None,
"clock_offset_ms": round(best_off, 1),
"align_error_ms": stat([abs(m["align_error_ms"]) for m in matched]),
"burst_duration_error_ms": stat(dur_err),
"our_tx_peak_db_over_floor": stat(our_peaks),
"other_burst_peak_db_over_floor": stat(other_peaks),
"firmware_repeat_delay_ms": stat(delays),
"expected_delay_ms": args.delay_ms,
"matched": matched[:50],
}
if args.json:
print(json.dumps(result, indent=2))
else:
print(f"IQ_REPEAT_PROOF iq={result['iq_seconds']}s floor={floor:.1f}dB "
f"clipped={result['clipped_sample_pct']}%")
print(f" bursts in window: {len(burst_info)}")
print(f" firmware TX ok / RX crc-ok: {len(tx_events)} / {len(rx_events)}")
print(f" TX events inside IQ window: {in_window} of {len(tx_events)}")
print(f" TX events with RF in IQ: {len(matched)}/{in_window} "
f"({result['tx_rf_confirmed_pct']} %)")
print(f" clock offset: {best_off:.0f} ms")
print(f" alignment error min/med/max: {result['align_error_ms']}")
print(f" duration error vs airtime: {result['burst_duration_error_ms']} ms")
print(f" our TX level over floor: {result['our_tx_peak_db_over_floor']} dB")
print(f" other bursts over floor: {result['other_burst_peak_db_over_floor']} dB")
print(f" firmware repeat delay: {result['firmware_repeat_delay_ms']} ms "
f"(configured {args.delay_ms:.0f})")
sys.exit(0 if matched else 1)
+33 -20
View File
@@ -8,18 +8,18 @@ SDR observes. This is also the honest test of "power it up and leave it be".
Two independent lines of evidence, both derived from ONE recorded IQ file so Two independent lines of evidence, both derived from ONE recorded IQ file so
they cannot disagree about gain or time: they cannot disagree about gain or time:
1. Decoded repeats - rtl_wmbus run over the recording; a repeat is the 1. Decoded repeats - a supported H=0 original followed by an H=1 frame
same cooked payload decoded twice within the delay window. with every other cooked byte unchanged.
2. RF-level repeats - burst-envelope pairs separated by the delay window 2. RF-level repeats - burst-envelope pairs separated by the delay window
where the second burst is at least as strong as the first. This catches where the second burst is at least as strong as the first. This catches
repeats that fail CRC because our transmission overloads the dongle repeats that fail CRC because our transmission overloads the dongle
(docs/RF_FRONTEND_TESTS.md), which is the common case on this bench. (docs/RF_FRONTEND_TESTS.md), which is the common case on this bench.
Usage: Usage:
verify_standalone.py --iq iq.raw --decodes decodes.log verify_standalone.py --iq iq.raw --decodes decodes.log [--delay-ms 500]
[--min-ms 20] [--max-ms 400] [--rate 1600000] [--json] [--delay-tol-ms 25] [--rate 1600000] [--json]
Exit 0 if at least one repeat was observed by either method. Exit 0 only if a decoded hop transition confirms repeater activity.
""" """
import argparse import argparse
import json import json
@@ -30,7 +30,7 @@ from datetime import datetime
import numpy as np import numpy as np
sys.path.insert(0, __file__.rsplit("/", 1)[0]) sys.path.insert(0, __file__.rsplit("/", 1)[0])
from correlate import SDR_RE # noqa: E402 from correlate import SDR_RE, expected_repeat # noqa: E402
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument("--iq", required=True) ap.add_argument("--iq", required=True)
@@ -57,23 +57,35 @@ for line in open(args.decodes, errors="replace"):
"crc_ok": m["crc"] == "1", "crc_ok": m["crc"] == "1",
"t": datetime.strptime(m["ts"].strip(), "%Y-%m-%d %H:%M:%S.%f").timestamp(), "t": datetime.strptime(m["ts"].strip(), "%Y-%m-%d %H:%M:%S.%f").timestamp(),
"serial": m["serial"].lower(), "serial": m["serial"].lower(),
"hex": m["hex"].lower(), "cooked": bytes.fromhex(m["hex"]),
}) })
rows.sort(key=lambda r: r["t"]) rows.sort(key=lambda r: r["t"])
c1 = [r for r in rows if r["mode"] == "C1" and r["crc_ok"]] decoded = [r for r in rows if r["mode"] in ("C1", "T1") and r["crc_ok"]]
# rtl_wmbus runs two demodulators; collapse identical bytes <5 ms apart # rtl_wmbus runs two demodulators; collapse identical bytes <5 ms apart
dedup = [] dedup = []
for r in c1: for r in decoded:
if dedup and dedup[-1]["hex"] == r["hex"] and r["t"] - dedup[-1]["t"] < 0.005: if (dedup and dedup[-1]["mode"] == r["mode"]
and dedup[-1]["cooked"] == r["cooked"]
and r["t"] - dedup[-1]["t"] < 0.005):
continue continue
dedup.append(r) dedup.append(r)
# A decoded repeat: identical payload seen twice. rtl_sdr delivers ~82 ms # rtl_sdr delivers ~82 ms buffers, so decode timestamps are quantised.
# buffers so decode timestamps are quantised; count occurrences rather than # Preserve order rather than trusting sub-100 ms timing (docs/FINDINGS.md).
# trusting sub-100 ms timing (docs/FINDINGS.md). # Each supported H=0 original permits one later H=1 counterpart; never
occ = Counter(r["hex"] for r in dedup) # normalize H on both sides or count identical originals as repeats.
decoded_repeats = sum(v - 1 for v in occ.values() if v > 1) pending = Counter()
decoded_repeats = 0
for r in dedup:
key = (r["mode"], r["cooked"])
if pending[key]:
pending[key] -= 1
decoded_repeats += 1
else:
marked = expected_repeat(r["cooked"])
if marked is not None:
pending[(r["mode"], marked)] += 1
meters = Counter(r["serial"] for r in dedup) meters = Counter(r["serial"] for r in dedup)
# ---------------------------------------------------------------- IQ bursts # ---------------------------------------------------------------- IQ bursts
@@ -123,7 +135,7 @@ binfo = [b for b in binfo_all
# RF-level repeat: a burst followed by a comparable-or-stronger burst of # RF-level repeat: a burst followed by a comparable-or-stronger burst of
# similar duration inside the delay window. Duration similarity matters -- # similar duration inside the delay window. Duration similarity matters --
# a repeat carries the same frame, so its airtime should match. # setting H leaves the frame length unchanged, so its airtime should match.
pairs = [] pairs = []
for i, a in enumerate(binfo): for i, a in enumerate(binfo):
a_end = a["t_ms"] + a["dur_ms"] a_end = a["t_ms"] + a["dur_ms"]
@@ -131,7 +143,7 @@ for i, a in enumerate(binfo):
gap = b["t_ms"] - a_end gap = b["t_ms"] - a_end
if gap > args.delay_ms + args.delay_tol_ms: if gap > args.delay_ms + args.delay_tol_ms:
break break
# A repeat re-sends the SAME frame, so it must (a) sit at the # A hop-marked repeat retains the frame length, so it must (a) sit at the
# configured delay, (b) have an airtime consistent with a C1 frame, # configured delay, (b) have an airtime consistent with a C1 frame,
# and (c) match the original's duration closely. Pairs that merely # and (c) match the original's duration closely. Pairs that merely
# fall in a wide window are usually unrelated 868 MHz traffic -- # fall in a wide window are usually unrelated 868 MHz traffic --
@@ -153,7 +165,8 @@ result = {
"noise_floor_db": round(floor, 1), "noise_floor_db": round(floor, 1),
"bursts_total": len(binfo_all), "bursts_total": len(binfo_all),
"frame_like_bursts": len(binfo), "frame_like_bursts": len(binfo),
"c1_decodes": len(dedup), "c1_decodes": sum(r["mode"] == "C1" for r in dedup),
"t1_decodes": sum(r["mode"] == "T1" for r in dedup),
"unique_meters": len(meters), "unique_meters": len(meters),
"decoded_repeats": decoded_repeats, "decoded_repeats": decoded_repeats,
"rf_repeat_pairs": len(pairs), "rf_repeat_pairs": len(pairs),
@@ -176,7 +189,7 @@ if args.json:
print(json.dumps(result, indent=2)) print(json.dumps(result, indent=2))
else: else:
print(f"STANDALONE CHECK iq={result['iq_seconds']}s floor={floor:.1f}dB") print(f"STANDALONE CHECK iq={result['iq_seconds']}s floor={floor:.1f}dB")
print(f" C1 telegrams decoded: {len(dedup)} from {len(meters)} meters") print(f" C1/T1 telegrams decoded: {len(dedup)} from {len(meters)} meters")
print(f" RF bursts (all): {len(binfo_all)}") print(f" RF bursts (all): {len(binfo_all)}")
print(f" frame-like bursts: {len(binfo)} (>= {MIN_FRAME_MS} ms, >= +{MIN_FRAME_DB:.0f} dB)") print(f" frame-like bursts: {len(binfo)} (>= {MIN_FRAME_MS} ms, >= +{MIN_FRAME_DB:.0f} dB)")
print(f" decoded repeats: {decoded_repeats}") print(f" decoded repeats: {decoded_repeats}")
@@ -196,7 +209,7 @@ else:
print(" looks like a singleton. Read the firmware counters over USB") print(" looks like a singleton. Read the firmware counters over USB")
print(" for an unambiguous answer.)") print(" for an unambiguous answer.)")
elif v == "not observed": elif v == "not observed":
print(" (No frame-like burst pairs and no decoded duplicates. Either") print(" (No frame-like burst pairs and no decoded hop transitions. Either")
print(" the device is not transmitting, or it transmitted nothing in") print(" the device is not transmitting, or it transmitted nothing in")
print(" this window. Firmware counters over USB are decisive.)") print(" this window. Firmware counters over USB are decisive.)")
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,95 @@
# RS-15-5 + Heltec WiFi LoRa 32 V4 enclosure
Printable mechanical prototype, revision 3 — 16 September 2026.
Units: millimetres. Case body: **122 × 116 × 51 mm**; overall envelope with mounting flanges: **122 × 152 × 51 mm**, excluding screw heads, feet, cable gland and antenna. Designed for the **Mean Well RS-15-5** and **Heltec WiFi LoRa 32 V4.3.1**. Other V4 revisions need a fit check.
## What to print
| File | Quantity | Purpose |
|---|---:|---|
| base.stl | 1 | Housing with bottom mounting flanges, PSU pads, divider and carrier supports |
| board_carrier.stl | 1 | Removable Heltec mount; print this first to check board fit |
| lid_solid.stl | 1 | Default ventilated lid, without a display opening |
| lid_window.stl | Alternative | Ventilated lid with a display opening and underside pane recess |
| M16_thread_test.stl | 1 first | Small horizontal-thread fit coupon for the actual LAPP gland |
Choose one lid. Print the M16 thread coupon before committing to the base. STL parts are already oriented for printing. The base sits on its floor, the carrier on its underside, and each lid on its exterior face. The lid's registration tabs face upwards in the print files. Ask the slicer to place all parts on the build plate; do not scale them. Required bed area for each large part is at least 132 × 162 mm including a 5 mm brim allowance.
`housing_assembly.step` is an assembly of the base, carrier and solid lid in their installed positions. Open it in FreeCAD using File → Open. Separate STEP files are also included, including the windowed lid. These are editable solid models, not a FreeCAD feature-history tree. `build_enclosure.py` is the parameterized CadQuery source; changing its parameters and running it regenerates all parts. Requires Python and CadQuery (generated with the installed CadQuery runtime).
## Construction
- 3 mm walls, floor and lid; 5 mm outside corner radius.
- PSU metal body at X=46, Y=13, Z=8. Its 62.5 × 51 × 28 mm body has a separate allowance for the **up to 13 mm terminal projection**.
- PSU bottom mounting holes at (54.75, 38.25) and (93.85, 38.25), with 3.6 mm clearance holes and 5 mm-high floor pads.
- Full-height, 3 mm-thick divider at Y=72…75. The 8 mm DC-wire passage needs an appropriate insulating grommet. It is a wiring separator, not certified reinforced insulation.
- Heltec PCB lower face at Z=35, with 13 mm clearance above the carrier plate for underside components and header pins. The screen is near the lid, in its own compartment.
- Heltec mount-hole centres: (28.879, 88.7), (57.879, 88.7), (28.879, 102.7), (57.879, 102.7). Pitch is 29 × 14 mm. Carrier passages are 2.1 mm diameter with 3.5 mm AF nut recesses underneath.
- **M16 × 1.5 right-hand internal thread** on the left wall, in an integral 24 mm-diameter boss. Total threaded wall depth is 6 mm, with the extra 3 mm extending inward. This is designed for the LAPP 53111810 gland and replaces the previous smooth 16.2 mm opening. The actual gland provides cable retention; its mounting thread screws into the printed case.
- 6.5 mm SMA bulkhead opening on the opposite wall, in the Heltec compartment. Verify the connector shank diameter, thread length and nut clearance; use an IPEX-to-SMA pigtail appropriate to your board.
- USB opening about 15.4 × 10 mm. The USB receptacle is recessed about 11 mm from the outer wall. A narrow plug overmould must pass through the opening. Check your cable before printing; enlarge the source opening if necessary.
- Small vent slots on the PSU side wall and lid; no lid vents above the terminal bank. Keep them unobstructed. No waterproofing or IP rating is claimed.
## Bottom mounting flanges (revision 2)
Two integral flanges extend 18 mm beyond the Y ends of the case. Each is 4.5 mm thick with rounded corners, a central keyhole, and two Ø4.5 mm clearance holes for M4 or similar screws. They print flat with the base and need no additional supports. The overall footprint is now 122 × 152 mm; the lid and internal layout retain their original dimensions.
| Feature | Hole centres (X, Y), mm |
|---|---|
| Four round mounting holes | (16, -9), (106, -9), (16, 125), (106, 125) |
| Keyhole head entries, Ø9 mm | (61, -10), (61, 124) |
| Keyhole seated positions, Ø4.5 mm | (61, -4.5), (61, 129.5) |
The four round holes form a **90 × 134 mm** rectangle. Both keyholes have a 5.5 mm travel toward +Y. For hanging, orient +Y upward (the Heltec compartment above the PSU compartment): engage the heads in the larger openings, lower the enclosure 5.5 mm, then tighten and secure it with at least one round-hole fastener to prevent lifting off. Use pan/button-head screws whose heads pass through the Ø9 mm entry but retain securely over the 4.5 mm neck; check actual head size. The flanges are not countersunk.
**Mounting clearance:** the PSU screws project below the case floor. Use rigid stand-offs/spacers at every mounting fastener, typically at least 3 mm and always greater than the measured screw-head projection, so the enclosure does not rock on those heads. Use washers at the round holes and tighten gently. Select fasteners/anchors for the wall or support material. Printed flange strength and pull-out resistance have not been physically tested.
## Threaded mains entry (revision 3)
The left-wall opening now has a modeled **M16 × 1.5, right-hand, single-start, 60-degree internal thread**, not merely a cosmetic thread annotation. It is present in both the STL and STEP files. An inward boss increases the wall locally from 3 to **6 mm** (four pitches of total depth, with partial threads at the lead-in and exit). Its outside diameter is 24 mm. A 0.75 mm entry chamfer helps the gland start squarely; a 0.5 mm exit chamfer relieves the inner edge. The exterior wall remains flat for the gland shoulder/sealing washer.
The profile includes **0.20 mm radial print clearance** (0.40 mm on diameter). This is a starting tolerance, not a verified thread-fit class. It can be adjusted through `THREAD_RADIAL_CLEARANCE` in `build_enclosure.py`. The nominal mating gland remains M16 × 1.5. Based on LAPP's listed 8 mm mounting-thread length, about 2 mm of that thread can extend past a 6 mm wall before allowance for a sealing washer. No separate locknut is intended for this revision.
Print **M16_thread_test.stl** first using the same material, layer height and settings as the case. The coupon holds the bore horizontally, matching the case's print orientation. Its foot should lie flat on the bed. Try approximately 0.15 mm layers, at least four perimeters, and inspect the top of the bore for sagging or support residue. Do not force the gland into an undersized or rough thread. It should start by hand and seat without cross-threading. If fit is too tight or loose, change the radial clearance and regenerate both parts. Scaling the whole case is not a thread-fit adjustment.
The gland mounts from the outside. Use its appropriate sealing washer if required, and seat the shoulder gently. The finished printed thread's tightening strength, pull-out resistance and long-term creep are **not validated**, so no mounting torque is specified. Check secure cable retention in the finished assembly before powered use; the gland's factory ratings do not establish those of the printed mounting thread or enclosure. Electrical-safety limitations in this document still apply.
Manufacturer identification: [LAPP SKINTOP BS-M product table, article 53111810](https://products.lappgroup.com/online-catalogue/cable-glands/skintop-cable-glands-plastic-metric/bending-protection/skintop-bs-m.html).
## Hardware and assembly
1. Print the **carrier first** and check all four holes against your particular board. With power disconnected, check how the original screen cover and its screws are retained. The model uses the four display-mount positions; it is not a snap-in cradle.
2. If those positions can accept through-fasteners without damaging the screen assembly, use **four M1.6 screws and nuts**, with the nuts in the carrier's underside recesses. Approximately 22 mm screw length is a starting point for a through-stack, not a confirmed OEM screw specification. Measure the actual grip length, head clearance and thread engagement. Do not force a screw into the board or drill the PCB. If your factory cover has incompatible blind posts or fasteners, adjust the carrier/fastening method before use.
3. Secure the carrier to the two base pedestals using **two M3 × 10 screws**. Secure the lid using **four M3 × 10 screws**. The 2.7 mm pilots are for careful hand tapping or suitable plastic-thread-forming screws; check thread fit and avoid overtightening. No heat-set inserts are required by this version.
4. Attach the PSU using **two M3 × 10 screws from below**, with approximately 0.5 mm-thick washers. The floor-plus-pad grip is 8 mm, giving about 1.5 mm nominal engagement. **Measure the actual protrusion: the PSU's bottom holes allow at most 3 mm insertion.** Adjust washers/length for printed dimensions. The side-mount holes are not used.
5. Add four adhesive feet taller than the underside screw heads (typically at least 3 mm); these are not printed into the base, so its floor prints flat.
6. Test and fit the threaded cable gland as described below, then the DC-passage grommet and SMA bulkhead. Cable-tie anchors are included for organizing wires; they do not replace the mains cable gland.
7. If using the windowed lid, fit a **30 × 22 × 1 mm clear polycarbonate pane**, with corners rounded about R1.5 to suit the recess. Retain it with a compatible adhesive around the perimeter. Do not leave the opening uncovered. Check display alignment before bonding.
### Mains-power and material limits
This is a **mechanical prototype, not a certified electrical enclosure**. The RS-15-5 has exposed mains terminals and requires protective-earth bonding to its FG terminal. Have the final wiring, strain relief, earth connection, touch protection, insulation and thermal behaviour checked by someone qualified before powered operation. Disconnect mains before removing the lid. The divider and small vents do not establish an electrical safety or IP rating.
Use a suitably rated flame-retardant, heat-resistant material/process for any proposed mains installation, and validate the finished print. Material marketing or a filament rating alone does not certify an FDM enclosure. PLA/PETG prototypes are useful for an **unpowered fit check**; this design does not validate them for unattended mains service. At 15 W output and the datasheet's nominal 77% efficiency, the PSU dissipates roughly 4.5 W internally; ventilation area alone does not prove an acceptable temperature.
For a fit prototype: 0.4 mm nozzle, 0.2 mm layers, 4 perimeters, 5 top/bottom layers and approximately 30% infill. Enable localized supports for the side cable-gland/SMA/USB openings if your printer needs them. The base contains short bridges at cable-tie anchors; inspect those passages. Clear the holes carefully and remove all debris before installing electronics.
The Heltec documentation states that USB and the 5 V input must not be supplied simultaneously. Isolate the PSU's low-voltage feed before connecting a powered programming USB cable. This enclosure does not add power switching or isolation circuitry. Do not feed 5 V into the battery connector.
## Validation and remaining fit checks
- All five printable CAD bodies pass OpenCascade validity checks and each contains one solid.
- Exact solid-intersection checks cover the installed printed parts, the nominal PSU body/terminal envelopes, and simplified board/screen envelopes. Results are included in `validation.json`.
- `board_cad_check.json` records the separate comparison against the manufacturer's V4.3.1 STEP geometry. That manufacturer model does not include a complete screen/cover assembly; the screen is represented by a simplified envelope in the preview and initial checks.
- `mesh_validation.json` records watertight-edge and positive-volume checks on the exported STLs.
- No physical print, screw engagement, cable insertion, heat test, material validation, electrical safety test or RF test has been performed. Printed thread fit/retention, SMA pigtail, screen-cover fasteners and the clear pane are hardware-dependent.
- **Source discrepancy:** the Heltec drawing labels mounting holes Ø1.90 mm, while the supplied STEP model's PCB holes measure approximately Ø2.80 mm. Hole pitch agrees at 29 × 14 mm. The carrier uses 2.1 mm passages for M1.6 fasteners, but the actual board/cover hardware must be checked.
## Manufacturer references
- Mean Well RS-15 datasheet, mechanical drawing on page 2: https://www.meanwell.com/upload/pdf/RS-15/RS-15-SPEC.pdf
- Heltec WiFi LoRa 32 V4.3.1 datasheet, dimensions on page 15: https://resource.heltec.cn/download/WiFi_LoRa_32_V4/datasheet/WiFi_LoRa_32_V4.3.1_Datasheet.pdf
- Heltec official 3D model directory: https://resource.heltec.cn/download/WiFi_LoRa_32_V4/3D
- STEP used for internal checks: HTIT-WB32LAF_V4.3.1(1).step. Manufacturer files are not redistributed in this package.
`preview.png` shows the housing with simplified component envelopes; the PSU, board, display, screws and purchased hardware are not printable parts. Auxiliary BREP caches are omitted from the download; the build script regenerates them.
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -0,0 +1,5 @@
{
"base": [],
"board_carrier": [],
"lid_solid": []
}
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -0,0 +1,168 @@
"""RS-15-5 + Heltec WiFi LoRa 32 V4.3.1 enclosure, units mm.
Requires CadQuery 2.6+. Run: python build_enclosure.py
Source dimensions and assembly limitations are in README.md.
"""
from pathlib import Path
import cadquery as cq
import json
from math import sqrt
OUT=Path(__file__).resolve().parent
L,W,H=122.,116.,48.
WALL=3.; FLOOR=3.; LID=3.
FLANGE_EXTENSION=18.; FLANGE_THICKNESS=4.5
MOUNT_HOLE_D=4.5; KEYHOLE_HEAD_D=9.; KEYHOLE_TRAVEL=5.5
GLAND_PITCH=1.5; GLAND_DIAMETER=16.; GLAND_DEPTH=6.
# Radial FDM clearance: 0.20 mm = 0.40 mm on diameter. Test before full print.
THREAD_RADIAL_CLEARANCE=0.20
PSU_X,PSU_Y,PSU_Z=46.,13.,8.
BOARD_X,BOARD_Y,BOARD_BOTTOM=12.,83.,35.
# Hole coordinates relative to PCB left edge / lower edge.
BOARD_HOLES=[(16.879,5.7),(45.879,5.7),(16.879,19.7),(45.879,19.7)]
LID_HOLES=[(6,6),(116,6),(6,110),(116,110)]
CARRIER_HOLES=[(15,80),(65,109)]
def box(x,y,z,dx,dy,dz):
return cq.Workplane('XY').box(dx,dy,dz,centered=False).translate((x,y,z))
def cyl(x,y,z,d,h):
return cq.Workplane('XY').circle(d/2).extrude(h).translate((x,y,z))
def rr(x,y,z,dx,dy,dz,r):
return box(x,y,z,dx,dy,dz).edges('|Z').fillet(r)
def xhole(x,y,z,d,length):
return cq.Workplane('YZ').circle(d/2).extrude(length).translate((x,y,z))
def yhole(x,y,z,d,length):
return cq.Workplane('XZ').circle(d/2).extrude(-length).translate((x,y,z))
def hexcut(x,y,z,af,h):
return cq.Workplane('XY').polygon(6,af/0.8660254038).extrude(h).translate((x,y,z))
def gland_thread_tool():
# Right-handed, single-start 60-degree metric internal thread, with flat roots.
pitch=GLAND_PITCH
major=GLAND_DIAMETER/2+THREAD_RADIAL_CLEARANCE
minor=major-5*sqrt(3)*pitch/16
overlap=.05
profile=cq.Workplane('XZ').polyline([
(minor-overlap,-3*pitch/8-overlap/sqrt(3)),
(major,-pitch/16),(major,pitch/16),
(minor-overlap,3*pitch/8+overlap/sqrt(3))]).close()
path=cq.Wire.makeHelix(pitch,GLAND_DEPTH+2*pitch,minor)
groove=profile.sweep(path,isFrenet=True).translate((0,0,-pitch))
cutter=cyl(0,0,-pitch,2*minor,GLAND_DEPTH+2*pitch).union(groove)
cutter=cutter.union(cq.Workplane(obj=cq.Solid.makeCone(major+.2,minor,.75)))
cutter=cutter.union(cq.Workplane(obj=cq.Solid.makeCone(minor,major+.1,.5)).translate((0,0,GLAND_DEPTH-.5)))
return cutter.rotate((0,0,0),(0,1,0),90)
thread_tool=gland_thread_tool()
# Main shell and full-height wiring divider.
base=rr(0,0,0,L,W,H,5).cut(rr(3,3,3,L-6,W-6,H,2))
base=base.union(box(3,72,3,L-6,3,H-3))
# Integral bottom flanges, coplanar with the floor for flat printing.
# Both keyhole necks point +Y: orient +Y upward for gravity-assisted hanging.
for flange_y,hole_y,entry_y in [(-FLANGE_EXTENSION,-9.,-10.),(W-3,W+9.,W+8.)]:
flange=rr(0,flange_y,0,L,FLANGE_EXTENSION+3,FLANGE_THICKNESS,5)
for x in [16.,L-16.]:
flange=flange.cut(cyl(x,hole_y,-1,MOUNT_HOLE_D,FLANGE_THICKNESS+2))
slot=cyl(L/2,entry_y,-1,KEYHOLE_HEAD_D,FLANGE_THICKNESS+2)
slot=slot.union(box(L/2-MOUNT_HOLE_D/2,entry_y,-1,MOUNT_HOLE_D,KEYHOLE_TRAVEL,FLANGE_THICKNESS+2))
slot=slot.union(cyl(L/2,entry_y+KEYHOLE_TRAVEL,-1,MOUNT_HOLE_D,FLANGE_THICKNESS+2))
base=base.union(flange.cut(slot))
# Lid pilots: M3 plastic-tapping screw or carefully hand-tapped M3.
for x,y in LID_HOLES:
base=base.union(cyl(x,y,3,10,H-3))
base=base.cut(cyl(x,y,H-12,2.7,13))
# PSU underside holes: 39.1 pitch; max 3 mm screw intrusion.
psu_holes=[(PSU_X+8.75,PSU_Y+25.25),(PSU_X+47.85,PSU_Y+25.25)]
for x,y in psu_holes:
base=base.union(cyl(x,y,3,12,PSU_Z-3))
base=base.cut(cyl(x,y,-1,3.6,PSU_Z+2))
# Support pads prevent rocking; contact metal base only.
for x in [PSU_X+3,PSU_X+57]:
for y in [PSU_Y+3,PSU_Y+45]:
base=base.union(box(x,y,3,3,3,PSU_Z-3))
# Carrier pedestals.
for x,y in CARRIER_HOLES:
base=base.union(cyl(x,y,3,9,19))
base=base.cut(cyl(x,y,12,2.7,11))
# Integral 24 mm boss: 6 mm total threaded wall depth, extending inward.
base=base.union(xhole(0,49,22,24,GLAND_DEPTH))
base=base.cut(thread_tool.translate((0,49,22)))
# Matching fit coupon, with its thread horizontal as in the case print.
thread_coupon=box(0,-14,0,GLAND_DEPTH,28,30).union(box(0,-14,0,20,28,3))
thread_coupon=thread_coupon.cut(thread_tool.translate((0,0,16)))
# SMA bulkhead on opposite wall (low voltage bay).
base=base.cut(xhole(L-4,94,32,6.5,5))
# USB opening sized for plug overmould, not just metal connector. Support locally.
base=base.cut(rr(-1,88,33,5,15.4,10,1.5))
# DC passage takes a grommet with a nominal 8 mm panel cutout.
base=base.cut(yhole(109,71,18,8,5))
# Small vertical side vents, only opposite the terminal bank.
for y in range(17,65,6):
for z in [10,29]:
base=base.cut(box(L-4,y,z,5,2,12))
# Cable tie anchors are raised blocks with horizontal 5 x 2.5 passages.
for x,y in [(24,15),(109,66),(89,103)]:
anchor=box(x-4,y-3,3,8,6,5).cut(box(x-2.5,y-4,4.5,5,8,2.5))
base=base.union(anchor)
# Removable carrier, print plate flat with four small supports upright.
carrier=rr(12,77,22,60,36,3,2)
for x,y in CARRIER_HOLES:
carrier=carrier.cut(cyl(x,y,21,3.4,5))
for hx,hy in BOARD_HOLES:
x,y=BOARD_X+hx,BOARD_Y+hy
carrier=carrier.union(cyl(x,y,25,4.4,BOARD_BOTTOM-25))
carrier=carrier.cut(cyl(x,y,21,2.1,BOARD_BOTTOM-20))
# M1.6 nut recess open underneath, 3.5 mm AF / 1.5 mm deep.
carrier=carrier.cut(hexcut(x,y,21.9,3.5,1.6))
# Lid in assembled coordinates, simple face-down print orientation on export.
lid=rr(0,0,H,L,W,LID,5)
for x,y in LID_HOLES:
lid=lid.cut(cyl(x,y,H-1,3.4,5))
# Registration tabs avoid tall corner posts and the divider.
for x in [22,87]:
lid=lid.union(box(x,3.3,H-2,15,1.5,2.1))
lid=lid.union(box(x,W-4.8,H-2,15,1.5,2.1))
for y in [17,80]:
lid=lid.union(box(3.3,y,H-2,1.5,10,2.1))
lid=lid.union(box(L-4.8,y,H-2,1.5,10,2.1))
# Exhaust slots above the metal PSU body, no slots above its terminals.
for x in range(61,106,5):
for y in [20,43]:
lid=lid.cut(rr(x,y,H-1,2,16,5,0.8))
# Two lid options. Windowed version requires a separately fitted clear pane.
lid_window=lid.cut(rr(31,87,H-1,25,17,5,1.5))
# Recess on underside for a 30 x 22 x 1 mm clear polycarbonate pane.
lid_window=lid_window.cut(rr(28.5,84.5,H-.1,30,22,1.2,1.5))
# Models used ONLY for clearance checks/preview, never included in print STLs.
psu_ref=box(PSU_X,PSU_Y,PSU_Z,62.5,51,28)
terminal_ref=box(PSU_X-13,PSU_Y+2,PSU_Z+8,13,47,13)
board_ref=box(BOARD_X,BOARD_Y,BOARD_BOTTOM,51.7,25.4,1.56)
# PCB underside relief, header pins and screen approximations are explicitly illustrative.
screen_ref=box(BOARD_X+15,BOARD_Y+3.3,BOARD_BOTTOM+1.56,33,18.8,5.5)
parts={'base':base,'lid_solid':lid,'lid_window':lid_window,'board_carrier':carrier,'M16_thread_test':thread_coupon}
report={}
for name,part in parts.items():
s=part.val(); assert s.isValid(),name+' invalid'
assert len(s.Solids())==1,name+' not one solid'
printable=part
if name.startswith('lid'):
printable=part.rotate((0,0,0),(1,0,0),180).translate((0,W,H+LID))
elif name=='board_carrier': printable=part.translate((0,0,-22))
cq.exporters.export(printable,str(OUT/(name+'.stl')),tolerance=0.03,angularTolerance=0.12)
cq.exporters.export(part,str(OUT/(name+'.step')))
b=printable.val().BoundingBox()
report[name]={'valid':True,'solids':1,'volume_mm3':round(s.Volume(),2),'print_bounds_mm':[round(b.xlen,3),round(b.ylen,3),round(b.zlen,3)],'print_zmin':round(b.zmin,5)}
# Pairwise exact solid intersections (touching surfaces permitted).
for a,b in [('base','lid_solid'),('base','lid_window'),('base','board_carrier'),('board_carrier','lid_solid')]:
vol=parts[a].intersect(parts[b]).val().Volume()
report[a+' vs '+b]={'intersection_mm3':round(vol,7)}
assert vol<1e-5,(a,b,vol)
for name,ref in [('PSU',psu_ref),('terminals',terminal_ref),('PCB',board_ref),('screen',screen_ref)]:
for pname in ['base','board_carrier','lid_solid']:
vol=parts[pname].intersect(ref).val().Volume()
report[pname+' vs '+name]={'intersection_mm3':round(vol,7)}
assert vol<1e-5,(pname,name,vol)
assy=cq.Assembly(name='RS15_Heltec_V4_housing')
for name in ['base','board_carrier','lid_solid']:
assy.add(parts[name],name=name,color=cq.Color(0.24,0.32,0.39) if name=='base' else cq.Color(0.8,0.84,0.85))
assy.save(str(OUT/'housing_assembly.step'))
(OUT/'validation.json').write_text(json.dumps(report,indent=2))
# Cache original shapes for deterministic previews without rebuilding.
for name,part in {**parts,'psu_reference':psu_ref,'terminal_reference':terminal_ref,'board_reference':board_ref,'screen_reference':screen_ref}.items():
part.val().exportBrep(str(OUT/(name+'.brep')))
print(json.dumps(report,indent=2))
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -0,0 +1,32 @@
{
"lid_solid.stl": {
"triangles": 10404,
"all_edges_have_two_faces": true,
"signed_volume_mm3": 40884.329,
"minimum_z_mm": -6.112874255887531e-16
},
"M16_thread_test.stl": {
"triangles": 4196,
"all_edges_have_two_faces": true,
"signed_volume_mm3": 5069.676,
"minimum_z_mm": 0.0
},
"board_carrier.stl": {
"triangles": 4764,
"all_edges_have_two_faces": true,
"signed_volume_mm3": 6800.201,
"minimum_z_mm": 0.0
},
"lid_window.stl": {
"triangles": 11304,
"all_edges_have_two_faces": true,
"signed_volume_mm3": 39356.635,
"minimum_z_mm": -6.112874255887531e-16
},
"base.stl": {
"triangles": 15766,
"all_edges_have_two_faces": true,
"signed_volume_mm3": 150649.21,
"minimum_z_mm": 0.0
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

@@ -0,0 +1,105 @@
{
"base": {
"valid": true,
"solids": 1,
"volume_mm3": 150656.34,
"print_bounds_mm": [
122.017,
152.004,
48.004
],
"print_zmin": -0.00222
},
"lid_solid": {
"valid": true,
"solids": 1,
"volume_mm3": 40884.34,
"print_bounds_mm": [
122.004,
116.004,
5.002
],
"print_zmin": -0.00212
},
"lid_window": {
"valid": true,
"solids": 1,
"volume_mm3": 39356.63,
"print_bounds_mm": [
122.004,
116.004,
5.002
],
"print_zmin": -0.00212
},
"board_carrier": {
"valid": true,
"solids": 1,
"volume_mm3": 6800.46,
"print_bounds_mm": [
60.002,
36.002,
13.002
],
"print_zmin": -0.00085
},
"M16_thread_test": {
"valid": true,
"solids": 1,
"volume_mm3": 5069.09,
"print_bounds_mm": [
20.015,
28.0,
30.0
],
"print_zmin": -0.0
},
"base vs lid_solid": {
"intersection_mm3": 0.0
},
"base vs lid_window": {
"intersection_mm3": 0.0
},
"base vs board_carrier": {
"intersection_mm3": 0.0
},
"board_carrier vs lid_solid": {
"intersection_mm3": 0.0
},
"base vs PSU": {
"intersection_mm3": 0.0
},
"board_carrier vs PSU": {
"intersection_mm3": 0.0
},
"lid_solid vs PSU": {
"intersection_mm3": 0.0
},
"base vs terminals": {
"intersection_mm3": 0.0
},
"board_carrier vs terminals": {
"intersection_mm3": 0.0
},
"lid_solid vs terminals": {
"intersection_mm3": 0.0
},
"base vs PCB": {
"intersection_mm3": 0.0
},
"board_carrier vs PCB": {
"intersection_mm3": 0.0
},
"lid_solid vs PCB": {
"intersection_mm3": 0.0
},
"base vs screen": {
"intersection_mm3": 0.0
},
"board_carrier vs screen": {
"intersection_mm3": 0.0
},
"lid_solid vs screen": {
"intersection_mm3": 0.0
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
"""Compress one embedded HTTP asset without runtime work or timestamp churn."""
import gzip
import sys
from pathlib import Path
source, destination = map(Path, sys.argv[1:])
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(gzip.compress(source.read_bytes(), compresslevel=9, mtime=0))
+7
View File
@@ -1,6 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Deterministic discovery of DUT (Heltec V4.3) and SDR (Nooelec NESDR SMArt v5). # Deterministic discovery of DUT (Heltec V4.3) and SDR (Nooelec NESDR SMArt v5).
# Prints selected devices; exits nonzero on ambiguity or absence. # Prints selected devices; exits nonzero on ambiguity or absence.
# ./tools/discover_devices.sh [--dut-only|-v]
# --dut-only prints only DUT_PORT and does not inspect or require an SDR.
# #
# Output (eval-able): # Output (eval-able):
# DUT_PORT=/dev/serial/by-id/... # DUT_PORT=/dev/serial/by-id/...
@@ -22,6 +24,11 @@ fi
DUT_PORT="${dut_candidates[0]}" DUT_PORT="${dut_candidates[0]}"
[ -e "$DUT_PORT" ] || fail "DUT path vanished: $DUT_PORT" [ -e "$DUT_PORT" ] || fail "DUT path vanished: $DUT_PORT"
if [ "${1:-}" = "--dut-only" ]; then
printf 'DUT_PORT=%q\n' "$DUT_PORT"
exit 0
fi
# --- SDR: Nooelec NESDR SMArt v5 (RTL2832U, USB 0bda:2838) --- # --- SDR: Nooelec NESDR SMArt v5 (RTL2832U, USB 0bda:2838) ---
# Identity is established by USB VID:PID, because this dongle sometimes # Identity is established by USB VID:PID, because this dongle sometimes
# enumerates with empty descriptor strings after a fault (rtl_test then # enumerates with empty descriptor strings after a fault (rtl_test then
+5 -3
View File
@@ -1,12 +1,13 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Build + flash a firmware profile to the discovered DUT. # Build + flash a firmware profile to the discovered DUT; no SDR required.
# ./tools/flash.sh [test|debug] # ./tools/flash.sh [test|debug]
# Refuses ambiguous serial devices (see tools/discover_devices.sh). # Refuses ambiguous serial devices (see tools/discover_devices.sh).
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
PROFILE=${1:-test} PROFILE=${1:-test}
eval "$(./tools/discover_devices.sh)" devices=$(./tools/discover_devices.sh --dut-only)
eval "$devices"
echo "Flashing profile '$PROFILE' to: $DUT_PORT" >&2 echo "Flashing profile '$PROFILE' to: $DUT_PORT" >&2
./tools/build.sh "$PROFILE" ./tools/build.sh "$PROFILE"
@@ -16,7 +17,8 @@ if ! idf.py -B "build-$PROFILE" -p "$DUT_PORT" flash; then
# entering download mode re-enumerates the USB device; rediscover once # entering download mode re-enumerates the USB device; rediscover once
sleep 2 sleep 2
cd .. cd ..
eval "$(./tools/discover_devices.sh)" devices=$(./tools/discover_devices.sh --dut-only)
eval "$devices"
cd firmware cd firmware
idf.py -B "build-$PROFILE" -p "$DUT_PORT" flash idf.py -B "build-$PROFILE" -p "$DUT_PORT" flash
fi fi