Building a web server

In this section, we will activate our web server on the ESP32 board. When we receive a SYSTEM_EVENT_STA_GOT_IP event from Wi-Fi service, we start a web server by calling the start_webserver() function.

  1. We will call the stop_webserver() function when the ESP32 board is disconnected on a SYSTEM_EVENT_STA_DISCONNECTED event:
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
httpd_handle_t *server = (httpd_handle_t *) ctx;

switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
ESP_ERROR_CHECK(esp_wifi_connect());
break;
case SYSTEM_EVENT_STA_GOT_IP:
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
ESP_LOGI(TAG, "Got IP: '%s'",
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));

/* Start the web server */
if (*server == NULL) {
*server = start_webserver();
}
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
ESP_ERROR_CHECK(esp_wifi_connect());

/* Stop the web server */
if (*server) {
stop_webserver(*server);
*server = NULL;
}
break;
default:
break;
}
return ESP_OK;
}
  1. Now, we will implement the start_webserver() function. We will first use httpd_start() to start our web server. Then, we will register all HTTP requests using the httpd_register_uri_handler() function:
httpd_handle_t start_webserver(void)
{
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();

// Start the httpd server
ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
if (httpd_start(&server, &config) == ESP_OK) {
// Set URI handlers
ESP_LOGI(TAG, "Registering URI handlers");
httpd_register_uri_handler(server, &hello);
httpd_register_uri_handler(server, &echo);
httpd_register_uri_handler(server, &ctrl);
return server;
}

ESP_LOGI(TAG, "Error starting server!");
return NULL;
}
  1. To stop the web server service from working, we will implement the stop_webserver() function. We will also call the httpd_stop() function to stop our web server service in ESP32:
void stop_webserver(httpd_handle_t server)
{
// Stop the httpd server
httpd_stop(server);
}
  1. Save all the programs. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset