#include #include #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "freertos/timers.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_log.h" #include "nvs_flash.h" #include "nvs.h" #include "esp_netif.h" #include "esp_http_server.h" #include "lwip/sockets.h" #include "board.h" /* ---- Fallbacks, used only if board.h does not define them ---- */ #ifndef WIFI_NS #define WIFI_NS "wifi_cfg" #endif #ifndef WIFI_SSID_KEY #define WIFI_SSID_KEY "ssid" #endif #ifndef WIFI_PASS_KEY #define WIFI_PASS_KEY "pass" #endif #ifndef WIFI_CONNECTED_BIT #define WIFI_CONNECTED_BIT BIT0 #endif #define PROV_TIMEOUT_SEC 300 /* portal closes and board restarts after this */ #define MAX_RECONNECT_TRIES 30 /* then the board reboots into the portal */ #define AP_SSID "ESP32_Setup" #define AP_CHANNEL 6 #define AP_IP_STR "192.168.4.1" #define HOSTNAME "hodor-cam" static const char *TAG = "WIFI"; bool g_wifi_is_shutting_down = false; /* kept for compatibility with other code */ static EventGroupHandle_t s_wifi_event_group = NULL; static httpd_handle_t s_portal_server = NULL; static TimerHandle_t s_prov_timer = NULL; static esp_netif_t *s_sta_netif = NULL; static esp_netif_t *s_ap_netif = NULL; static bool s_provisioning = false; static int s_retry = 0; /* Survive esp_restart() (software reset), lost on power cycle */ RTC_DATA_ATTR static bool rtc_force_portal = false; /* set after too many failed reconnects */ RTC_DATA_ATTR static bool rtc_hint_valid = false; /* fast-connect channel hint */ RTC_DATA_ATTR static uint8_t rtc_hint_channel = 0; /* ------------------------------------------------------------------ */ /* Portal web page */ /* ------------------------------------------------------------------ */ static const char *html_settings = "" "" "" "" "" "تنظیمات وای‌فای" "" "" "" "
" "

⚙️ تنظیمات وای‌فای

