Add repeater protocol and device firmware features

This commit is contained in:
Lars Nolden
2026-09-21 12:30:50 +02:00
parent 73d3ddf00c
commit a11a4b3b89
41 changed files with 7791 additions and 228 deletions
+492 -129
View File
@@ -3,6 +3,9 @@
#include "wmbus.h"
#include "board.h"
#include "led.h"
#include "duty_ledger.h"
#include "debug_history.h"
#include "settings.h"
#include <stdio.h>
#include <string.h>
@@ -35,63 +38,129 @@ repeater_cfg_t g_cfg = {
#else
.verbose = false,
#endif
.fem_rx_csd = true,
.preamble_bits = 8,
.test_lfield = 19,
.whitelist = {0},
.whitelist_len = 0,
};
repeater_stats_t g_stats;
repeater_ui_t g_ui;
static TaskHandle_t s_task;
static volatile int64_t s_irq_ts;
static volatile bool s_want_radio_reset;
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_test_burst;
static volatile int s_inject; // 1 = standby, 2 = sleep (config loss)
static uint8_t s_test_access_nr;
static uint8_t s_test_lfield = 19;
static uint32_t s_seq;
static int64_t s_last_beacon;
static struct { uint32_t hash; int64_t ts; } s_dup[DUP_RING];
static int s_dup_idx;
// Rolling-hour TX airtime ledger for the duty-cycle guard. At 0.1 % and
// ~13 ms per repeat the hourly ceiling is ~270 transmissions, so this ring
// cannot overflow within the window.
#define DUTY_RING 384
#define DUTY_WINDOW_US 3600000000LL
static struct { int64_t ts; uint32_t airtime_us; } s_duty[DUTY_RING];
static int s_duty_idx;
// Minute buckets retain every transmission in the rolling hour without an
// event-count limit. The oldest partial minute is included in full, so the
// compliance guard can over-count slightly but cannot silently under-count.
static duty_ledger_t s_duty;
// Cached radio-task health. heartbeat_us is the last existing hardware probe;
// 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)
{
uint64_t sum = 0;
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;
return duty_ledger_used(&s_duty, now);
}
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;
s_duty[s_duty_idx].airtime_us = airtime_us;
s_duty_idx = (s_duty_idx + 1) % DUTY_RING;
return duty_ledger_used(&s_duty, esp_timer_get_time());
}
// Would transmitting `bytes` now exceed the configured rolling-hour budget?
static bool duty_would_exceed(int64_t now, int bytes, uint64_t *used_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);
uint32_t want = (uint32_t)(bytes * US_PER_BYTE + 640);
uint32_t want = tx_airtime_us(bytes);
if (used_out) *used_out = used;
if (budget_out) *budget_out = budget_us;
if (g_cfg.duty_budget_ppm == 0) return false;
return (used + want) > budget_us;
return used > budget_us || want > budget_us - used;
}
// ------------------------------------------------------------------ logging
@@ -116,6 +185,11 @@ static void irq_cb(int64_t ts)
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)
{
sx126x_diag_t diag;
@@ -137,6 +211,9 @@ static bool radio_full_init(void)
diag.device_errors, diag.chip_mode,
(int)g_cfg.tx_power_dbm,
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;
}
@@ -145,6 +222,7 @@ static bool radio_full_init(void)
static bool recover(const char *reason, int level)
{
g_stats.recoveries++;
s_debug_status.recoveries++;
led_notify_fault();
bool ok = false;
switch (level) {
@@ -174,6 +252,9 @@ static bool recover(const char *reason, int level)
ok = radio_full_init() && sx126x_set_rx() && sx126x_config_intact();
break;
default:
s_debug_status.chip_mode = 0;
s_debug_status.config_intact = false;
publish_debug_status();
LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d,"
"\"result\":\"mcu_reset\"", reason, level);
fflush(stdout);
@@ -182,6 +263,10 @@ static bool recover(const char *reason, int level)
}
LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d,"
"\"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;
}
@@ -221,15 +306,6 @@ static bool whitelist_pass(const uint8_t *frame)
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)
{
int64_t now = esp_timer_get_time();
@@ -240,18 +316,26 @@ static void precise_delay_until(int64_t target_us)
// ------------------------------------------------------------------ TX
// Transmit mode bytes + frame. Returns result string for logging.
static const char *do_tx(const uint8_t *payload, int payload_len,
int64_t *tx_start_us, int64_t *tx_done_us)
// Transmit a physical radio payload. For C-mode that is mode bytes +
// frame; for T-mode the 3-of-6 coded stream. Returns result string.
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++;
// 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();
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++;
return "start_failed";
}
// airtime: 48 bit preamble + 16 bit sync + payload -> ~80us/byte + 640
uint32_t airtime_ms = (payload_len * US_PER_BYTE + 640) / 1000;
const uint32_t airtime_us = tx_airtime_us(payload_len);
const uint32_t airtime_ms = (airtime_us + 999) / 1000;
// Instrumented wait: poll IRQ flags, DIO1 level and chip mode while
// also honoring the ISR notification. Gives ground truth about the
// 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));
}
*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);
sx126x_clear_irq(SX126X_IRQ_ALL);
#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) {
g_stats.tx_success++;
led_notify_tx();
if (*tx_done_us > *tx_start_us) {
g_stats.tx_airtime_us += (uint64_t)(*tx_done_us - *tx_start_us);
}
g_stats.tx_airtime_us += airtime_us;
duty_ledger_record(&s_duty, *tx_start_us, airtime_us);
return notify_seen ? "ok" : "ok_polled";
}
if (irq & SX126X_IRQ_TIMEOUT) {
@@ -300,17 +389,31 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
return "irq_timeout";
}
static void log_tx(const char *result, uint32_t hash, int len,
int64_t rx_ts, int64_t tx_start, int64_t tx_done,
const uint8_t *payload, int payload_len)
static const char *do_tx(const uint8_t *payload, int payload_len, bool t1,
int64_t *tx_start_us, int64_t *tx_done_us,
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,"
"\"source_rx_timestamp_us\":%lld,\"delay_us\":%lld,"
"\"length\":%d,\"hash\":\"%08" PRIx32 "\","
"\"configured_tx_dbm\":%d,\"airtime_us\":%lld,\"result\":\"%s\"",
"\"length\":%d,\"mode\":\"%s\",\"hash\":\"%08" PRIx32 "\","
"\"configured_tx_dbm\":%d,\"airtime_us\":%" PRIu32 ","
"\"tx_operation_us\":%lld,\"result\":\"%s\"",
s_seq++, (long long)tx_start, (long long)rx_ts,
(long long)(tx_start - rx_ts), len, hash,
(int)g_cfg.tx_power_dbm,
(long long)(tx_start - rx_ts), len, mode, hash,
(int)g_cfg.tx_power_dbm, tx_airtime_us(phys_len),
(long long)(tx_done > tx_start ? tx_done - tx_start : 0), result);
#ifdef CONFIG_WMBUS_LOG_RAW_FRAMES
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)
{
debug_record_t record = debug_record_init("test", "C1", "A", esp_timer_get_time());
uint8_t frame[256];
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++,
s_test_lfield);
if (n < 0) return;
g_cfg.test_lfield);
if (n < 0) {
debug_history_record(&record);
return;
}
static uint8_t payload[258];
payload[0] = WMBUS_MODE_BYTE_A_HI;
payload[1] = WMBUS_MODE_BYTE_A_LO;
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;
const char *res = do_tx(payload, n + 2, &t0, &t1);
log_tx(res, hash, n, t0, t0, t1, NULL, 0);
const char *res = do_tx(payload, n + 2, false, &t0, &t1, &record);
log_tx(res, hash, n, n + 2, "C1", t0, t0, t1, NULL, 0);
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);
printf("\"}\n");
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();
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.
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 acc = s_test_access_nr++;
int n = wmbus_build_test_frame(frame, sizeof(frame), acc, s_test_lfield);
if (n < 0) return;
int n = wmbus_build_test_frame(frame, sizeof(frame), acc, g_cfg.test_lfield);
if (n < 0) {
debug_history_record(&record);
return;
}
uint64_t duty_used = 0, duty_budget = 0;
if (duty_would_exceed(esp_timer_get_time(), n + 2, &duty_used, &duty_budget)) {
g_stats.tx_suppressed_duty++;
LOGJ("\"event\":\"beacon_suppressed\",\"reason\":\"duty_cycle\","
"\"used_us\":%llu,\"budget_us\":%llu",
(unsigned long long)duty_used, (unsigned long long)duty_budget);
debug_frame(&record, frame, n);
record.outcome = "duty_cycle";
debug_history_record(&record);
return;
}
static uint8_t payload[258];
@@ -373,11 +527,13 @@ static void run_beacon(void)
memcpy(payload + 2, frame, n);
int64_t t0, t1;
const char *res = do_tx(payload, n + 2, &t0, &t1);
if (t1 > t0) duty_record(t0, (uint32_t)(t1 - t0));
const char *res = do_tx(payload, n + 2, false, &t0, &t1, &record);
LOGJ("\"event\":\"beacon\",\"acc\":%u,\"lfield\":%u,\"result\":\"%s\","
"\"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();
if (!sx126x_set_rx()) recover_ladder("beacon_rx_restore");
@@ -389,33 +545,45 @@ static void run_beacon(void)
// from anything in the RX path.
static void run_test_burst(void)
{
debug_record_t record = debug_record_init("test", "C1", "A", esp_timer_get_time());
uint8_t frame[256];
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++,
s_test_lfield);
if (n < 0) return;
g_cfg.test_lfield);
if (n < 0) {
debug_history_record(&record);
return;
}
static uint8_t payload[258];
payload[0] = WMBUS_MODE_BYTE_A_HI;
payload[1] = WMBUS_MODE_BYTE_A_LO;
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,"
"\"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);
printf("\"}\n");
fflush(stdout);
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();
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);
int64_t t2, t3;
const char *r2 = do_tx(payload, n + 2, &t2, &t3);
log_tx(r2, hash, n, first_end, t2, t3, NULL, 0);
const char *r2 = do_tx(payload, n + 2, false, &t2, &t3, &second);
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();
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.
static void run_probe(void)
{
debug_record_t record = debug_record_init("test", "C1", "A", 0);
uint8_t r[16];
printf("{\"event\":\"probe\",");
@@ -453,16 +622,29 @@ static void run_probe(void)
// small TX: 8 byte payload
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\":[");
for (int i = 0; i < 12; i++) {
vTaskDelay(pdMS_TO_TICKS(2));
uint8_t s2[2], q[4];
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],
i < 11 ? "," : "");
}
if (record.tx_done_us == 0) record.tx_done_us = esp_timer_get_time();
printf("],");
fem_set_tx(false);
@@ -474,6 +656,8 @@ static void run_probe(void)
sx126x_set_rx();
printf("\"done\":true}\n");
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)
{
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];
int8_t rssi = 0;
int n = sx126x_read_rx(buf, sizeof(buf), &rssi);
record.rssi_dbm = rssi;
if (n < 3) {
recover_ladder("rx_read_failed");
return;
debug_rx_rejected(&record, "rx_read_failed", buf, n);
read_failed = true;
goto done;
}
g_stats.rx_candidates++;
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]);
if (fmt == WMBUS_FRAME_UNKNOWN) {
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);
bool t1 = false;
bool identity_available = true;
uint8_t *frame;
int total;
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) led_notify_rx();
uint32_t hash = wmbus_hash(frame, total);
// RxDone fires after the fixed 255-byte capture; the frame actually
// ended earlier. Reconstruct the real end-of-frame time.
int64_t frame_end_ts = rxdone_ts - (int64_t)(RX_PAYLOAD_LEN - (total + 2)) * US_PER_BYTE;
// ended earlier. Reconstruct the real end-of-frame time from the
// 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,"
"\"rxdone_us\":%lld,\"frequency_hz\":868950000,\"format\":\"%c\","
"\"length\":%d,\"rssi_dbm\":%d,\"crc_ok\":%s,"
"\"rxdone_us\":%lld,\"frequency_hz\":868950000,\"mode\":\"%s\","
"\"format\":\"%c\",\"length\":%d,\"rssi_dbm\":%d,\"crc_ok\":%s,"
"\"hash\":\"%08" PRIx32 "\"",
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);
#ifdef CONFIG_WMBUS_LOG_RAW_FRAMES
printf(",\"raw\":\"");
@@ -536,10 +794,11 @@ static void handle_rx(int64_t rxdone_ts)
printf("}\n");
fflush(stdout);
if (!g_cfg.repeat_enabled || !crc_ok) return;
if (!g_cfg.repeat_enabled || !crc_ok) goto done;
if (!whitelist_pass(frame)) {
g_stats.tx_suppressed_whitelist++;
return;
record.outcome = "whitelist";
goto done;
}
int64_t now = esp_timer_get_time();
if (is_dup(hash, now)) {
@@ -547,32 +806,67 @@ static void handle_rx(int64_t rxdone_ts)
if (g_cfg.verbose) {
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"dup\",\"hash\":\"%08" PRIx32 "\"", hash);
}
return;
record.outcome = "duplicate";
goto done;
}
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++;
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"duty_cycle\","
"\"hash\":\"%08" PRIx32 "\",\"used_us\":%llu,\"budget_us\":%llu",
hash, (unsigned long long)duty_used,
(unsigned long long)duty_budget);
return;
record.outcome = "duty_cycle";
goto done;
}
// ---- repeat ----
static uint8_t txbuf[RX_PAYLOAD_LEN + 2];
txbuf[0] = buf[0];
txbuf[1] = buf[1];
memcpy(txbuf + 2, frame, total);
// RX logging/hash above describe the original. TX carries only the
// standard H-bit change and repaired CRC; ciphertext is untouched.
if (!wmbus_mark_repeated(fmt, frame, total)) {
if (g_cfg.verbose) {
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);
int64_t t0, t1;
const char *res = do_tx(txbuf, total + 2, &t0, &t1);
if (t1 > t0) duty_record(t0, (uint32_t)(t1 - t0));
int64_t t0, t1_done;
const char *res = do_tx(txbuf, phys, t1, &t0, &t1_done, &record);
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
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
static void repeater_task(void *arg)
@@ -596,27 +931,38 @@ static void repeater_task(void *arg)
s_task = xTaskGetCurrentTaskHandle();
sx126x_set_irq_callback(irq_cb);
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()) {
// keep retrying with full ladder rather than dying
recover_ladder("boot_init_failed");
}
if (!sx126x_set_rx()) recover_ladder("boot_rx_failed");
s_debug_status.chip_mode = 0x5;
publish_debug_status();
led_boot_done();
int64_t last_heartbeat = 0;
for (;;) {
esp_task_wdt_reset();
apply_pending_settings();
if (s_want_radio_reset) {
s_want_radio_reset = false;
g_stats.radio_reinit++;
if (!radio_full_init() || !sx126x_set_rx()) recover_ladder("manual_reset");
else s_debug_status.chip_mode = 0x5;
}
if (s_want_test_tx) {
s_want_test_tx = false;
run_test_tx();
}
if (s_want_test_tx_t1) {
s_want_test_tx_t1 = false;
run_test_tx_t1();
}
if (s_want_test_burst) {
s_want_test_burst = false;
run_test_burst();
@@ -640,14 +986,7 @@ static void repeater_task(void *arg)
}
if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(1000)) > 0) {
uint16_t 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);
}
handle_irq(sx126x_get_irq());
}
if (g_cfg.beacon_period_ms) {
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 mode = (st >> 4) & 0x7;
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,"
"\"config_intact\":%s,\"rssi_dbm\":%d",
(long long)now, mode, cfg_ok ? "true" : "false",
sx126x_get_rssi_inst());
(int)rssi_now);
if (mode != 0x5) {
recover_ladder("not_in_rx");
} else if (!cfg_ok) {
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_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_set_test_lfield(uint8_t l) { s_test_lfield = l; }
void repeater_request_test_burst(void) { s_want_test_burst = true; }
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)
{
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,"
"\"repeat_delay_ms\":%" PRIu32 ",\"configured_tx_dbm\":%d,"
"\"repeat_enabled\":%s,\"verbose\":%s,\"whitelist_len\":%d,"
"\"preamble_detect_code\":%u,\"duty_budget_ppm\":%" 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(),
g_cfg.repeat_delay_ms, (int)g_cfg.tx_power_dbm,
g_cfg.repeat_enabled ? "true" : "false",
g_cfg.verbose ? "true" : "false",
g_cfg.whitelist_len,
sx126x_get_preamble_detect(),
g_cfg.duty_budget_ppm,
g_cfg.beacon_period_ms,
cfg->repeat_delay_ms, (int)cfg->tx_power_dbm,
cfg->repeat_enabled ? "true" : "false",
cfg->verbose ? "true" : "false",
cfg->whitelist_len, preamble_detect_code(cfg->preamble_bits),
cfg->duty_budget_ppm, cfg->beacon_period_ms,
(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)
@@ -719,7 +1080,8 @@ void repeater_print_stats(void)
LOGJ("\"event\":\"stats\",\"uptime_us\":%lld,"
"\"rx_candidates\":%" PRIu32 ",\"rx_valid\":%" 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_timeout\":%" PRIu32 ",\"tx_failures\":%" PRIu32 ","
"\"tx_suppressed_dup\":%" PRIu32 ",\"tx_suppressed_whitelist\":%" PRIu32 ","
@@ -729,7 +1091,8 @@ void repeater_print_stats(void)
"\"tx_duty_cycle_ppm\":%llu",
(long long)esp_timer_get_time(),
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_failures, g_stats.tx_suppressed_dup,
g_stats.tx_suppressed_whitelist, g_stats.tx_suppressed_duty,