wifi.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "freertos/event_groups.h"
  6. #include "esp_wifi.h"
  7. #include "esp_event.h"
  8. #include "esp_log.h"
  9. #include "esp_mac.h"
  10. #include "esp_netif.h"
  11. #include "esp_timer.h"
  12. #include "nvs_flash.h"
  13. #include "wifi.h"
  14. #include "settings.h"
  15. static const char *TAG = "wifi";
  16. // Event group to signal WiFi connection
  17. static EventGroupHandle_t s_wifi_event_group;
  18. #define WIFI_CONNECTED_BIT BIT0
  19. #define WIFI_FAIL_BIT BIT1
  20. // Re-enable AP after this many consecutive failures
  21. #define AP_REENABLE_THRESHOLD 5
  22. // lwIP DHCP hostnames are limited to 31 characters plus the trailing NUL.
  23. #define DHCP_HOSTNAME_MAX_LEN 31
  24. static int s_retry_num = 0;
  25. static esp_netif_t *s_sta_netif = NULL;
  26. static esp_netif_t *s_ap_netif = NULL;
  27. static bool s_wifi_initialized = false;
  28. static bool s_sta_connected = false;
  29. static bool s_bssid_set = false;
  30. static esp_timer_handle_t s_retry_timer = NULL;
  31. // Saved AP config from init, used to re-enable AP without duplication
  32. static wifi_config_t s_ap_config;
  33. static void wifi_select_best_ap(const char *ssid);
  34. static void scan_and_connect_task(void *arg);
  35. static void sanitize_hostname(const char *name, char *out, size_t out_len) {
  36. size_t j = 0;
  37. for (size_t i = 0; name[i] && j < out_len - 1; i++) {
  38. char c = name[i];
  39. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  40. (c >= '0' && c <= '9')) {
  41. out[j++] = c;
  42. } else if (j > 0 && out[j - 1] != '-') {
  43. out[j++] = '-';
  44. }
  45. }
  46. while (j > 0 && out[j - 1] == '-') {
  47. j--;
  48. }
  49. if (j == 0) {
  50. strlcpy(out, "esp32-airplay", out_len);
  51. return;
  52. }
  53. out[j] = '\0';
  54. }
  55. void wifi_set_hostname(const char *device_name) {
  56. if (!s_sta_netif || !device_name) {
  57. return;
  58. }
  59. char hostname[DHCP_HOSTNAME_MAX_LEN + 1];
  60. sanitize_hostname(device_name, hostname, sizeof(hostname));
  61. esp_err_t err = esp_netif_set_hostname(s_sta_netif, hostname);
  62. if (err != ESP_OK) {
  63. ESP_LOGE(TAG, "Failed to set hostname '%s': %s", hostname,
  64. esp_err_to_name(err));
  65. } else {
  66. ESP_LOGI(TAG, "Hostname set to: %s", hostname);
  67. }
  68. }
  69. static void retry_timer_callback(void *arg) {
  70. if (!s_sta_connected) {
  71. ESP_LOGI(TAG, "Retry timer fired, reconnecting (attempt %d)...",
  72. s_retry_num + 1);
  73. esp_wifi_connect();
  74. }
  75. }
  76. static void schedule_retry(void) {
  77. // Exponential backoff: 5s, 10s, 20s, 30s (max)
  78. int delay_s = 5;
  79. if (s_retry_num > AP_REENABLE_THRESHOLD) {
  80. int backoff_count = s_retry_num - AP_REENABLE_THRESHOLD;
  81. delay_s = 5 * (1 << (backoff_count > 3 ? 3 : backoff_count));
  82. if (delay_s > 30) {
  83. delay_s = 30;
  84. }
  85. }
  86. ESP_LOGI(TAG, "Scheduling retry in %d seconds", delay_s);
  87. esp_timer_start_once(s_retry_timer, (uint64_t)delay_s * 1000000);
  88. }
  89. static void enable_ap_mode(void) {
  90. wifi_mode_t mode;
  91. if (esp_wifi_get_mode(&mode) == ESP_OK && mode != WIFI_MODE_APSTA) {
  92. ESP_LOGI(TAG, "Re-enabling AP mode for configuration access");
  93. if (!s_ap_netif) {
  94. s_ap_netif = esp_netif_create_default_wifi_ap();
  95. }
  96. esp_wifi_set_mode(WIFI_MODE_APSTA);
  97. esp_wifi_set_config(WIFI_IF_AP, &s_ap_config);
  98. }
  99. }
  100. static void event_handler(void *arg, esp_event_base_t event_base,
  101. int32_t event_id, void *event_data) {
  102. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
  103. // Defer scan+connect to a separate task — the blocking scan uses too
  104. // much stack to run inside the sys_evt event loop (2–4 KB).
  105. xTaskCreate(scan_and_connect_task, "wifi_scan", 4096, NULL, 3, NULL);
  106. } else if (event_base == WIFI_EVENT &&
  107. event_id == WIFI_EVENT_STA_DISCONNECTED) {
  108. s_sta_connected = false;
  109. wifi_event_sta_disconnected_t *disconnected =
  110. (wifi_event_sta_disconnected_t *)event_data;
  111. ESP_LOGI(TAG, "Disconnected from AP, reason: %d", disconnected->reason);
  112. s_retry_num++;
  113. if (s_retry_num < AP_REENABLE_THRESHOLD) {
  114. // Fast retries — reconnect immediately
  115. ESP_LOGI(TAG, "Retrying connection (%d/%d)...", s_retry_num,
  116. AP_REENABLE_THRESHOLD);
  117. esp_wifi_connect();
  118. } else {
  119. if (s_retry_num == AP_REENABLE_THRESHOLD) {
  120. xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
  121. ESP_LOGW(TAG,
  122. "WiFi connection failed after %d attempts, switching to "
  123. "backoff retries",
  124. AP_REENABLE_THRESHOLD);
  125. enable_ap_mode();
  126. }
  127. // Delayed retries with backoff
  128. schedule_retry();
  129. }
  130. } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
  131. ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
  132. ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
  133. s_retry_num = 0;
  134. s_sta_connected = true;
  135. xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
  136. // Disable AP mode when STA connects
  137. wifi_mode_t mode;
  138. if (esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_APSTA) {
  139. ESP_LOGI(TAG, "STA connected, disabling AP mode");
  140. esp_wifi_set_mode(WIFI_MODE_STA);
  141. }
  142. } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_START) {
  143. ESP_LOGI(TAG, "AP started");
  144. }
  145. }
  146. // One-shot task: scan for best AP then connect — runs outside the event loop
  147. // to avoid overflowing the sys_evt stack.
  148. static void scan_and_connect_task(void *arg) {
  149. wifi_config_t cfg;
  150. if (esp_wifi_get_config(WIFI_IF_STA, &cfg) == ESP_OK &&
  151. strlen((char *)cfg.sta.ssid) > 0) {
  152. wifi_select_best_ap((char *)cfg.sta.ssid);
  153. }
  154. esp_wifi_connect();
  155. vTaskDelete(NULL);
  156. }
  157. // Scan for the best AP matching our SSID and set its BSSID in the STA config
  158. static void wifi_select_best_ap(const char *ssid) {
  159. wifi_scan_config_t scan_config = {
  160. .ssid = (uint8_t *)ssid,
  161. .bssid = NULL,
  162. .channel = 0,
  163. .show_hidden = false,
  164. .scan_type = WIFI_SCAN_TYPE_ACTIVE,
  165. .scan_time = {.active = {.min = 0,
  166. .max = 0}}, // 0, 0 needed for BT co-exist
  167. };
  168. esp_err_t err = esp_wifi_scan_start(&scan_config, true);
  169. if (err != ESP_OK) {
  170. ESP_LOGW(TAG, "Best-AP scan failed: %s", esp_err_to_name(err));
  171. return;
  172. }
  173. uint16_t ap_count = 0;
  174. esp_wifi_scan_get_ap_num(&ap_count);
  175. if (ap_count == 0) {
  176. ESP_LOGW(TAG, "Best-AP scan: no APs found for SSID %s", ssid);
  177. esp_wifi_scan_get_ap_records(&ap_count, NULL);
  178. return;
  179. }
  180. wifi_ap_record_t *ap_list = malloc(sizeof(wifi_ap_record_t) * ap_count);
  181. if (!ap_list) {
  182. esp_wifi_scan_get_ap_records(&ap_count, NULL);
  183. return;
  184. }
  185. esp_wifi_scan_get_ap_records(&ap_count, ap_list);
  186. // Find AP with strongest signal
  187. int best_idx = 0;
  188. for (int i = 1; i < ap_count; i++) {
  189. if (ap_list[i].rssi > ap_list[best_idx].rssi) {
  190. best_idx = i;
  191. }
  192. }
  193. ESP_LOGI(TAG, "Found %d APs for SSID '%s', best: " MACSTR " (rssi=%d, ch=%d)",
  194. ap_count, ssid, MAC2STR(ap_list[best_idx].bssid),
  195. ap_list[best_idx].rssi, ap_list[best_idx].primary);
  196. for (int i = 0; i < ap_count; i++) {
  197. if (i != best_idx) {
  198. ESP_LOGI(TAG, " Other AP: " MACSTR " (rssi=%d, ch=%d)",
  199. MAC2STR(ap_list[i].bssid), ap_list[i].rssi, ap_list[i].primary);
  200. }
  201. }
  202. // Set BSSID in the STA config to lock to the best AP
  203. wifi_config_t sta_cfg;
  204. esp_wifi_get_config(WIFI_IF_STA, &sta_cfg);
  205. memcpy(sta_cfg.sta.bssid, ap_list[best_idx].bssid, 6);
  206. sta_cfg.sta.bssid_set = true;
  207. esp_wifi_set_config(WIFI_IF_STA, &sta_cfg);
  208. s_bssid_set = true;
  209. free(ap_list);
  210. }
  211. static void wifi_init_base(void) {
  212. if (s_wifi_initialized) {
  213. return;
  214. }
  215. s_wifi_event_group = xEventGroupCreate();
  216. esp_err_t ret = esp_netif_init();
  217. if (ret != ESP_OK && ret != ESP_ERR_INVALID_STATE) {
  218. ESP_ERROR_CHECK(ret);
  219. }
  220. // Create event loop if it doesn't exist
  221. ret = esp_event_loop_create_default();
  222. if (ret != ESP_OK && ret != ESP_ERR_INVALID_STATE) {
  223. ESP_ERROR_CHECK(ret);
  224. }
  225. esp_event_handler_instance_t instance_any_id;
  226. esp_event_handler_instance_t instance_got_ip;
  227. ESP_ERROR_CHECK(esp_event_handler_instance_register(
  228. WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &instance_any_id));
  229. ESP_ERROR_CHECK(esp_event_handler_instance_register(
  230. IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, &instance_got_ip));
  231. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  232. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  233. ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
  234. // Create one-shot retry timer (no background task needed)
  235. const esp_timer_create_args_t timer_args = {
  236. .callback = retry_timer_callback,
  237. .name = "wifi_retry",
  238. };
  239. ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer));
  240. s_wifi_initialized = true;
  241. }
  242. void wifi_init_apsta(const char *ap_ssid, const char *ap_password) {
  243. wifi_init_base();
  244. if (!s_sta_netif) {
  245. s_sta_netif = esp_netif_create_default_wifi_sta();
  246. char dev_name[65];
  247. settings_get_device_name(dev_name, sizeof(dev_name));
  248. wifi_set_hostname(dev_name);
  249. }
  250. if (!s_ap_netif) {
  251. s_ap_netif = esp_netif_create_default_wifi_ap();
  252. }
  253. // Configure STA
  254. char ssid[33] = {0};
  255. char password[65] = {0};
  256. bool has_credentials = false;
  257. if (settings_get_wifi_ssid(ssid, sizeof(ssid)) == ESP_OK &&
  258. settings_get_wifi_password(password, sizeof(password)) == ESP_OK &&
  259. strlen(ssid) > 0) {
  260. has_credentials = true;
  261. }
  262. wifi_config_t sta_config = {0};
  263. strlcpy((char *)sta_config.sta.ssid, ssid, sizeof(sta_config.sta.ssid));
  264. strlcpy((char *)sta_config.sta.password, password,
  265. sizeof(sta_config.sta.password));
  266. sta_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
  267. // Configure AP and save for later re-enable
  268. const char *default_ssid = ap_ssid ? ap_ssid : CONFIG_DEFAULT_AP_SSID;
  269. const char *default_password =
  270. ap_password ? ap_password : CONFIG_DEFAULT_AP_PASSWORD;
  271. memset(&s_ap_config, 0, sizeof(s_ap_config));
  272. strncpy((char *)s_ap_config.ap.ssid, default_ssid,
  273. sizeof(s_ap_config.ap.ssid) - 1);
  274. s_ap_config.ap.ssid_len = strlen(default_ssid);
  275. s_ap_config.ap.channel = 1;
  276. s_ap_config.ap.max_connection = 4;
  277. if (strlen(default_password) == 0) {
  278. s_ap_config.ap.authmode = WIFI_AUTH_OPEN;
  279. } else {
  280. strncpy((char *)s_ap_config.ap.password, default_password,
  281. sizeof(s_ap_config.ap.password) - 1);
  282. s_ap_config.ap.authmode = WIFI_AUTH_WPA2_PSK;
  283. }
  284. s_retry_num = 0;
  285. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
  286. ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &sta_config));
  287. ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &s_ap_config));
  288. ESP_ERROR_CHECK(esp_wifi_start());
  289. ESP_LOGI(TAG, "AP+STA mode started: AP SSID=%s", default_ssid);
  290. if (has_credentials) {
  291. ESP_LOGI(TAG, "Connecting to WiFi: %s", ssid);
  292. }
  293. }
  294. bool wifi_wait_connected(uint32_t timeout_ms) {
  295. if (!s_wifi_event_group) {
  296. return false;
  297. }
  298. TickType_t timeout_ticks =
  299. timeout_ms > 0 ? pdMS_TO_TICKS(timeout_ms) : portMAX_DELAY;
  300. EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
  301. WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
  302. pdFALSE, pdFALSE, timeout_ticks);
  303. if (bits & WIFI_CONNECTED_BIT) {
  304. return true;
  305. }
  306. if (bits & WIFI_FAIL_BIT) {
  307. ESP_LOGE(TAG, "Failed to connect to WiFi");
  308. }
  309. return false;
  310. }
  311. void wifi_get_mac_str(char *mac_str, size_t len) {
  312. uint8_t mac[6];
  313. esp_read_mac(mac, ESP_MAC_WIFI_STA);
  314. snprintf(mac_str, len, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1],
  315. mac[2], mac[3], mac[4], mac[5]);
  316. }
  317. bool wifi_is_connected(void) {
  318. return s_sta_connected;
  319. }
  320. esp_err_t wifi_get_ip_str(char *ip_str, size_t len) {
  321. if (!s_sta_netif || !ip_str || len == 0) {
  322. return ESP_ERR_INVALID_ARG;
  323. }
  324. esp_netif_ip_info_t ip_info;
  325. esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip_info);
  326. if (err == ESP_OK) {
  327. snprintf(ip_str, len, IPSTR, IP2STR(&ip_info.ip));
  328. }
  329. return err;
  330. }
  331. esp_err_t wifi_scan(wifi_ap_record_t **ap_list, uint16_t *ap_count) {
  332. if (!ap_list || !ap_count) {
  333. return ESP_ERR_INVALID_ARG;
  334. }
  335. // Stop any pending retry and disconnect cleanly
  336. esp_timer_stop(s_retry_timer);
  337. esp_wifi_disconnect();
  338. vTaskDelay(pdMS_TO_TICKS(100));
  339. // Clear BSSID lock so next connect can use a fresh scan result
  340. if (s_bssid_set) {
  341. wifi_config_t sta_cfg;
  342. if (esp_wifi_get_config(WIFI_IF_STA, &sta_cfg) == ESP_OK) {
  343. memset(sta_cfg.sta.bssid, 0, sizeof(sta_cfg.sta.bssid));
  344. sta_cfg.sta.bssid_set = false;
  345. esp_wifi_set_config(WIFI_IF_STA, &sta_cfg);
  346. }
  347. s_bssid_set = false;
  348. }
  349. wifi_scan_config_t scan_config = {
  350. .ssid = NULL,
  351. .bssid = NULL,
  352. .channel = 0,
  353. .show_hidden = true,
  354. };
  355. esp_err_t err = esp_wifi_scan_start(&scan_config, true);
  356. if (err != ESP_OK) {
  357. ESP_LOGE(TAG, "WiFi scan failed: %s", esp_err_to_name(err));
  358. return err;
  359. }
  360. uint16_t number = 0;
  361. err = esp_wifi_scan_get_ap_num(&number);
  362. if (err != ESP_OK) {
  363. ESP_LOGE(TAG, "Failed to get AP count: %s", esp_err_to_name(err));
  364. return err;
  365. }
  366. if (number == 0) {
  367. *ap_list = NULL;
  368. *ap_count = 0;
  369. return ESP_OK;
  370. }
  371. wifi_ap_record_t *aps = malloc(sizeof(wifi_ap_record_t) * number);
  372. if (!aps) {
  373. return ESP_ERR_NO_MEM;
  374. }
  375. err = esp_wifi_scan_get_ap_records(&number, aps);
  376. if (err != ESP_OK) {
  377. ESP_LOGE(TAG, "Failed to get AP records: %s", esp_err_to_name(err));
  378. free(aps);
  379. return err;
  380. }
  381. *ap_list = aps;
  382. *ap_count = number;
  383. return ESP_OK;
  384. }
  385. void wifi_stop(void) {
  386. if (s_wifi_initialized) {
  387. esp_timer_stop(s_retry_timer);
  388. esp_wifi_stop();
  389. esp_wifi_deinit();
  390. s_wifi_initialized = false;
  391. s_sta_connected = false;
  392. s_retry_num = 0;
  393. if (s_wifi_event_group) {
  394. xEventGroupClearBits(s_wifi_event_group,
  395. WIFI_CONNECTED_BIT | WIFI_FAIL_BIT);
  396. }
  397. }
  398. }