Handling HTTP requests

Now we will develop a program for our smart home project:

  1. Create a project called smarthome. Our main program is the smarthome.c file.

First, we will declare our libraries for this project:

#include <esp_wifi.h>
#include <esp_event_loop.h>
#include <esp_log.h>
#include <esp_system.h>
#include <nvs_flash.h>
#include <sys/param.h>

#include <esp_http_server.h>
  1. We will then define our logger title and GPIO for our LED:
static const char *TAG="APP";
#define LED1 12

  1. Next, we will develop a HTTP POST request handler via the httpd_uri_t struct. We define the /led request with HTTP_POST for the request method. In addition, we pass the led_post_handle() function into the request handler as follows:
httpd_uri_t led_post = {
.uri = "/led",
.method = HTTP_POST,
.handler = led_post_handler,
.user_ctx = NULL
};
  1. Now we implement our led_post_handler() function. This function reads the HTTP request message. Then, check whether the request body has a value of 1 or 0 in the HTTP request body. If the request body consists of value 1, we turn on the LED by calling the gpio_set_level() function:
esp_err_t led_post_handler(httpd_req_t *req)
{
char buf[100];
int ret, remaining = req->content_len;

while (remaining > 0) {
buf[0] = '';
if ((ret = httpd_req_recv(req, &buf, 1)) <= 0) {
if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
httpd_resp_send_408(req);
}
return ESP_FAIL;
}
buf[ret] = '';
ESP_LOGI(TAG, "Recv HTTP => %s", buf);
if (buf[0] == '1') {
ESP_LOGI(TAG, "====================================");
ESP_LOGI(TAG, ">>> Turn on LED");
gpio_set_level(LED1, 1);
httpd_resp_send_chunk(req, "Turn on LED", ret);

}
else
if (buf[0] == '0') {
ESP_LOGI(TAG, "====================================");
ESP_LOGI(TAG, ">>> Turn off LED");
gpio_set_level(LED1, 0);
httpd_resp_send_chunk(req, "Turn off LED", ret);
}
else {
ESP_LOGI(TAG, "====================================");
ESP_LOGI(TAG, ">>> Unknow command");
httpd_resp_send_chunk(req, "Unknow command", ret);
}
remaining -= ret;

}

// End response
httpd_resp_send_chunk(req, NULL, 0);
return ESP_OK;
}
  1. Next, we will develop a web server in the ESP32 board.
..................Content has been hidden....................

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