main.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /* Simple HTTP Server Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <esp_wifi.h>
  8. #include <esp_event.h>
  9. #include <esp_log.h>
  10. #include <esp_system.h>
  11. #include <nvs_flash.h>
  12. #include <sys/param.h>
  13. #include "nvs_flash.h"
  14. #include "esp_netif.h"
  15. #include "esp_eth.h"
  16. #include "protocol_examples_common.h"
  17. #include <esp_http_server.h>
  18. /* A simple example that demonstrates how to create GET and POST
  19. * handlers for the web server.
  20. */
  21. static const char *TAG = "example";
  22. /* An HTTP GET handler */
  23. static esp_err_t hello_get_handler(httpd_req_t *req)
  24. {
  25. char* buf;
  26. size_t buf_len;
  27. /* Get header value string length and allocate memory for length + 1,
  28. * extra byte for null termination */
  29. buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1;
  30. if (buf_len > 1) {
  31. buf = malloc(buf_len);
  32. /* Copy null terminated value string into buffer */
  33. if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
  34. ESP_LOGI(TAG, "Found header => Host: %s", buf);
  35. }
  36. free(buf);
  37. }
  38. buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-2") + 1;
  39. if (buf_len > 1) {
  40. buf = malloc(buf_len);
  41. if (httpd_req_get_hdr_value_str(req, "Test-Header-2", buf, buf_len) == ESP_OK) {
  42. ESP_LOGI(TAG, "Found header => Test-Header-2: %s", buf);
  43. }
  44. free(buf);
  45. }
  46. buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-1") + 1;
  47. if (buf_len > 1) {
  48. buf = malloc(buf_len);
  49. if (httpd_req_get_hdr_value_str(req, "Test-Header-1", buf, buf_len) == ESP_OK) {
  50. ESP_LOGI(TAG, "Found header => Test-Header-1: %s", buf);
  51. }
  52. free(buf);
  53. }
  54. /* Read URL query string length and allocate memory for length + 1,
  55. * extra byte for null termination */
  56. buf_len = httpd_req_get_url_query_len(req) + 1;
  57. if (buf_len > 1) {
  58. buf = malloc(buf_len);
  59. if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
  60. ESP_LOGI(TAG, "Found URL query => %s", buf);
  61. char param[32];
  62. /* Get value of expected key from query string */
  63. if (httpd_query_key_value(buf, "query1", param, sizeof(param)) == ESP_OK) {
  64. ESP_LOGI(TAG, "Found URL query parameter => query1=%s", param);
  65. }
  66. if (httpd_query_key_value(buf, "query3", param, sizeof(param)) == ESP_OK) {
  67. ESP_LOGI(TAG, "Found URL query parameter => query3=%s", param);
  68. }
  69. if (httpd_query_key_value(buf, "query2", param, sizeof(param)) == ESP_OK) {
  70. ESP_LOGI(TAG, "Found URL query parameter => query2=%s", param);
  71. }
  72. }
  73. free(buf);
  74. }
  75. /* Set some custom headers */
  76. httpd_resp_set_hdr(req, "Custom-Header-1", "Custom-Value-1");
  77. httpd_resp_set_hdr(req, "Custom-Header-2", "Custom-Value-2");
  78. /* Send response with custom headers and body set as the
  79. * string passed in user context*/
  80. const char* resp_str = (const char*) req->user_ctx;
  81. httpd_resp_send(req, resp_str, strlen(resp_str));
  82. /* After sending the HTTP response the old HTTP request
  83. * headers are lost. Check if HTTP request headers can be read now. */
  84. if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
  85. ESP_LOGI(TAG, "Request headers lost");
  86. }
  87. return ESP_OK;
  88. }
  89. static const httpd_uri_t hello = {
  90. .uri = "/hello",
  91. .method = HTTP_GET,
  92. .handler = hello_get_handler,
  93. /* Let's pass response string in user
  94. * context to demonstrate it's usage */
  95. .user_ctx = "Hello World!"
  96. };
  97. /* An HTTP POST handler */
  98. static esp_err_t echo_post_handler(httpd_req_t *req)
  99. {
  100. char buf[100];
  101. int ret, remaining = req->content_len;
  102. while (remaining > 0) {
  103. /* Read the data for the request */
  104. if ((ret = httpd_req_recv(req, buf,
  105. MIN(remaining, sizeof(buf)))) <= 0) {
  106. if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
  107. /* Retry receiving if timeout occurred */
  108. continue;
  109. }
  110. return ESP_FAIL;
  111. }
  112. /* Send back the same data */
  113. httpd_resp_send_chunk(req, buf, ret);
  114. remaining -= ret;
  115. /* Log data received */
  116. ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
  117. ESP_LOGI(TAG, "%.*s", ret, buf);
  118. ESP_LOGI(TAG, "====================================");
  119. }
  120. // End response
  121. httpd_resp_send_chunk(req, NULL, 0);
  122. return ESP_OK;
  123. }
  124. static const httpd_uri_t echo = {
  125. .uri = "/echo",
  126. .method = HTTP_POST,
  127. .handler = echo_post_handler,
  128. .user_ctx = NULL
  129. };
  130. /* This handler allows the custom error handling functionality to be
  131. * tested from client side. For that, when a PUT request 0 is sent to
  132. * URI /ctrl, the /hello and /echo URIs are unregistered and following
  133. * custom error handler http_404_error_handler() is registered.
  134. * Afterwards, when /hello or /echo is requested, this custom error
  135. * handler is invoked which, after sending an error message to client,
  136. * either closes the underlying socket (when requested URI is /echo)
  137. * or keeps it open (when requested URI is /hello). This allows the
  138. * client to infer if the custom error handler is functioning as expected
  139. * by observing the socket state.
  140. */
  141. esp_err_t http_404_error_handler(httpd_req_t *req, httpd_err_code_t err)
  142. {
  143. if (strcmp("/hello", req->uri) == 0) {
  144. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/hello URI is not available");
  145. /* Return ESP_OK to keep underlying socket open */
  146. return ESP_OK;
  147. } else if (strcmp("/echo", req->uri) == 0) {
  148. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/echo URI is not available");
  149. /* Return ESP_FAIL to close underlying socket */
  150. return ESP_FAIL;
  151. }
  152. /* For any other URI send 404 and close socket */
  153. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Some 404 error message");
  154. return ESP_FAIL;
  155. }
  156. /* An HTTP PUT handler. This demonstrates realtime
  157. * registration and deregistration of URI handlers
  158. */
  159. static esp_err_t ctrl_put_handler(httpd_req_t *req)
  160. {
  161. char buf;
  162. int ret;
  163. if ((ret = httpd_req_recv(req, &buf, 1)) <= 0) {
  164. if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
  165. httpd_resp_send_408(req);
  166. }
  167. return ESP_FAIL;
  168. }
  169. if (buf == '0') {
  170. /* URI handlers can be unregistered using the uri string */
  171. ESP_LOGI(TAG, "Unregistering /hello and /echo URIs");
  172. httpd_unregister_uri(req->handle, "/hello");
  173. httpd_unregister_uri(req->handle, "/echo");
  174. /* Register the custom error handler */
  175. httpd_register_err_handler(req->handle, HTTPD_404_NOT_FOUND, http_404_error_handler);
  176. }
  177. else {
  178. ESP_LOGI(TAG, "Registering /hello and /echo URIs");
  179. httpd_register_uri_handler(req->handle, &hello);
  180. httpd_register_uri_handler(req->handle, &echo);
  181. /* Unregister custom error handler */
  182. httpd_register_err_handler(req->handle, HTTPD_404_NOT_FOUND, NULL);
  183. }
  184. /* Respond with empty body */
  185. httpd_resp_send(req, NULL, 0);
  186. return ESP_OK;
  187. }
  188. static const httpd_uri_t ctrl = {
  189. .uri = "/ctrl",
  190. .method = HTTP_PUT,
  191. .handler = ctrl_put_handler,
  192. .user_ctx = NULL
  193. };
  194. static httpd_handle_t start_webserver(void)
  195. {
  196. httpd_handle_t server = NULL;
  197. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  198. config.lru_purge_enable = true;
  199. // Start the httpd server
  200. ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
  201. if (httpd_start(&server, &config) == ESP_OK) {
  202. // Set URI handlers
  203. ESP_LOGI(TAG, "Registering URI handlers");
  204. httpd_register_uri_handler(server, &hello);
  205. httpd_register_uri_handler(server, &echo);
  206. httpd_register_uri_handler(server, &ctrl);
  207. return server;
  208. }
  209. ESP_LOGI(TAG, "Error starting server!");
  210. return NULL;
  211. }
  212. static void stop_webserver(httpd_handle_t server)
  213. {
  214. // Stop the httpd server
  215. httpd_stop(server);
  216. }
  217. static void disconnect_handler(void* arg, esp_event_base_t event_base,
  218. int32_t event_id, void* event_data)
  219. {
  220. httpd_handle_t* server = (httpd_handle_t*) arg;
  221. if (*server) {
  222. ESP_LOGI(TAG, "Stopping webserver");
  223. stop_webserver(*server);
  224. *server = NULL;
  225. }
  226. }
  227. static void connect_handler(void* arg, esp_event_base_t event_base,
  228. int32_t event_id, void* event_data)
  229. {
  230. httpd_handle_t* server = (httpd_handle_t*) arg;
  231. if (*server == NULL) {
  232. ESP_LOGI(TAG, "Starting webserver");
  233. *server = start_webserver();
  234. }
  235. }
  236. void app_main(void)
  237. {
  238. static httpd_handle_t server = NULL;
  239. ESP_ERROR_CHECK(nvs_flash_init());
  240. ESP_ERROR_CHECK(esp_netif_init());
  241. ESP_ERROR_CHECK(esp_event_loop_create_default());
  242. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  243. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  244. * examples/protocols/README.md for more information about this function.
  245. */
  246. ESP_ERROR_CHECK(example_connect());
  247. /* Register event handlers to stop the server when Wi-Fi or Ethernet is disconnected,
  248. * and re-start it upon connection.
  249. */
  250. #ifdef CONFIG_EXAMPLE_CONNECT_WIFI
  251. ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server));
  252. ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server));
  253. #endif // CONFIG_EXAMPLE_CONNECT_WIFI
  254. #ifdef CONFIG_EXAMPLE_CONNECT_ETHERNET
  255. ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &connect_handler, &server));
  256. ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ETHERNET_EVENT_DISCONNECTED, &disconnect_handler, &server));
  257. #endif // CONFIG_EXAMPLE_CONNECT_ETHERNET
  258. /* Start the server for the first time */
  259. server = start_webserver();
  260. }