ESP32 (ESP-IDF) WiFi setup over HTTP requests

YHatahet
Posts: 2
Joined: Sun Oct 20, 2019 12:32 pm

ESP32 (ESP-IDF) WiFi setup over HTTP requests

Postby YHatahet » Sun Oct 20, 2019 12:58 pm

Hello all,

I have recently succeeded in running the ESP32 as an access point (AP), while simultaneously running it as a station (connected to my home router), and having it receive and interpret HTTP requests.
My next step is to try and run the ESP as an AP on startup, make it receive my WiFi credentials over an HTTP request (over POST requests or something, ill decide later - got that figured out), and then change from an AP to station. I know you can change it from APSTA mode to STA mode (I tried and it works), but it always crashes if I run APSTA without configuring the STA mode.

Short version, I want to input my credentials over HTTP requests, and then turn off AP mode. Also if possible, if it loses wifi connection, turn on AP mode again.

I attached the code I used at the bottom. Thank you for your time.
Regards.

  1. #include <string.h>
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "freertos/event_groups.h"
  5. #include "lwip/err.h"
  6. #include "lwip/sys.h"
  7. #include <esp_wifi.h>
  8. #include <esp_event_loop.h>
  9. #include <esp_log.h>
  10. #include <esp_system.h>
  11. #include <nvs_flash.h>
  12. #include <sys/param.h>
  13. #include <esp_http_server.h>
  14.  
  15. // Function Signatures:
  16.  
  17. void wifi_init_ap_sta();
  18. esp_err_t hello_get_handler(httpd_req_t *req);
  19. httpd_handle_t start_webserver(void);
  20. static esp_err_t WiFi_event_handler(void *ctx, system_event_t *event);
  21. void wifi_init_ap_sta();
  22. void app_main();
  23.  
  24.  
  25. static const char *TAG="APP";
  26.  
  27. /* //////////////////////////////////////////////////////////////////// */
  28. /*                          An HTTP GET handler                         */
  29. /* //////////////////////////////////////////////////////////////////// */
  30.  
  31. char username[32];
  32. char password[32];
  33. bool check = false;
  34. uint32_t timeNow;
  35.  
  36. esp_err_t hello_get_handler(httpd_req_t *req)
  37. {
  38.     char*  buf;
  39.     size_t buf_len;
  40.    
  41.     /*
  42.     * Get header value (request msg Headers) string length and
  43.     * allocate memory for length + 1, extra byte for null termination
  44.     */
  45.     buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1; //Host returns the IP address
  46.     if (buf_len > 1) {
  47.         buf = malloc(buf_len);
  48.         /* Copy null terminated value string into buffer */
  49.         if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
  50.             ESP_LOGI(TAG, "Found header => Host: %s", buf);
  51.         }
  52.         free(buf);
  53.     }
  54.     /*
  55.     * Read URL query string length and allocate memory for length + 1,
  56.     * extra byte for null termination
  57.     */
  58.     buf_len = httpd_req_get_url_query_len(req) + 1;
  59.     if (buf_len > 1) {
  60.         buf = malloc(buf_len);
  61.         if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
  62.             ESP_LOGI(TAG, "Found URL query => %s", buf);
  63.  
  64.             /* Get value of expected key from query string (parameters) */
  65.             if (httpd_query_key_value(buf, "user", username, sizeof(username)) == ESP_OK) {
  66.                 ESP_LOGI(TAG, "Found URL query parameter => Username=%s", username);
  67.             }
  68.             if (httpd_query_key_value(buf, "pass", password, sizeof(password)) == ESP_OK) {
  69.                 ESP_LOGI(TAG, "Found URL query parameter => Password=%s", password);
  70.             }
  71.         }
  72.  
  73.     }
  74.  
  75.     // Send response with custom headers and body set as the string passed in user context
  76.  
  77.     const char* resp_str = (const char*) req->user_ctx;
  78.     httpd_resp_send(req, resp_str, strlen(resp_str)); //This is essential regardless
  79.  
  80.     /* After sending the HTTP response, the old HTTP request
  81.      * headers are lost. Check if HTTP request headers can be read now. */
  82.     if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
  83.         ESP_LOGI(TAG, "Request headers lost");
  84.     }
  85.     return ESP_OK;
  86. }
  87.  
  88. httpd_uri_t hello = {
  89.     .uri       = "/hello",
  90.     .method    = HTTP_GET,
  91.     .handler   = hello_get_handler,
  92.     // pass a response string in user context to demonstrate it's usage:
  93.     .user_ctx  = "Hello World!" //
  94. };
  95.  
  96. /* //////////////////////////////////////////////////////////////////// */
  97. /*                  START WEBSERVER + REGISTER HANDLERS                 */
  98. /* //////////////////////////////////////////////////////////////////// */
  99.  
  100. httpd_handle_t start_webserver(void)
  101. {
  102.     httpd_handle_t server = NULL;
  103.     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  104.  
  105.     // Start the httpd server
  106.     ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
  107.     if (httpd_start(&server, &config) == ESP_OK) {
  108.         // Set URI handlers
  109.         ESP_LOGI(TAG, "Registering URI handlers");
  110.         httpd_register_uri_handler(server, &hello);
  111.         return server;
  112.     }
  113.  
  114.     ESP_LOGI(TAG, "Error starting server!");
  115.     return NULL;
  116. }
  117. void stop_webserver(httpd_handle_t server)
  118. {
  119.     // Stop the httpd server
  120.     httpd_stop(server);
  121. }
  122.  
  123. /* //////////////////////////////////////////////////////////////////// */
  124. /*                              EVENT HANDLER                           */
  125. /* //////////////////////////////////////////////////////////////////// */
  126.  
  127. static esp_err_t WiFi_event_handler(void *ctx, system_event_t *event)
  128. {
  129.     httpd_handle_t *server = (httpd_handle_t *) ctx;
  130.     switch (event->event_id)
  131.     {  
  132.  
  133.     //--------------- STA events ---------------//
  134.     case SYSTEM_EVENT_STA_START:
  135.         ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
  136.         ESP_ERROR_CHECK(esp_wifi_connect());
  137.         break;
  138.     case SYSTEM_EVENT_STA_GOT_IP:
  139.         ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
  140.         ESP_LOGI(TAG, "Got IP: '%s'",
  141.                  ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
  142.         /* Start the web server */
  143.         // if (*server == NULL)
  144.         // {
  145.         //     *server = start_webserver();
  146.         // }
  147.         break;
  148.     case SYSTEM_EVENT_STA_DISCONNECTED:
  149.         ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
  150.         ESP_ERROR_CHECK(esp_wifi_connect());
  151.  
  152.         /* Stop the web server */
  153.         if (*server)
  154.         {
  155.             stop_webserver(*server);
  156.             *server = NULL;
  157.         }
  158.         break;
  159.  
  160.     //--------------- AP events ---------------//
  161.     case SYSTEM_EVENT_AP_STACONNECTED:
  162.         ESP_LOGI(TAG, "station:" MACSTR " join, AID=%d",
  163.                  MAC2STR(event->event_info.sta_connected.mac),
  164.                  event->event_info.sta_connected.aid);
  165.         break;
  166.     case SYSTEM_EVENT_AP_STADISCONNECTED:
  167.         ESP_LOGI(TAG, "station:" MACSTR "leave, AID=%d",
  168.                  MAC2STR(event->event_info.sta_disconnected.mac),
  169.                  event->event_info.sta_disconnected.aid);
  170.         break;
  171.     default:
  172.         break;
  173.     }
  174.     return ESP_OK;
  175. }
  176.  
  177.  
  178. /* //////////////////////////////////////////////////////////////////// */
  179. /*                            CONFIGURING WIFI                          */
  180. /* //////////////////////////////////////////////////////////////////// */
  181.  
  182. #define CONFIG_AP_SSID      CONFIGURE
  183. #define CONFIG_AP_PASS      CONFIGURE
  184. #define CONFIG_STA_SSID     CONFIGURE
  185. #define CONFIG_STA_PASS     CONFIGURE
  186. #define CONFIG_MAX_CONN     4 //default is also 4
  187.  
  188. /* FreeRTOS event group to signal when we are connected*/
  189. // static EventGroupHandle_t s_wifi_event_group;
  190.  
  191. void wifi_init_ap_sta()
  192. {
  193.     tcpip_adapter_init(); //initialize the TCP/IP stack (Done once at the start of the code)
  194.     ESP_ERROR_CHECK(esp_event_loop_init(WiFi_event_handler, NULL));
  195.     wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  196.     ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  197.     ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
  198.  
  199.     //Write configurations for both AP and STA modes
  200.     wifi_config_t wifi_ap_config = {
  201.         .ap = {
  202.             .ssid = CONFIG_AP_SSID,
  203.             .ssid_len = (uint8_t)strlen(CONFIG_AP_SSID),
  204.             .password = CONFIG_AP_PASS,
  205.             .max_connection = CONFIG_MAX_CONN,
  206.             .authmode = WIFI_AUTH_WPA_WPA2_PSK}};
  207.     if (strlen(CONFIG_AP_PASS) == 0)    //if no password, leave it open
  208.     {
  209.         wifi_ap_config.ap.authmode = WIFI_AUTH_OPEN;
  210.     }
  211.  
  212.     // --------------- Configuring STA: --------------- //
  213.     // wifi_config_t wifi_sta_config = {
  214.     //     .sta = {
  215.     //         .ssid = CONFIG_STA_SSID,
  216.     //         .password = CONFIG_STA_PASS,
  217.     //     },
  218.     // };
  219.  
  220.     //Set the configurations and start WiFi
  221.     ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));    //Set Wifi mode to AP
  222.     ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_ap_config));
  223.     // ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config));
  224.     ESP_ERROR_CHECK(esp_wifi_start());
  225.     ESP_LOGI(TAG, "Connecting to ap SSID:%s, password:%s", CONFIG_STA_SSID, CONFIG_STA_PASS);
  226. }
  227.  
  228. /* //////////////////////////////////////////////////////////////////// */
  229. /*                                  MAIN                                */
  230. /* //////////////////////////////////////////////////////////////////// */
  231.  
  232. void app_main()
  233. {
  234.     //Initialize NVS
  235.     esp_err_t ret = nvs_flash_init();
  236.     if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
  237.     {
  238.         ESP_ERROR_CHECK(nvs_flash_erase());
  239.         ret = nvs_flash_init();
  240.     }
  241.     ESP_ERROR_CHECK(ret);
  242.  
  243.     wifi_init_ap_sta(); // Start WiFi with the chosen configs
  244.     start_webserver();  // Enable HTTP requests
  245. }

Who is online

Users browsing this forum: leonardo.ceolin, tanmanh0707 and 121 guests