1 /* HTTP Server Tests
2 
3    This example code is in the Public Domain (or CC0 licensed, at your option.)
4 
5    Unless required by applicable law or agreed to in writing, this
6    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7    CONDITIONS OF ANY KIND, either express or implied.
8 */
9 
10 #include "esp_wifi.h"
11 #include "esp_event.h"
12 #include "esp_log.h"
13 #include "esp_system.h"
14 #include "nvs_flash.h"
15 #include "esp_netif.h"
16 #include "esp_eth.h"
17 #include "protocol_examples_common.h"
18 
19 #include "tests.h"
20 
21 static const char *TAG = "example";
22 
disconnect_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)23 static void disconnect_handler(void* arg, esp_event_base_t event_base,
24                                int32_t event_id, void* event_data)
25 {
26     httpd_handle_t* server = (httpd_handle_t*) arg;
27     if (*server) {
28         ESP_LOGI(TAG, "Stopping webserver");
29         stop_tests(*server);
30         *server = NULL;
31     }
32 }
33 
connect_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)34 static void connect_handler(void* arg, esp_event_base_t event_base,
35                             int32_t event_id, void* event_data)
36 {
37     httpd_handle_t* server = (httpd_handle_t*) arg;
38     if (*server == NULL) {
39         ESP_LOGI(TAG, "Starting webserver");
40         *server = start_tests();
41     }
42 }
43 
app_main(void)44 void app_main(void)
45 {
46     static httpd_handle_t server = NULL;
47 
48     ESP_ERROR_CHECK(nvs_flash_init());
49     ESP_ERROR_CHECK(esp_netif_init());
50     ESP_ERROR_CHECK(esp_event_loop_create_default());
51 
52     /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
53      * Read "Establishing Wi-Fi or Ethernet Connection" section in
54      * examples/protocols/README.md for more information about this function.
55      */
56     ESP_ERROR_CHECK(example_connect());
57 
58     /* Register event handlers to stop the server when Wi-Fi or Ethernet is disconnected,
59      * and re-start it upon connection.
60      */
61 #ifdef CONFIG_EXAMPLE_CONNECT_WIFI
62     ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server));
63     ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server));
64 #endif // CONFIG_EXAMPLE_CONNECT_WIFI
65 #ifdef CONFIG_EXAMPLE_CONNECT_ETHERNET
66     ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &connect_handler, &server));
67     ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ETHERNET_EVENT_DISCONNECTED, &disconnect_handler, &server));
68 #endif // CONFIG_EXAMPLE_CONNECT_ETHERNET
69 
70     /* Start the server for the first time */
71     server = start_tests();
72 }
73