// 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 #include #include #include #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); } }