#include "repeater.h" #include "sx126x.h" #include "wmbus.h" #include "board.h" #include "led.h" #include "duty_ledger.h" #include "debug_history.h" #include "settings.h" #include #include #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_timer.h" #include "driver/gpio.h" #include "esp_task_wdt.h" #include "esp_system.h" #define RX_PAYLOAD_LEN 255 // fixed radio capture length; truncated in software #define US_PER_BYTE 80 // 100 kbps -> 80 us per byte #define DUP_WINDOW_US 2500000LL #define DUP_RING 8 repeater_cfg_t g_cfg = { .repeat_delay_ms = 50, // 868.7-869.2 MHz is limited to 0.1 % duty cycle (25 mW e.r.p.) by // ERC/REC 70-03 annex h1.6, unless LBT+AFA is implemented. A repeater // that echoes every telegram can exceed this in a dense meter // environment, so the experiment enforces the budget itself rather than // relying on traffic being sparse. See docs/STANDARDS_GAPS.md. .duty_budget_ppm = 1000, // 1000 ppm = 0.1 % .beacon_period_ms = 0, .tx_power_dbm = -9, .repeat_enabled = true, #ifdef CONFIG_WMBUS_VERBOSE_DEFAULT .verbose = true, #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 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; // 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) { return duty_ledger_used(&s_duty, now); } uint64_t repeater_duty_used_us(void) { 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 * DUTY_LEDGER_WINDOW_US / 1000000ULL; uint64_t used = duty_used_us(now); 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 > budget_us || want > budget_us - used; } // ------------------------------------------------------------------ logging static void print_hex(const uint8_t *d, int n) { for (int i = 0; i < n; i++) printf("%02X", d[i]); } #define LOGJ(fmt, ...) do { \ printf("{\"seq\":%" PRIu32 "," fmt "}\n", s_seq++, ##__VA_ARGS__); \ fflush(stdout); \ } while (0) // ------------------------------------------------------------------ radio static void irq_cb(int64_t ts) { s_irq_ts = ts; BaseType_t hp = pdFALSE; if (s_task) vTaskNotifyGiveFromISR(s_task, &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) { sx126x_diag_t diag; bool init_ok = sx126x_init(&diag); // Apply the wM-Bus configuration even when init reports soft failures: // an unconfigured radio in RX is worse than a partially degraded one, // and the recovery ladder judges the combined result anyway. bool cfg_ok = sx126x_config_wmbus_c1(868950000u, RX_PAYLOAD_LEN) & sx126x_set_tx_power(g_cfg.tx_power_dbm); cfg_ok = init_ok && cfg_ok; LOGJ("\"event\":\"radio_init\",\"spi\":%s,\"reset\":%s,\"busy_low\":%s," "\"tcxo\":%s,\"device_errors\":%u,\"chip_mode\":%u," "\"fem_power\":true,\"fem_mode\":\"rx\",\"frequency_hz\":868950000," "\"configured_tx_dbm\":%d,\"result\":\"%s\"", diag.spi_ok ? "true" : "false", diag.reset_ok ? "true" : "false", diag.busy_ok ? "true" : "false", diag.tcxo_ok ? "true" : "false", 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; } // Recovery ladder: 1 clear/restart RX, 2 radio reinit, 3 FEM+radio reinit, // 4 reboot. Returns true if RX was restored. static bool recover(const char *reason, int level) { g_stats.recoveries++; s_debug_status.recoveries++; led_notify_fault(); bool ok = false; switch (level) { case 1: // Cheapest step: clear IRQ state and re-arm RX. It must only report // success if the radio really is configured and receiving, otherwise // the ladder would stop at a deaf radio. sx126x_clear_irq(SX126X_IRQ_ALL); sx126x_standby(); sx126x_restore_rx_payload_len(); ok = sx126x_set_rx() && sx126x_config_intact(); if (ok) { vTaskDelay(pdMS_TO_TICKS(2)); ok = (((sx126x_get_status() >> 4) & 0x7) == 0x5); } break; case 2: g_stats.radio_reinit++; ok = radio_full_init() && sx126x_set_rx() && sx126x_config_intact(); break; case 3: g_stats.fem_reinit++; fem_power(false); vTaskDelay(pdMS_TO_TICKS(20)); fem_power(true); vTaskDelay(pdMS_TO_TICKS(5)); 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); vTaskDelay(pdMS_TO_TICKS(100)); esp_restart(); } 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; } static void recover_ladder(const char *reason) { for (int level = 1; level <= 4; level++) { if (recover(reason, level)) return; } } // ------------------------------------------------------------------ helpers static bool is_dup(uint32_t hash, int64_t now) { for (int i = 0; i < DUP_RING; i++) { if (s_dup[i].hash == hash && now - s_dup[i].ts < DUP_WINDOW_US) return true; } return false; } static void remember_dup(uint32_t hash, int64_t now) { s_dup[s_dup_idx].hash = hash; s_dup[s_dup_idx].ts = now; s_dup_idx = (s_dup_idx + 1) % DUP_RING; } static bool whitelist_pass(const uint8_t *frame) { if (g_cfg.whitelist_len == 0) return true; // A-field ID: frame bytes 4..7 (after L, C, M) little endian uint32_t id = (uint32_t)frame[4] | ((uint32_t)frame[5] << 8) | ((uint32_t)frame[6] << 16) | ((uint32_t)frame[7] << 24); for (int i = 0; i < g_cfg.whitelist_len; i++) { if (g_cfg.whitelist[i] == id) return true; } return false; } static void precise_delay_until(int64_t target_us) { int64_t now = esp_timer_get_time(); int64_t remaining = target_us - now; if (remaining > 2000) vTaskDelay(pdMS_TO_TICKS((remaining - 1000) / 1000)); while (esp_timer_get_time() < target_us) { /* spin <=~1ms */ } } // ------------------------------------------------------------------ TX // 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(); *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"; } 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. int64_t deadline = esp_timer_get_time() + (airtime_ms + 200) * 1000LL; uint16_t irq = 0; bool notify_seen = false, dio1_seen = false; uint8_t max_mode = 0; while (esp_timer_get_time() < deadline) { if (ulTaskNotifyTake(pdTRUE, 0) > 0) notify_seen = true; if (gpio_get_level(BOARD_LORA_DIO1)) dio1_seen = true; uint8_t st = sx126x_get_status(); uint8_t mode = (st >> 4) & 0x7; if (mode > max_mode) max_mode = mode; irq = sx126x_get_irq(); if (irq) break; 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 const bool want_diag = true; #else // otherwise only when something went wrong, so timing stays clean const bool want_diag = g_cfg.verbose || !(irq & SX126X_IRQ_TX_DONE); #endif if (want_diag) { LOGJ("\"event\":\"tx_diag\",\"irq\":%u,\"notify\":%s," "\"dio1_high_seen\":%s,\"max_chip_mode\":%u,\"device_errors\":%u", irq, notify_seen ? "true" : "false", dio1_seen ? "true" : "false", max_mode, sx126x_get_device_errors()); } if (irq & SX126X_IRQ_TX_DONE) { g_stats.tx_success++; led_notify_tx(); 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) { g_stats.tx_timeout++; return "radio_timeout"; } g_stats.tx_timeout++; return "irq_timeout"; } 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,\"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, 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) { printf(",\"tx_payload\":\""); print_hex(payload, payload_len); printf("\""); } #else (void)payload; (void)payload_len; #endif printf("}\n"); fflush(stdout); } 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++, 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); debug_frame(&record, frame, n); uint32_t hash = record.hash; int64_t t0, t1; 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++, 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"); } // Periodic synthetic OMS beacon: standalone RF measurements without meter // traffic or serial coordination. access_nr doubles as sequence number and // is recoverable from every SDR-side decode (SLN manufacturer, ID 00000001). // 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, 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]; payload[0] = WMBUS_MODE_BYTE_A_HI; payload[1] = WMBUS_MODE_BYTE_A_LO; memcpy(payload + 2, frame, n); int64_t t0, t1; 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, 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"); } // Transmit the SAME frame twice, separated by repeat_delay_ms. This // reproduces the original+repeat timing pattern without needing a meter, // isolating "can the observer decode a second identical frame N ms later" // 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++, 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); 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++, 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, false, &t0, &t1, &record); int64_t first_end = t1 > t0 ? t1 : esp_timer_get_time(); 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, 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"); } // ---------------------------------------------------------------- probe static void hexdump_json(const char *key, const uint8_t *d, int n) { printf("\"%s\":\"", key); print_hex(d, n); printf("\","); } // 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\","); sx126x_standby(); sx126x_raw(0xC0, NULL, 0, r, 2); // GetStatus hexdump_json("status0", r, 2); // SetDioIrqParams: all IRQs, all on DIO1 uint8_t di[8] = {0x03, 0xFF, 0x03, 0xFF, 0, 0, 0, 0}; sx126x_raw(0x08, di, 8, r, 9); hexdump_json("setirq_resp", r, 9); sx126x_raw(0xC0, NULL, 0, r, 2); // status after SetDioIrqParams hexdump_json("status_after_setirq", r, 2); sx126x_raw(0x02, (uint8_t[]){0x03, 0xFF}, 2, NULL, 0); // ClearIrq sx126x_raw(0x12, NULL, 0, r, 4); // GetIrqStatus raw hexdump_json("irq_cleared", r, 4); // small TX: 8 byte payload uint8_t pkt[8] = {0x54, 0xCD, 0xAA, 0x55, 0xDE, 0xAD, 0xBE, 0xEF}; 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); 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); sx126x_raw(0x17, NULL, 0, r, 4); // GetDeviceErrors hexdump_json("dev_errors", r, 4); sx126x_clear_irq(SX126X_IRQ_ALL); sx126x_restore_rx_payload_len(); sx126x_set_rx(); printf("\"done\":true}\n"); fflush(stdout); debug_frame(&record, pkt + 2, sizeof(pkt) - 2); debug_history_record(&record); } // ------------------------------------------------------------------ RX path 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) { 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]); 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; } } 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 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,\"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, t1 ? "T1" : "C1", fmt == WMBUS_FRAME_A ? 'A' : 'B', total, rssi, crc_ok ? "true" : "false", hash); #ifdef CONFIG_WMBUS_LOG_RAW_FRAMES printf(",\"raw\":\""); print_hex(frame, total); printf("\""); #endif printf("}\n"); fflush(stdout); if (!g_cfg.repeat_enabled || !crc_ok) goto done; if (!whitelist_pass(frame)) { g_stats.tx_suppressed_whitelist++; record.outcome = "whitelist"; goto done; } int64_t now = esp_timer_get_time(); if (is_dup(hash, now)) { g_stats.tx_suppressed_dup++; if (g_cfg.verbose) { LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"dup\",\"hash\":\"%08" PRIx32 "\"", hash); } record.outcome = "duplicate"; goto done; } uint64_t duty_used = 0, duty_budget = 0; 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); record.outcome = "duty_cycle"; goto done; } // 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_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, 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(); if (!sx126x_set_rx()) { recover_ladder("post_tx_rx_restore"); } else { int64_t rx_ready = esp_timer_get_time(); if (g_cfg.verbose) { LOGJ("\"event\":\"rx_ready\",\"timestamp_us\":%lld," "\"deaf_time_us\":%lld", (long long)rx_ready, (long long)(rx_ready - frame_end_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) { (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(); } if (s_want_probe) { s_want_probe = false; run_probe(); } if (s_inject) { int what = s_inject; s_inject = 0; // Deliberately break the radio to exercise detection + the // recovery ladder. The heartbeat probe is expected to notice. if (what == 1) { sx126x_standby(); } else { sx126x_inject_sleep(); } LOGJ("\"event\":\"fault_injected\",\"fault\":\"%s\"", what == 1 ? "standby" : "sleep"); } if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(1000)) > 0) { handle_irq(sx126x_get_irq()); } if (g_cfg.beacon_period_ms) { int64_t bnow = esp_timer_get_time(); if (bnow - s_last_beacon >= (int64_t)g_cfg.beacon_period_ms * 1000) { s_last_beacon = bnow; run_beacon(); } } int64_t now = esp_timer_get_time(); if (now - last_heartbeat > 10000000LL) { last_heartbeat = now; // Consistency probe: the chip must be in RX (0x5) AND still // hold its wM-Bus configuration. Checking the mode alone is not // enough: a radio that lost its configuration (reset, sleep, // glitch) can sit in RX looking healthy while deaf to C1. 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", (int)rssi_now); if (mode != 0x5) { recover_ladder("not_in_rx"); } else if (!cfg_ok) { recover_ladder("config_lost"); } } publish_debug_status(); } } void repeater_start(void) { xTaskCreatePinnedToCore(repeater_task, "repeater", 8192, NULL, 10, NULL, 1); } 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_request_test_burst(void) { s_want_test_burst = true; } void repeater_inject_fault(int what) { s_inject = what; } // ------------------------------------------------------------------ status 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," "\"fem_rx_csd\":%s,\"preamble_bits\":%u,\"test_lfield\":%u," "\"whitelist\":[%s],\"revision\":%" PRIu32 ",\"applied_revision\":%" PRIu32, (long long)esp_timer_get_time(), 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(), cfg->fem_rx_csd ? "true" : "false", cfg->preamble_bits, cfg->test_lfield, whitelist, snapshot.revision, snapshot.applied_revision); } 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_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 "," "\"tx_suppressed_duty\":%" PRIu32 "," "\"radio_reinit\":%" PRIu32 ",\"fem_reinit\":%" PRIu32 "," "\"recoveries\":%" PRIu32 ",\"tx_airtime_us\":%llu," "\"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_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, g_stats.radio_reinit, g_stats.fem_reinit, g_stats.recoveries, (unsigned long long)g_stats.tx_airtime_us, (unsigned long long)(esp_timer_get_time() > 0 ? (g_stats.tx_airtime_us * 1000000ULL) / (uint64_t)esp_timer_get_time() : 0)); } void repeater_print_radio_status(void) { uint8_t st = sx126x_get_status(); LOGJ("\"event\":\"radio_status\",\"status_byte\":%u,\"chip_mode\":%u," "\"cmd_status\":%u,\"device_errors\":%u,\"rssi_dbm\":%d," "\"busy\":%s", st, (st >> 4) & 0x7, (st >> 1) & 0x7, sx126x_get_device_errors(), sx126x_get_rssi_inst(), "false"); }