" "
" "" "" "" "" "" "
" "
" "
" "" "" ""; /* ------------------------------------------------------------------ */ /* Helpers */ /* ------------------------------------------------------------------ */ static int hex_val(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; } static void url_decode(char *dest, const char *src) { while (*src) { if (src[0] == '%' && hex_val(src[1]) >= 0 && hex_val(src[2]) >= 0) { *dest++ = (char)(16 * hex_val(src[1]) + hex_val(src[2])); src += 3; } else if (*src == '+') { *dest++ = ' '; src++; } else { *dest++ = *src++; } } *dest = '\0'; } void wifi_erase_credentials(void) { nvs_handle_t h; if (nvs_open(WIFI_NS, NVS_READWRITE, &h) == ESP_OK) { nvs_erase_key(h, WIFI_SSID_KEY); nvs_erase_key(h, WIFI_PASS_KEY); nvs_commit(h); nvs_close(h); } } /* ------------------------------------------------------------------ */ /* Portal HTTP server */ /* ------------------------------------------------------------------ */ static esp_err_t root_get_handler(httpd_req_t *req) { httpd_resp_set_type(req, "text/html; charset=utf-8"); httpd_resp_set_hdr(req, "Cache-Control", "no-cache"); return httpd_resp_send(req, html_settings, HTTPD_RESP_USE_STRLEN); } static esp_err_t save_post_handler(httpd_req_t *req) { char body[512]; size_t total = req->content_len; if (total == 0 || total >= sizeof(body)) { httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad length"); return ESP_FAIL; } size_t got = 0; while (got < total) { int r = httpd_req_recv(req, body + got, total - got); if (r == HTTPD_SOCK_ERR_TIMEOUT) continue; if (r <= 0) return ESP_FAIL; got += r; } body[got] = '\0'; char ssid_enc[128] = {0}, pass_enc[256] = {0}; char ssid[33] = {0}, pass[65] = {0}; httpd_query_key_value(body, "ssid", ssid_enc, sizeof(ssid_enc)); httpd_query_key_value(body, "pass", pass_enc, sizeof(pass_enc)); url_decode(ssid, ssid_enc); url_decode(pass, pass_enc); size_t sl = strlen(ssid), pl = strlen(pass); if (sl == 0 || sl > 32 || (pl != 0 && (pl < 8 || pl > 63))) { httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "invalid credentials"); return ESP_FAIL; } ESP_LOGI(TAG, "Saving SSID: %s", ssid); nvs_handle_t h; if (nvs_open(WIFI_NS, NVS_READWRITE, &h) != ESP_OK) { httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "nvs error"); return ESP_FAIL; } nvs_set_str(h, WIFI_SSID_KEY, ssid); nvs_set_str(h, WIFI_PASS_KEY, pass); nvs_commit(h); nvs_close(h); rtc_hint_valid = false; rtc_force_portal = false; httpd_resp_send(req, "OK", HTTPD_RESP_USE_STRLEN); vTaskDelay(pdMS_TO_TICKS(800)); esp_restart(); return ESP_OK; } /* Every unknown URL (Android generate_204, Apple hotspot-detect, Windows * connecttest, ...) is redirected to the setup page. This is what makes the * phone/PC pop up the "sign in to network" screen. */ static esp_err_t redirect_404_handler(httpd_req_t *req, httpd_err_code_t err) { httpd_resp_set_status(req, "302 Found"); httpd_resp_set_hdr(req, "Location", "http://" AP_IP_STR "/"); httpd_resp_set_hdr(req, "Cache-Control", "no-store"); httpd_resp_send(req, NULL, 0); return ESP_OK; } static void start_portal_webserver(void) { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.server_port = 80; config.stack_size = 8192; config.lru_purge_enable = true; if (httpd_start(&s_portal_server, &config) != ESP_OK) { ESP_LOGE(TAG, "Portal HTTP server failed to start"); s_portal_server = NULL; return; } httpd_uri_t root = { .uri = "/", .method = HTTP_GET, .handler = root_get_handler }; httpd_uri_t save = { .uri = "/save", .method = HTTP_POST, .handler = save_post_handler }; httpd_register_uri_handler(s_portal_server, &root); httpd_register_uri_handler(s_portal_server, &save); httpd_register_err_handler(s_portal_server, HTTPD_404_NOT_FOUND, redirect_404_handler); ESP_LOGI(TAG, "Portal HTTP server started on port 80"); } /* ------------------------------------------------------------------ */ /* Portal DNS server: answers every A query with 192.168.4.1 */ /* ------------------------------------------------------------------ */ static void dns_server_task(void *param) { int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) { ESP_LOGE(TAG, "DNS: socket failed"); vTaskDelete(NULL); return; } struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(53); if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { ESP_LOGE(TAG, "DNS: bind failed"); close(sock); vTaskDelete(NULL); return; } ESP_LOGI(TAG, "DNS server started on port 53"); static uint8_t buf[512]; static uint8_t resp[576]; while (1) { struct sockaddr_in client; socklen_t clen = sizeof(client); int n = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&client, &clen); if (n <= 12) continue; uint16_t flags = (buf[2] << 8) | buf[3]; if (flags & 0x8000) continue; /* not a query */ /* walk the question name */ int pos = 12; while (pos < n && buf[pos] != 0) pos += buf[pos] + 1; if (pos + 5 > n) continue; /* malformed */ pos++; /* terminating 0 */ uint16_t qtype = (buf[pos] << 8) | buf[pos + 1]; pos += 4; /* QTYPE + QCLASS */ int qd_len = pos - 12; bool answer = (qtype == 1); /* A record only; AAAA etc. get empty NOERROR */ memset(resp, 0, 12); resp[0] = buf[0]; resp[1] = buf[1]; resp[2] = 0x81; /* response, recursion desired */ resp[3] = 0x80; /* recursion available, no error */ resp[5] = 1; /* QDCOUNT */ resp[7] = answer ? 1 : 0; /* ANCOUNT */ int rl = 12; memcpy(&resp[rl], &buf[12], qd_len); rl += qd_len; if (answer) { static const uint8_t ans[] = { 0xC0, 0x0C, /* name pointer */ 0x00, 0x01, /* type A */ 0x00, 0x01, /* class IN */ 0x00, 0x00, 0x01, 0x2C, /* TTL 300 */ 0x00, 0x04, /* RDLENGTH */ 192, 168, 4, 1 /* 192.168.4.1 */ }; memcpy(&resp[rl], ans, sizeof(ans)); rl += sizeof(ans); } sendto(sock, resp, rl, 0, (struct sockaddr *)&client, clen); } } /* ------------------------------------------------------------------ */ /* Provisioning mode */ /* ------------------------------------------------------------------ */ static void prov_timeout_callback(TimerHandle_t xTimer) { ESP_LOGW(TAG, "Provisioning timed out, restarting"); esp_restart(); } static void start_provisioning_mode(void) { ESP_LOGI(TAG, "Starting captive portal"); s_provisioning = true; ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP)); wifi_config_t ap_cfg = {0}; strcpy((char *)ap_cfg.ap.ssid, AP_SSID); ap_cfg.ap.ssid_len = strlen(AP_SSID); ap_cfg.ap.channel = AP_CHANNEL; ap_cfg.ap.max_connection = 4; ap_cfg.ap.authmode = WIFI_AUTH_OPEN; ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_cfg)); /* Make the DHCP server hand out our own IP as DNS server, otherwise * phones keep using mobile data / cached DNS and never see the portal. */ esp_netif_dns_info_t dns = {0}; dns.ip.type = ESP_IPADDR_TYPE_V4; dns.ip.u_addr.ip4.addr = esp_ip4addr_aton(AP_IP_STR); uint8_t offer_dns = 0x02; /* OFFER_DNS */ esp_netif_dhcps_stop(s_ap_netif); esp_netif_set_dns_info(s_ap_netif, ESP_NETIF_DNS_MAIN, &dns); esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_DOMAIN_NAME_SERVER, &offer_dns, sizeof(offer_dns)); esp_netif_dhcps_start(s_ap_netif); ESP_ERROR_CHECK(esp_wifi_start()); xTaskCreate(dns_server_task, "dns_server", 4096, NULL, 3, NULL); start_portal_webserver(); s_prov_timer = xTimerCreate("prov_timeout", pdMS_TO_TICKS(PROV_TIMEOUT_SEC * 1000), pdFALSE, NULL, prov_timeout_callback); if (s_prov_timer) xTimerStart(s_prov_timer, 0); ESP_LOGI(TAG, "Portal ready: join \"%s\" and open http://%s/", AP_SSID, AP_IP_STR); } /* ------------------------------------------------------------------ */ /* Station mode */ /* ------------------------------------------------------------------ */ static void start_station_mode(const char *ssid, const char *pass) { ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); wifi_config_t cfg = {0}; strncpy((char *)cfg.sta.ssid, ssid, sizeof(cfg.sta.ssid) - 1); strncpy((char *)cfg.sta.password, pass, sizeof(cfg.sta.password) - 1); cfg.sta.threshold.authmode = (strlen(pass) == 0) ? WIFI_AUTH_OPEN : WIFI_AUTH_WPA_PSK; cfg.sta.pmf_cfg.capable = true; cfg.sta.pmf_cfg.required = false; cfg.sta.scan_method = WIFI_FAST_SCAN; if (rtc_hint_valid) { ESP_LOGI(TAG, "Fast connect: trying channel %d first", rtc_hint_channel); cfg.sta.channel = rtc_hint_channel; } ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &cfg)); ESP_ERROR_CHECK(esp_wifi_start()); ESP_LOGI(TAG, "Connecting to \"%s\"...", ssid); } /* ------------------------------------------------------------------ */ /* Events */ /* ------------------------------------------------------------------ */ static void wifi_event_handler(void *arg, esp_event_base_t base, int32_t id, void *data) { if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) { esp_wifi_connect(); } else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_CONNECTED) { wifi_event_sta_connected_t *e = (wifi_event_sta_connected_t *)data; rtc_hint_channel = e->channel; rtc_hint_valid = true; } else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) { xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT); if (s_provisioning || g_wifi_is_shutting_down) return; if (rtc_hint_valid) { /* hint failed: drop it, do a full scan */ rtc_hint_valid = false; wifi_config_t cfg = {0}; esp_wifi_get_config(WIFI_IF_STA, &cfg); cfg.sta.channel = 0; esp_wifi_set_config(WIFI_IF_STA, &cfg); } s_retry++; ESP_LOGW(TAG, "Disconnected, try %d/%d", s_retry, MAX_RECONNECT_TRIES); if (s_retry > MAX_RECONNECT_TRIES) { /* The media servers own port 80 by now, so reboot straight into the portal. */ rtc_force_portal = true; esp_restart(); } else { esp_wifi_connect(); } } else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t *e = (ip_event_got_ip_t *)data; ESP_LOGI(TAG, "Connected! IP: " IPSTR, IP2STR(&e->ip_info.ip)); s_retry = 0; esp_wifi_set_ps(WIFI_PS_NONE); /* needed for low-latency audio/video */ xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); } } /* ------------------------------------------------------------------ */ /* Public API */ /* ------------------------------------------------------------------ */ bool wifi_wait_connected(uint32_t timeout_ms) { if (!s_wifi_event_group) return false; EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT, pdFALSE, pdTRUE, pdMS_TO_TICKS(timeout_ms)); return (bits & WIFI_CONNECTED_BIT) != 0; } bool wifi_is_provisioning(void) { return s_provisioning; } void wifi_start_provisioning_if_needed(void) { /* NVS must be ready before the Wi-Fi driver starts */ esp_err_t err = nvs_flash_init(); if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); err = nvs_flash_init(); } ESP_ERROR_CHECK(err); s_wifi_event_group = xEventGroupCreate(); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); s_sta_netif = esp_netif_create_default_wifi_sta(); s_ap_netif = esp_netif_create_default_wifi_ap(); esp_netif_set_hostname(s_sta_netif, HOSTNAME); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); /* credentials live in our own NVS keys */ ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL)); /* Previous run gave up reconnecting: show the portal so credentials can be fixed */ if (rtc_force_portal) { rtc_force_portal = false; ESP_LOGW(TAG, "Previous boot failed to connect, opening portal"); start_provisioning_mode(); return; } char ssid[33] = {0}, pass[65] = {0}; nvs_handle_t h; if (nvs_open(WIFI_NS, NVS_READONLY, &h) != ESP_OK) { ESP_LOGW(TAG, "No stored Wi-Fi settings"); start_provisioning_mode(); return; } size_t len = sizeof(ssid); err = nvs_get_str(h, WIFI_SSID_KEY, ssid, &len); if (err != ESP_OK || strlen(ssid) == 0) { ESP_LOGW(TAG, "No SSID in NVS"); nvs_close(h); start_provisioning_mode(); return; } len = sizeof(pass); if (nvs_get_str(h, WIFI_PASS_KEY, pass, &len) != ESP_OK) pass[0] = '\0'; nvs_close(h); start_station_mode(ssid, pass); }