#include "repeater.h" #include "sx126x.h" #include "wmbus.h" #include "board.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, .tx_power_dbm = -9, .repeat_enabled = true, #ifdef CONFIG_WMBUS_VERBOSE_DEFAULT .verbose = true, #else .verbose = false, #endif .whitelist = {0}, .whitelist_len = 0, }; repeater_stats_t g_stats; 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_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 struct { uint32_t hash; int64_t ts; } s_dup[DUP_RING]; static int s_dup_idx; // ------------------------------------------------------------------ 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 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"); 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++; 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: 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"); 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; } // 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(); 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 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) { g_stats.tx_attempts++; *tx_start_us = esp_timer_get_time(); if (!sx126x_start_tx(payload, (uint8_t)payload_len)) { 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; // 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(); 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++; 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 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) { 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\"", 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_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) { uint8_t frame[256]; int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++, s_test_lfield); if (n < 0) 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); int64_t t0, t1; const char *res = do_tx(payload, n + 2, &t0, &t1); log_tx(res, hash, n, t0, t0, t1, NULL, 0); printf("{\"seq\":%" PRIu32 ",\"event\":\"test_tx_frame\",\"lfield\":%u,\"raw\":\"", s_seq++, s_test_lfield); print_hex(frame, n); printf("\"}\n"); fflush(stdout); sx126x_restore_rx_payload_len(); if (!sx126x_set_rx()) recover_ladder("test_tx_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) { uint8_t frame[256]; int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++, s_test_lfield); if (n < 0) 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); printf("{\"seq\":%" PRIu32 ",\"event\":\"test_burst_frame\",\"lfield\":%u," "\"delay_ms\":%" PRIu32 ",\"raw\":\"", s_seq++, s_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); int64_t first_end = t1 > t0 ? t1 : esp_timer_get_time(); log_tx(r1, hash, n, 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); 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) { 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}; sx126x_start_tx(pkt, 8); 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); printf("\"%02X-%02X%02X%02X%02X\"%s", s2[1], q[0], q[1], q[2], q[3], i < 11 ? "," : ""); } 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); } // ------------------------------------------------------------------ RX path static void handle_rx(int64_t rxdone_ts) { static uint8_t buf[RX_PAYLOAD_LEN]; int8_t rssi = 0; int n = sx126x_read_rx(buf, sizeof(buf), &rssi); if (n < 3) { recover_ladder("rx_read_failed"); return; } g_stats.rx_candidates++; g_stats.rx_bytes += n; 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); } 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++; 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; 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," "\"hash\":\"%08" PRIx32 "\"", s_seq++, (long long)frame_end_ts, (long long)rxdone_ts, 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) return; if (!whitelist_pass(frame)) { g_stats.tx_suppressed_whitelist++; return; } 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); } return; } // ---- repeat ---- static uint8_t txbuf[RX_PAYLOAD_LEN + 2]; txbuf[0] = buf[0]; txbuf[1] = buf[1]; memcpy(txbuf + 2, frame, total); 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); remember_dup(hash, esp_timer_get_time()); log_tx(res, hash, total, frame_end_ts, t0, t1, txbuf, total + 2); // 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)); } } } // ------------------------------------------------------------------ task static void repeater_task(void *arg) { (void)arg; s_task = xTaskGetCurrentTaskHandle(); sx126x_set_irq_callback(irq_cb); esp_task_wdt_add(NULL); 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"); int64_t last_heartbeat = 0; for (;;) { esp_task_wdt_reset(); 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"); } if (s_want_test_tx) { s_want_test_tx = false; run_test_tx(); } 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) { 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); } } 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(); 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()); if (mode != 0x5) { recover_ladder("not_in_rx"); } else if (!cfg_ok) { recover_ladder("config_lost"); } } } } 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_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; } // ------------------------------------------------------------------ status void repeater_print_status(void) { 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,\"reset_reason\":%d", (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(), (int)esp_reset_reason()); } 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 "," "\"tx_attempts\":%" PRIu32 ",\"tx_success\":%" PRIu32 "," "\"tx_timeout\":%" PRIu32 ",\"tx_failures\":%" PRIu32 "," "\"tx_suppressed_dup\":%" PRIu32 ",\"tx_suppressed_whitelist\":%" PRIu32 "," "\"radio_reinit\":%" PRIu32 ",\"fem_reinit\":%" PRIu32 "," "\"recoveries\":%" PRIu32, (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.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.radio_reinit, g_stats.fem_reinit, g_stats.recoveries); } 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"); }