diff --git a/main/audio.c b/main/audio.c index 2294d20..ceb2e79 100644 --- a/main/audio.c +++ b/main/audio.c @@ -1,17 +1,7 @@ -#include "sdkconfig.h" -#include -#include -#include -#include -#include #include #include -#include "driver/gpio.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" #include "driver/i2c_master.h" #include "driver/i2s_std.h" -#include "esp_io_expander.h" #include "esp_codec_dev.h" #include "esp_codec_dev_defaults.h" #include "audio.h" @@ -28,82 +18,6 @@ static i2s_chan_handle_t rx_chan = NULL; static StreamBufferHandle_t s_mic_sb; static volatile bool s_mic_on = false; -// esp_err_t audio_ws_handler(httpd_req_t *req) -// { -// if (req->method == HTTP_GET) { // WebSocket handshake -// s_audio_hd = req->handle; -// s_audio_fd = httpd_req_to_sockfd(req); -// ESP_LOGI("AUDIO", "WS client connected, fd=%d", s_audio_fd); -// return ESP_OK; -// } - -// if (req->method == HTTP_GET) { -// s_audio_hd = req->handle; -// s_audio_fd = httpd_req_to_sockfd(req); -// int one = 1; -// setsockopt(s_audio_fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); -// return ESP_OK; -// } - -// static int16_t in[2048]; // mono from browser (max 4096 bytes) -// // static int16_t st[4096]; // stereo for the codec - -// httpd_ws_frame_t pkt = {0}; -// esp_err_t ret = httpd_ws_recv_frame(req, &pkt, 0); -// if (ret != ESP_OK) return ret; -// if (pkt.type == HTTPD_WS_TYPE_CLOSE) { s_audio_fd = -1; return ESP_OK; } - -// if (pkt.type == HTTPD_WS_TYPE_TEXT) { // control messages -// char txt[16] = {0}; -// if (pkt.len >= sizeof(txt)) return ESP_FAIL; -// pkt.payload = (uint8_t *)txt; -// ret = httpd_ws_recv_frame(req, &pkt, pkt.len); -// if (ret != ESP_OK) return ret; -// int v; -// if (sscanf(txt, "VOL:%d", &v) == 1) { -// if (v < 0) v = 0; -// if (v > 100) v = 100; -// esp_codec_dev_set_out_vol(spk_dev, v); -// } -// return ESP_OK; -// } - -// if (pkt.len == 0 || pkt.len > sizeof(in)) return ESP_FAIL; - -// pkt.payload = (uint8_t *)in; -// ret = httpd_ws_recv_frame(req, &pkt, pkt.len); -// if (ret != ESP_OK) return ret; - -// int n = pkt.len / 2; -// size_t len = pkt.len & ~1u; -// if (xStreamBufferSpacesAvailable(s_play_sb) >= len) -// xStreamBufferSend(s_play_sb, in, len, 0); // never blocks -// // else: buffer is full, drop this packet to keep latency bounded -// return ESP_OK; -// // esp_codec_dev_write(spk_dev, st, n * 4); -// // return ESP_OK; -// } - -// httpd_handle_t start_audio_server(void) { -// httpd_config_t config = HTTPD_DEFAULT_CONFIG(); -// config.server_port = 81; -// config.ctrl_port = 32769; -// config.max_open_sockets = 3; - -// httpd_handle_t audio_server = NULL; -// if (httpd_start(&audio_server, &config) == ESP_OK) { -// httpd_uri_t uri_audio_ws = { -// .uri = "/audio", -// .method = HTTP_GET, -// .handler = audio_ws_handler, -// .is_websocket = true -// }; -// httpd_register_uri_handler(audio_server, &uri_audio_ws); -// ESP_LOGI("AUDIO", "Audio WebSocket Server started on port 81"); -// } -// return audio_server; -// } - #define MIC_BOOST 4 void mic_task(void *arg) @@ -131,50 +45,6 @@ void mic_task(void *arg) } } -// void mic_task(void *arg) -// { -// static int16_t st[512]; // 512 stereo frames -// static int16_t mono[256]; -// int blocks = 0, sendFail = 0, pkL = 0, pkR = 0; - -// while (1) { -// int rd = esp_codec_dev_read(mic_dev, st, sizeof(st)); -// if (rd != ESP_CODEC_DEV_OK) { -// ESP_LOGE("MIC", "read error %d", rd); -// vTaskDelay(pdMS_TO_TICKS(50)); -// continue; -// } - -// long eL = 0, eR = 0; -// for (int i = 0; i < 256; i++) { -// int l = abs(st[2*i]), r = abs(st[2*i+1]); -// eL += l; eR += r; -// if (l > pkL) pkL = l; -// if (r > pkR) pkR = r; -// } -// int useRight = eR > eL; - -// if (s_audio_fd >= 0) { -// for (int i = 0; i < 256; i++) { -// int v = (useRight ? st[2*i+1] : st[2*i]) * MIC_BOOST; -// if (v > 32767) v = 32767; -// if (v < -32768) v = -32768; -// mono[i] = (int16_t)v; -// } -// httpd_ws_frame_t f = { .payload = (uint8_t *)mono, .len = sizeof(mono), -// .type = HTTPD_WS_TYPE_BINARY }; -// if (httpd_ws_send_frame_async(s_audio_hd, s_audio_fd, &f) != ESP_OK) -// sendFail++; -// } - -// if (++blocks >= 62) { // about once per second -// ESP_LOGI("MIC", "peakL=%d peakR=%d client_fd=%d sendFail=%d", -// pkL, pkR, (int)s_audio_fd, sendFail); -// blocks = 0; pkL = pkR = 0; sendFail = 0; -// } -// } -// } - static void play_task(void *arg) { static int16_t mono[256]; @@ -189,7 +59,6 @@ static void play_task(void *arg) } } - esp_err_t audio_init(i2c_master_bus_handle_t bus) { // 2) One I2S port, full duplex (shared clocks) @@ -262,12 +131,27 @@ static void cors(httpd_req_t *req) { } // GET /mic : endless raw PCM stream (16 kHz, 16-bit, mono) +// 44-byte WAV header: PCM, mono, 16 kHz, 16-bit, unknown length +static const uint8_t WAV_HDR[44] = { + 'R','I','F','F', 0xFF,0xFF,0xFF,0xFF, 'W','A','V','E', + 'f','m','t',' ', 16,0,0,0, + 1,0, // PCM + 1,0, // mono + 0x80,0x3E,0,0, // 16000 Hz + 0x00,0x7D,0,0, // byte rate 32000 + 2,0, // block align + 16,0, // bits per sample + 'd','a','t','a', 0xFF,0xFF,0xFF,0xFF +}; + static esp_err_t mic_handler(httpd_req_t *req) { static int16_t buf[256]; cors(req); - httpd_resp_set_type(req, "application/octet-stream"); + httpd_resp_set_type(req, "audio/wav"); xStreamBufferReset(s_mic_sb); + if (httpd_resp_send_chunk(req, (const char *)WAV_HDR, sizeof(WAV_HDR)) != ESP_OK) + return ESP_FAIL; s_mic_on = true; esp_err_t res = ESP_OK; @@ -275,7 +159,7 @@ static esp_err_t mic_handler(httpd_req_t *req) size_t n = xStreamBufferReceive(s_mic_sb, buf, sizeof(buf), pdMS_TO_TICKS(200)); if (!n) continue; res = httpd_resp_send_chunk(req, (const char *)buf, n); - if (res != ESP_OK) break; // client left + if (res != ESP_OK) break; } s_mic_on = false; return res; @@ -341,4 +225,4 @@ void start_audio_server(void) httpd_register_uri_handler(h, &s); httpd_register_uri_handler(h, &v); } -} \ No newline at end of file +} diff --git a/main/audio.h b/main/audio.h index e5aea6d..2c79133 100644 --- a/main/audio.h +++ b/main/audio.h @@ -1,5 +1,4 @@ #include "esp_http_server.h" -#include "lwip/sockets.h" #define I2S_MCLK GPIO_NUM_10 #define I2S_BCLK GPIO_NUM_11 diff --git a/main/board.h b/main/board.h index 918f5ff..3691cdb 100644 --- a/main/board.h +++ b/main/board.h @@ -1,4 +1,12 @@ #include "driver/i2c_master.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include +#include "sdkconfig.h" +#include +#include +#include "esp_http_server.h" // support IDF 5.x #ifndef portTICK_RATE_MS @@ -16,3 +24,6 @@ esp_err_t audio_init(i2c_master_bus_handle_t bus); void mic_task(void *arg); void start_wifi_and_server(void); void start_audio_server(void); +void start_camera_server(void); +void wifi_start_provisioning_if_needed(void); +bool wifi_wait_connected(uint32_t timeout_ms); \ No newline at end of file diff --git a/main/camera.c b/main/camera.c index 4d923fc..2cf4c13 100644 --- a/main/camera.c +++ b/main/camera.c @@ -1,16 +1,5 @@ -#include "sdkconfig.h" -#include -#include #include "esp_http_server.h" -#include -#include -#include "driver/gpio.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" #include "img_converters.h" -#include "driver/i2c_master.h" -#include "esp_io_expander.h" -#include "freertos/stream_buffer.h" #include "esp_camera.h" #include "camera_pinout.h" #include "esp32_s3_cam_ovxxxx.h" @@ -75,6 +64,18 @@ esp_err_t init_camera(void) return ESP_OK; } + void start_camera_server(void) +{ + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + httpd_handle_t server = NULL; + if (httpd_start(&server, &config) == ESP_OK) { + httpd_uri_t uri_capture = { .uri = "/pic", .method = HTTP_GET, .handler = capture_handler }; + httpd_uri_t uri_stream = { .uri = "/stream", .method = HTTP_GET, .handler = stream_handler }; + httpd_register_uri_handler(server, &uri_capture); + httpd_register_uri_handler(server, &uri_stream); + } +} + #if defined(CONFIG_CAMERA_AF_SUPPORT) && CONFIG_CAMERA_AF_SUPPORT static void maybe_init_autofocus(void) { diff --git a/main/main.c b/main/main.c index 68f9cb3..78e31b7 100644 --- a/main/main.c +++ b/main/main.c @@ -1,495 +1,7 @@ -#include "sdkconfig.h" -#include -#include -#include -#include -#include -#include -#include -#include "driver/gpio.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "esp_wifi.h" -#include "nvs_flash.h" -#include "esp_netif.h" -#include "esp_http_server.h" -#include "img_converters.h" #include "driver/i2c_master.h" -#include "driver/i2s_std.h" -#include "esp_io_expander.h" -#include "esp_codec_dev.h" -#include "esp_codec_dev_defaults.h" -#include "freertos/stream_buffer.h" -#include "lwip/sockets.h" -#include #include "board.h" - -// static StreamBufferHandle_t s_play_sb; // mono 16-bit PCM from the browser - -// // support IDF 5.x -// #ifndef portTICK_RATE_MS -// #define portTICK_RATE_MS portTICK_PERIOD_MS -// #endif - -// #include "esp_camera.h" - -// #if defined(CONFIG_CAMERA_AF_SUPPORT) && CONFIG_CAMERA_AF_SUPPORT -// #include "esp_camera_af.h" -// #endif - -// #define BOARD_WAVESHARE_ESP32S3 1 - -// #include "camera_pinout.h" #include "esp32_s3_cam_ovxxxx.h" -// static const char *TAG = "example:take_picture"; -// // FILL THESE IN FROM YOUR SCHEMATIC -// #define I2S_MCLK GPIO_NUM_10 -// #define I2S_BCLK GPIO_NUM_11 -// #define I2S_WS GPIO_NUM_12 -// #define I2S_DOUT GPIO_NUM_14 // ESP -> ES8311 DSDIN -// #define I2S_DIN GPIO_NUM_13 // ES7210 SDOUT -> ESP -// #define SR 16000 - -// static esp_codec_dev_handle_t spk_dev, mic_dev; - -// #define PART_BOUNDARY "123456789000000000000987654321" -// static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; -// static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; -// static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n"; - -// #if ESP_CAMERA_SUPPORTED -// static camera_config_t camera_config = { -// .pin_pwdn = CAM_PIN_PWDN, -// .pin_reset = CAM_PIN_RESET, -// .pin_xclk = CAM_PIN_XCLK, -// .pin_sccb_sda = -1, -// .pin_sccb_scl = -1, - -// .pin_d7 = CAM_PIN_D7, -// .pin_d6 = CAM_PIN_D6, -// .pin_d5 = CAM_PIN_D5, -// .pin_d4 = CAM_PIN_D4, -// .pin_d3 = CAM_PIN_D3, -// .pin_d2 = CAM_PIN_D2, -// .pin_d1 = CAM_PIN_D1, -// .pin_d0 = CAM_PIN_D0, -// .pin_vsync = CAM_PIN_VSYNC, -// .pin_href = CAM_PIN_HREF, -// .pin_pclk = CAM_PIN_PCLK, - -// //XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental) -// .xclk_freq_hz = 10000000, -// .ledc_timer = LEDC_TIMER_0, -// .ledc_channel = LEDC_CHANNEL_0, - -// .pixel_format = PIXFORMAT_YUV422, //YUV422,GRAYSCALE,RGB565,JPEG -// .frame_size = FRAMESIZE_QVGA, //QQVGA-UXGA, For ESP32, do not use sizes above QVGA when not JPEG. The performance of the ESP32-S series has improved a lot, but JPEG mode always gives better frame rates. - -// .jpeg_quality = 12, //0-63, for OV series camera sensors, lower number means higher quality -// .fb_count = 2, //When jpeg mode is used, if fb_count more than one, the driver will work in continuous mode. -// .fb_location = CAMERA_FB_IN_PSRAM, -// // .grab_mode = CAMERA_GRAB_WHEN_EMPTY, -// .grab_mode = CAMERA_GRAB_LATEST, -// }; - -// static esp_err_t init_camera(void) -// { -// //initialize the camera -// esp_err_t err = esp_camera_init(&camera_config); -// if (err != ESP_OK) -// { -// ESP_LOGE(TAG, "Camera Init Failed"); -// return err; -// } - -// return ESP_OK; -// } - -// #if defined(CONFIG_CAMERA_AF_SUPPORT) && CONFIG_CAMERA_AF_SUPPORT -// static void maybe_init_autofocus(void) -// { -// sensor_t *s = esp_camera_sensor_get(); -// if (!s) { -// ESP_LOGW(TAG, "AF: no sensor handle"); -// return; -// } - -// if (!esp_camera_af_is_supported(s)) { -// ESP_LOGI(TAG, "AF: not supported by this sensor"); -// return; -// } - -// esp_camera_af_config_t af_cfg = { -// .mode = ESP_CAMERA_AF_MODE_AUTO, -// .timeout_ms = CONFIG_CAMERA_AF_DEFAULT_TIMEOUT_MS, -// }; - -// esp_err_t ret = esp_camera_af_init(s, &af_cfg); -// if (ret != ESP_OK) { -// ESP_LOGW(TAG, "AF init failed: %s", esp_err_to_name(ret)); -// return; -// } - -// ESP_LOGI(TAG, "AF initialized (AUTO mode)"); -// } -// #endif -// #endif - -// static esp_err_t capture_handler(httpd_req_t *req) { -// camera_fb_t *fb = esp_camera_fb_get(); -// if (!fb) { -// ESP_LOGE(TAG, "Camera capture failed"); -// httpd_resp_send_500(req); -// return ESP_FAIL; -// } - -// uint8_t *jpeg_buf = NULL; -// size_t jpeg_len = 0; - -// bool jpeg_converted = frame2jpg(fb, 50, &jpeg_buf, &jpeg_len); - -// esp_camera_fb_return(fb); - -// if (!jpeg_converted) { -// ESP_LOGE(TAG, "JPEG compression failed"); -// httpd_resp_send_500(req); -// return ESP_FAIL; -// } - -// httpd_resp_set_type(req, "image/jpeg"); -// httpd_resp_send(req, (const char *)jpeg_buf, jpeg_len); - -// free(jpeg_buf); - -// return ESP_OK; -// } - -// static esp_err_t stream_handler(httpd_req_t *req) { -// camera_fb_t * fb = NULL; -// esp_err_t res = ESP_OK; -// size_t _jpg_buf_len = 0; -// uint8_t * _jpg_buf = NULL; -// char * part_buf[64]; - -// res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE); -// if (res != ESP_OK) { -// return res; -// } - -// while(true) { -// fb = esp_camera_fb_get(); -// if (!fb) { -// ESP_LOGE(TAG, "Camera capture failed"); -// res = ESP_FAIL; -// break; -// } - -// bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len); -// esp_camera_fb_return(fb); - -// if (!jpeg_converted) { -// ESP_LOGE(TAG, "JPEG compression failed"); -// res = ESP_FAIL; -// break; -// } - -// if (res == ESP_OK) { -// res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY)); -// } -// if (res == ESP_OK) { -// size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len); -// res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); -// } -// if (res == ESP_OK) { -// res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); -// } - -// free(_jpg_buf); -// _jpg_buf = NULL; - -// if (res != ESP_OK) { -// break; -// } -// vTaskDelay(1); -// } -// return res; -// } - -// static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { -// if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { -// esp_wifi_connect(); -// } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { -// ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying..."); -// esp_wifi_connect(); -// } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { -// ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; -// ESP_LOGI(TAG, "SUCCESS! Got IP: " IPSTR, IP2STR(&event->ip_info.ip)); -// } -// } - -// static i2s_chan_handle_t tx_chan = NULL; -// static i2s_chan_handle_t rx_chan = NULL; -// static volatile int s_audio_fd = -1; -// static httpd_handle_t s_audio_hd = NULL; - -// static esp_err_t audio_ws_handler(httpd_req_t *req) -// { -// if (req->method == HTTP_GET) { // WebSocket handshake -// s_audio_hd = req->handle; -// s_audio_fd = httpd_req_to_sockfd(req); -// ESP_LOGI("AUDIO", "WS client connected, fd=%d", s_audio_fd); -// return ESP_OK; -// } - -// if (req->method == HTTP_GET) { -// s_audio_hd = req->handle; -// s_audio_fd = httpd_req_to_sockfd(req); -// int one = 1; -// setsockopt(s_audio_fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); -// return ESP_OK; -// } - -// static int16_t in[2048]; // mono from browser (max 4096 bytes) -// // static int16_t st[4096]; // stereo for the codec - -// httpd_ws_frame_t pkt = {0}; -// esp_err_t ret = httpd_ws_recv_frame(req, &pkt, 0); -// if (ret != ESP_OK) return ret; -// if (pkt.type == HTTPD_WS_TYPE_CLOSE) { s_audio_fd = -1; return ESP_OK; } - -// if (pkt.type == HTTPD_WS_TYPE_TEXT) { // control messages -// char txt[16] = {0}; -// if (pkt.len >= sizeof(txt)) return ESP_FAIL; -// pkt.payload = (uint8_t *)txt; -// ret = httpd_ws_recv_frame(req, &pkt, pkt.len); -// if (ret != ESP_OK) return ret; -// int v; -// if (sscanf(txt, "VOL:%d", &v) == 1) { -// if (v < 0) v = 0; -// if (v > 100) v = 100; -// esp_codec_dev_set_out_vol(spk_dev, v); -// } -// return ESP_OK; -// } - -// if (pkt.len == 0 || pkt.len > sizeof(in)) return ESP_FAIL; - -// pkt.payload = (uint8_t *)in; -// ret = httpd_ws_recv_frame(req, &pkt, pkt.len); -// if (ret != ESP_OK) return ret; - -// int n = pkt.len / 2; -// size_t len = pkt.len & ~1u; -// if (xStreamBufferSpacesAvailable(s_play_sb) >= len) -// xStreamBufferSend(s_play_sb, in, len, 0); // never blocks -// // else: buffer is full, drop this packet to keep latency bounded -// return ESP_OK; -// // esp_codec_dev_write(spk_dev, st, n * 4); -// // return ESP_OK; -// } - -// static void play_task(void *arg) -// { -// static int16_t mono[256]; -// static int16_t st[512]; -// while (1) { -// size_t got = xStreamBufferReceive(s_play_sb, mono, sizeof(mono), pdMS_TO_TICKS(50)); -// got &= ~1u; // whole samples only -// if (!got) continue; -// int n = got / 2; -// for (int i = 0; i < n; i++) { st[2*i] = mono[i]; st[2*i+1] = mono[i]; } -// esp_codec_dev_write(spk_dev, st, n * 4); -// } -// } - -// static httpd_handle_t start_audio_server(void) { -// httpd_config_t config = HTTPD_DEFAULT_CONFIG(); -// config.server_port = 81; -// config.ctrl_port = 32769; -// config.max_open_sockets = 3; - -// httpd_handle_t audio_server = NULL; -// if (httpd_start(&audio_server, &config) == ESP_OK) { -// httpd_uri_t uri_audio_ws = { -// .uri = "/audio", -// .method = HTTP_GET, -// .handler = audio_ws_handler, -// .is_websocket = true -// }; -// httpd_register_uri_handler(audio_server, &uri_audio_ws); -// ESP_LOGI("AUDIO", "Audio WebSocket Server started on port 81"); -// } -// return audio_server; -// } - -// static void start_wifi_and_server(void) { -// esp_err_t ret = nvs_flash_init(); -// if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { -// nvs_flash_erase(); -// nvs_flash_init(); -// } -// esp_netif_init(); -// esp_event_loop_create_default(); -// esp_netif_create_default_wifi_sta(); - -// wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); -// esp_wifi_init(&cfg); - -// wifi_config_t wifi_config = { -// .sta = { -// .ssid = "viratak-lte", -// .password = "mydlinkviratak", -// }, -// }; -// esp_wifi_set_mode(WIFI_MODE_STA); -// esp_wifi_set_config(WIFI_IF_STA, &wifi_config); -// esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL); -// esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL); -// esp_wifi_start(); -// esp_wifi_set_ps(WIFI_PS_NONE); -// esp_wifi_connect(); - -// httpd_config_t config = HTTPD_DEFAULT_CONFIG(); -// httpd_handle_t server = NULL; -// if (httpd_start(&server, &config) == ESP_OK) { -// httpd_uri_t uri_capture = { -// .uri = "/pic", -// .method = HTTP_GET, -// .handler = capture_handler, -// .user_ctx = NULL -// }; -// httpd_register_uri_handler(server, &uri_capture); - -// httpd_uri_t uri_stream = { -// .uri = "/stream", -// .method = HTTP_GET, -// .handler = stream_handler, -// .user_ctx = NULL -// }; -// httpd_register_uri_handler(server, &uri_stream); - -// httpd_uri_t uri_audio_ws = { -// .uri = "/audio", -// .method = HTTP_GET, -// .handler = audio_ws_handler, -// .is_websocket = true -// }; -// httpd_register_uri_handler(server, &uri_audio_ws); -// } -// } - -// esp_err_t audio_init(i2c_master_bus_handle_t bus) -// { -// // 2) One I2S port, full duplex (shared clocks) -// i2s_chan_config_t cc = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); -// cc.auto_clear = true; -// cc.dma_desc_num = 4; -// cc.dma_frame_num = 160; // about 40 ms total instead of about 90 ms -// ESP_ERROR_CHECK(i2s_new_channel(&cc, &tx_chan, &rx_chan)); - -// i2s_std_config_t std = { -// .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(SR), -// .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, -// I2S_SLOT_MODE_STEREO), -// .gpio_cfg = { .mclk = I2S_MCLK, .bclk = I2S_BCLK, .ws = I2S_WS, -// .dout = I2S_DOUT, .din = I2S_DIN }, -// }; -// ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_chan, &std)); -// ESP_ERROR_CHECK(i2s_channel_init_std_mode(rx_chan, &std)); -// ESP_ERROR_CHECK(i2s_channel_enable(tx_chan)); -// ESP_ERROR_CHECK(i2s_channel_enable(rx_chan)); - -// audio_codec_i2s_cfg_t i2s_cfg = { .port = I2S_NUM_0, -// .tx_handle = tx_chan, .rx_handle = rx_chan }; -// const audio_codec_data_if_t *data_if = audio_codec_new_i2s_data(&i2s_cfg); -// const audio_codec_gpio_if_t *gpio_if = audio_codec_new_gpio(); - -// // 3) Speaker: ES8311 -// audio_codec_i2c_cfg_t out_i2c = { .port = 0, .addr = ES8311_CODEC_DEFAULT_ADDR, -// .bus_handle = bus }; -// es8311_codec_cfg_t es8311_cfg = { -// .ctrl_if = audio_codec_new_i2c_ctrl(&out_i2c), -// .gpio_if = gpio_if, -// .codec_mode = ESP_CODEC_DEV_TYPE_OUT, -// .pa_pin = -1, // amp is on the IO expander, handled above -// .use_mclk = true, -// }; -// esp_codec_dev_cfg_t spk_cfg = { .dev_type = ESP_CODEC_DEV_TYPE_OUT, -// .codec_if = es8311_codec_new(&es8311_cfg), .data_if = data_if }; -// spk_dev = esp_codec_dev_new(&spk_cfg); - -// // 4) Mic: ES7210 -// audio_codec_i2c_cfg_t in_i2c = { .port = 0, .addr = ES7210_CODEC_DEFAULT_ADDR, -// .bus_handle = bus }; -// es7210_codec_cfg_t es7210_cfg = { -// .ctrl_if = audio_codec_new_i2c_ctrl(&in_i2c), -// .mic_selected = ES7210_SEL_MIC1 | ES7210_SEL_MIC2, -// }; -// esp_codec_dev_cfg_t mic_cfg = { .dev_type = ESP_CODEC_DEV_TYPE_IN, -// .codec_if = es7210_codec_new(&es7210_cfg), .data_if = data_if }; -// mic_dev = esp_codec_dev_new(&mic_cfg); - -// // 5) Open both -// esp_codec_dev_sample_info_t fs = { .sample_rate = SR, .channel = 2, -// .bits_per_sample = 16 }; -// ESP_ERROR_CHECK(esp_codec_dev_open(spk_dev, &fs) == ESP_CODEC_DEV_OK ? ESP_OK : ESP_FAIL); -// ESP_ERROR_CHECK(esp_codec_dev_open(mic_dev, &fs) == ESP_CODEC_DEV_OK ? ESP_OK : ESP_FAIL); -// esp_codec_dev_set_out_vol(spk_dev, 100); -// esp_codec_dev_set_in_gain(mic_dev, 30.0); - -// s_play_sb = xStreamBufferCreate(4096, 1); // about 128 ms maximum queue -// xTaskCreate(play_task, "play", 4096, NULL, 6, NULL); - -// return ESP_OK; -// } - -// #define MIC_BOOST 4 // software gain, raise if still quiet - -// static void mic_task(void *arg) -// { -// static int16_t st[512]; // 512 stereo frames -// static int16_t mono[256]; -// int blocks = 0, sendFail = 0, pkL = 0, pkR = 0; - -// while (1) { -// int rd = esp_codec_dev_read(mic_dev, st, sizeof(st)); -// if (rd != ESP_CODEC_DEV_OK) { -// ESP_LOGE("MIC", "read error %d", rd); -// vTaskDelay(pdMS_TO_TICKS(50)); -// continue; -// } - -// long eL = 0, eR = 0; -// for (int i = 0; i < 256; i++) { -// int l = abs(st[2*i]), r = abs(st[2*i+1]); -// eL += l; eR += r; -// if (l > pkL) pkL = l; -// if (r > pkR) pkR = r; -// } -// int useRight = eR > eL; - -// if (s_audio_fd >= 0) { -// for (int i = 0; i < 256; i++) { -// int v = (useRight ? st[2*i+1] : st[2*i]) * MIC_BOOST; -// if (v > 32767) v = 32767; -// if (v < -32768) v = -32768; -// mono[i] = (int16_t)v; -// } -// httpd_ws_frame_t f = { .payload = (uint8_t *)mono, .len = sizeof(mono), -// .type = HTTPD_WS_TYPE_BINARY }; -// if (httpd_ws_send_frame_async(s_audio_hd, s_audio_fd, &f) != ESP_OK) -// sendFail++; -// } - -// if (++blocks >= 62) { // about once per second -// ESP_LOGI("MIC", "peakL=%d peakR=%d client_fd=%d sendFail=%d", -// pkL, pkR, (int)s_audio_fd, sendFail); -// blocks = 0; pkL = pkR = 0; sendFail = 0; -// } -// } -// } - void app_main(void) { #if ESP_CAMERA_SUPPORTED @@ -503,11 +15,17 @@ void app_main(void) #endif ESP_ERROR_CHECK(audio_init(bsp_i2c_get_handle())); - xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL); - start_wifi_and_server(); - start_audio_server(); + wifi_start_provisioning_if_needed(); // station mode, or the captive portal if no credentials + + while (!wifi_wait_connected(5000)) { + ESP_LOGI("Main", "Waiting for Wi-Fi (or setup portal)..."); + } + + start_camera_server(); // port 80: /pic, /stream + xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL); + start_audio_server(); // ports 81 and 82: /mic, /spk, /vol while (1) vTaskDelay(pdMS_TO_TICKS(1000)); #endif -} \ No newline at end of file +} \ No newline at end of file diff --git a/main/wifi.c b/main/wifi.c index f4efb03..5f354ce 100644 --- a/main/wifi.c +++ b/main/wifi.c @@ -1,78 +1,586 @@ -#include "sdkconfig.h" -#include -#include -#include "esp_http_server.h" -#include -#include +// #include "sdkconfig.h" +// #include +// #include +// #include "esp_http_server.h" +// #include +// #include +// #include +// #include "freertos/FreeRTOS.h" +// #include "freertos/task.h" +// #include "esp_wifi.h" +// #include "nvs_flash.h" +// #include "esp_netif.h" +// #include "esp_http_server.h" +// #include "lwip/sockets.h" +// #include +// #include "board.h" + +// static const char *TAG = "WIFI:"; + +// static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { +// if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { +// esp_wifi_connect(); +// } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { +// ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying..."); +// esp_wifi_connect(); +// } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { +// ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; +// ESP_LOGI(TAG, "SUCCESS! Got IP: " IPSTR, IP2STR(&event->ip_info.ip)); +// } +// } + +// void start_wifi_and_server(void) { +// esp_err_t ret = nvs_flash_init(); +// if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { +// nvs_flash_erase(); +// nvs_flash_init(); +// } +// esp_netif_init(); +// esp_event_loop_create_default(); +// esp_netif_create_default_wifi_sta(); + +// wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); +// esp_wifi_init(&cfg); + +// wifi_config_t wifi_config = { +// .sta = { +// .ssid = "viratak-lte", +// .password = "mydlinkviratak", +// }, +// }; +// esp_wifi_set_mode(WIFI_MODE_STA); +// esp_wifi_set_config(WIFI_IF_STA, &wifi_config); +// esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL); +// esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL); +// esp_wifi_start(); +// esp_wifi_set_ps(WIFI_PS_NONE); +// esp_wifi_connect(); + +// httpd_config_t config = HTTPD_DEFAULT_CONFIG(); +// httpd_handle_t server = NULL; +// if (httpd_start(&server, &config) == ESP_OK) { +// httpd_uri_t uri_capture = { +// .uri = "/pic", +// .method = HTTP_GET, +// .handler = capture_handler, +// .user_ctx = NULL +// }; +// httpd_register_uri_handler(server, &uri_capture); + +// httpd_uri_t uri_stream = { +// .uri = "/stream", +// .method = HTTP_GET, +// .handler = stream_handler, +// .user_ctx = NULL +// }; +// httpd_register_uri_handler(server, &uri_stream); +// } +// } + #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 #include "board.h" -static const char *TAG = "WIFI:"; +/* ---- 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 -static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { - if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { - esp_wifi_connect(); - } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { - ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying..."); - esp_wifi_connect(); - } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { - ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; - ESP_LOGI(TAG, "SUCCESS! Got IP: " IPSTR, IP2STR(&event->ip_info.ip)); +#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); } } -void start_wifi_and_server(void) { - esp_err_t ret = nvs_flash_init(); - if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { - nvs_flash_erase(); - nvs_flash_init(); +/* ------------------------------------------------------------------ */ +/* 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; } - esp_netif_init(); - esp_event_loop_create_default(); - esp_netif_create_default_wifi_sta(); + + 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; /* phones open many short connections */ + + 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_wifi_init(&cfg); + ESP_ERROR_CHECK(esp_wifi_init(&cfg)); + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); /* credentials live in our own NVS keys */ - wifi_config_t wifi_config = { - .sta = { - .ssid = "viratak-lte", - .password = "mydlinkviratak", - }, - }; - esp_wifi_set_mode(WIFI_MODE_STA); - esp_wifi_set_config(WIFI_IF_STA, &wifi_config); - esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL); - esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL); - esp_wifi_start(); - esp_wifi_set_ps(WIFI_PS_NONE); - esp_wifi_connect(); + 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)); - httpd_config_t config = HTTPD_DEFAULT_CONFIG(); - httpd_handle_t server = NULL; - if (httpd_start(&server, &config) == ESP_OK) { - httpd_uri_t uri_capture = { - .uri = "/pic", - .method = HTTP_GET, - .handler = capture_handler, - .user_ctx = NULL - }; - httpd_register_uri_handler(server, &uri_capture); - - httpd_uri_t uri_stream = { - .uri = "/stream", - .method = HTTP_GET, - .handler = stream_handler, - .user_ctx = NULL - }; - httpd_register_uri_handler(server, &uri_stream); + /* 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); +} \ No newline at end of file