Advertisement
DemSec

mesh_main.c

Aug 20th, 2019
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 22.75 KB | None | 0 0
  1. #include <string.h>
  2. #include "esp_wifi.h"
  3. #include "esp_system.h"
  4. #include "esp_event_loop.h"
  5. #include "esp_log.h"
  6. #include "esp_mesh.h"
  7. #include "esp_mesh_internal.h"
  8. #include "mesh_light.h"
  9. #include "nvs_flash.h"
  10. #include <sys/param.h>
  11. #include <esp_http_server.h>
  12.  
  13. #define CONFIG_MESH_ROUTE_TABLE_SIZE 50
  14. #define CONFIG_MESH_MAX_LAYER 6
  15. #define CONFIG_MESH_CHANNEL 0
  16. #define CONFIG_MESH_ROUTER_SSID "Anchor"
  17. #define CONFIG_MESH_ROUTER_PASSWD "12345678"
  18. #define CONFIG_MESH_AP_AUTHMODE WIFI_AUTH_WPA2_PSK
  19. #define CONFIG_MESH_AP_CONNECTIONS 6
  20. #define CONFIG_MESH_AP_PASSWD "ichiban7"
  21.  
  22. /*******************************************************
  23.  *                Macros
  24.  *******************************************************/
  25. //#define MESH_P2P_TOS_OFF
  26.  
  27. /*******************************************************
  28.  *                Constants
  29.  *******************************************************/
  30. #define RX_SIZE          (1500)
  31. #define TX_SIZE          (1460)
  32.  
  33. /*******************************************************
  34.  *                Variable Definitions
  35.  *******************************************************/
  36. static const char *MESH_TAG = "mesh_main";
  37. static const uint8_t MESH_ID[6] = { 0x77, 0x77, 0x77, 0x77, 0x77, 0x77};
  38. static uint8_t tx_buf[TX_SIZE] = { 0, };
  39. static uint8_t rx_buf[RX_SIZE] = { 0, };
  40. static bool is_running = true;
  41. static bool is_mesh_connected = false;
  42. static mesh_addr_t mesh_parent_addr;
  43. static int mesh_layer = -1;
  44. static const char *TAG="APP";
  45.  
  46. mesh_light_ctl_t light_on = {
  47.     .cmd = MESH_CONTROL_CMD,
  48.     .on = 1,
  49.     .token_id = MESH_TOKEN_ID,
  50.     .token_value = MESH_TOKEN_VALUE,
  51. };
  52.  
  53. mesh_light_ctl_t light_off = {
  54.     .cmd = MESH_CONTROL_CMD,
  55.     .on = 0,
  56.     .token_id = MESH_TOKEN_ID,
  57.     .token_value = MESH_TOKEN_VALUE,
  58. };
  59.  
  60. /*******************************************************
  61.  *                Function Declarations
  62.  *******************************************************/
  63.  
  64. /*******************************************************
  65.  *                Function Definitions
  66.  *******************************************************/
  67. void esp_mesh_p2p_tx_main(void *arg)
  68. {
  69.     int i;
  70.     esp_err_t err;
  71.     int send_count = 0;
  72.     mesh_addr_t route_table[CONFIG_MESH_ROUTE_TABLE_SIZE];
  73.     int route_table_size = 0;
  74.     mesh_data_t data;
  75.     data.data = tx_buf;
  76.     data.size = sizeof(tx_buf);
  77.     data.proto = MESH_PROTO_BIN;
  78. #ifdef MESH_P2P_TOS_OFF
  79.     data.tos = MESH_TOS_DEF;
  80. #endif /* MESH_P2P_TOS_OFF */
  81.  
  82.     is_running = true;
  83.     while (is_running) {
  84.         /* non-root do nothing but print */
  85.         if (!esp_mesh_is_root()) {
  86.             ESP_LOGI(MESH_TAG, "layer:%d, rtableSize:%d, %s", mesh_layer,
  87.                      esp_mesh_get_routing_table_size(),
  88.                      (is_mesh_connected && esp_mesh_is_root()) ? "ROOT" : is_mesh_connected ? "NODE" : "DISCONNECT");
  89.             vTaskDelay(10 * 1000 / portTICK_RATE_MS);
  90.             continue;
  91.         }
  92.         esp_mesh_get_routing_table((mesh_addr_t *) &route_table,
  93.                                    CONFIG_MESH_ROUTE_TABLE_SIZE * 6, &route_table_size);
  94.         if (send_count && !(send_count % 100)) {
  95.             ESP_LOGI(MESH_TAG, "size:%d/%d,send_count:%d", route_table_size,
  96.                      esp_mesh_get_routing_table_size(), send_count);
  97.         }
  98.         send_count++;
  99.         tx_buf[25] = (send_count >> 24) & 0xff;
  100.         tx_buf[24] = (send_count >> 16) & 0xff;
  101.         tx_buf[23] = (send_count >> 8) & 0xff;
  102.         tx_buf[22] = (send_count >> 0) & 0xff;
  103.         if (send_count % 2) {
  104.             memcpy(tx_buf, (uint8_t *)&light_on, sizeof(light_on));
  105.         } else {
  106.             memcpy(tx_buf, (uint8_t *)&light_off, sizeof(light_off));
  107.         }
  108.  
  109.         for (i = 0; i < route_table_size; i++) {
  110.             err = esp_mesh_send(&route_table[i], &data, MESH_DATA_P2P, NULL, 0);
  111.             if (err) {
  112.                 ESP_LOGE(MESH_TAG,
  113.                          "[ROOT-2-UNICAST:%d][L:%d]parent:"MACSTR" to "MACSTR", heap:%d[err:0x%x, proto:%d, tos:%d]",
  114.                          send_count, mesh_layer, MAC2STR(mesh_parent_addr.addr),
  115.                          MAC2STR(route_table[i].addr), esp_get_free_heap_size(),
  116.                          err, data.proto, data.tos);
  117.             } else if (!(send_count % 100)) {
  118.                 ESP_LOGW(MESH_TAG,
  119.                          "[ROOT-2-UNICAST:%d][L:%d][rtableSize:%d]parent:"MACSTR" to "MACSTR", heap:%d[err:0x%x, proto:%d, tos:%d]",
  120.                          send_count, mesh_layer,
  121.                          esp_mesh_get_routing_table_size(),
  122.                          MAC2STR(mesh_parent_addr.addr),
  123.                          MAC2STR(route_table[i].addr), esp_get_free_heap_size(),
  124.                          err, data.proto, data.tos);
  125.             }
  126.         }
  127.         /* if route_table_size is less than 10, add delay to avoid watchdog in this task. */
  128.         if (route_table_size < 10) {
  129.             vTaskDelay(1 * 1000 / portTICK_RATE_MS);
  130.         }
  131.     }
  132.     vTaskDelete(NULL);
  133. }
  134.  
  135. void esp_mesh_p2p_rx_main(void *arg)
  136. {
  137.     int recv_count = 0;
  138.     esp_err_t err;
  139.     mesh_addr_t from;
  140.     int send_count = 0;
  141.     mesh_data_t data;
  142.     int flag = 0;
  143.     data.data = rx_buf;
  144.     data.size = RX_SIZE;
  145.  
  146.     is_running = true;
  147.     while (is_running) {
  148.         data.size = RX_SIZE;
  149.         err = esp_mesh_recv(&from, &data, portMAX_DELAY, &flag, NULL, 0);
  150.         if (err != ESP_OK || !data.size) {
  151.             ESP_LOGE(MESH_TAG, "err:0x%x, size:%d", err, data.size);
  152.             continue;
  153.         }
  154.         /* extract send count */
  155.         if (data.size >= sizeof(send_count)) {
  156.             send_count = (data.data[25] << 24) | (data.data[24] << 16)
  157.                          | (data.data[23] << 8) | data.data[22];
  158.         }
  159.         recv_count++;
  160.         /* process light control */
  161.         mesh_light_process(&from, data.data, data.size);
  162.         if (!(recv_count % 1)) {
  163.             ESP_LOGW(MESH_TAG,
  164.                      "[#RX:%d/%d][L:%d] parent:"MACSTR", receive from "MACSTR", size:%d, heap:%d, flag:%d[err:0x%x, proto:%d, tos:%d]",
  165.                      recv_count, send_count, mesh_layer,
  166.                      MAC2STR(mesh_parent_addr.addr), MAC2STR(from.addr),
  167.                      data.size, esp_get_free_heap_size(), flag, err, data.proto,
  168.                      data.tos);
  169.         }
  170.     }
  171.     vTaskDelete(NULL);
  172. }
  173.  
  174. esp_err_t esp_mesh_comm_p2p_start(void)
  175. {
  176.     static bool is_comm_p2p_started = false;
  177.     if (!is_comm_p2p_started) {
  178.         is_comm_p2p_started = true;
  179.         xTaskCreate(esp_mesh_p2p_tx_main, "MPTX", 3072, NULL, 5, NULL);
  180.         xTaskCreate(esp_mesh_p2p_rx_main, "MPRX", 3072, NULL, 5, NULL);
  181.     }
  182.     return ESP_OK;
  183. }
  184.  
  185. void mesh_event_handler(mesh_event_t event)
  186. {
  187.     mesh_addr_t id = {0,};
  188.     static uint8_t last_layer = 0;
  189.     ESP_LOGD(MESH_TAG, "esp_event_handler:%d", event.id);
  190.  
  191.     switch (event.id) {
  192.     case MESH_EVENT_STARTED:
  193.         esp_mesh_get_id(&id);
  194.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_STARTED>ID:"MACSTR"", MAC2STR(id.addr));
  195.         is_mesh_connected = false;
  196.         mesh_layer = esp_mesh_get_layer();
  197.         break;
  198.     case MESH_EVENT_STOPPED:
  199.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_STOPPED>");
  200.         is_mesh_connected = false;
  201.         mesh_layer = esp_mesh_get_layer();
  202.         break;
  203.     case MESH_EVENT_CHILD_CONNECTED:
  204.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_CHILD_CONNECTED>aid:%d, "MACSTR"",
  205.                  event.info.child_connected.aid,
  206.                  MAC2STR(event.info.child_connected.mac));
  207.         break;
  208.     case MESH_EVENT_CHILD_DISCONNECTED:
  209.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_CHILD_DISCONNECTED>aid:%d, "MACSTR"",
  210.                  event.info.child_disconnected.aid,
  211.                  MAC2STR(event.info.child_disconnected.mac));
  212.         break;
  213.     case MESH_EVENT_ROUTING_TABLE_ADD:
  214.         ESP_LOGW(MESH_TAG, "<MESH_EVENT_ROUTING_TABLE_ADD>add %d, new:%d",
  215.                  event.info.routing_table.rt_size_change,
  216.                  event.info.routing_table.rt_size_new);
  217.         break;
  218.     case MESH_EVENT_ROUTING_TABLE_REMOVE:
  219.         ESP_LOGW(MESH_TAG, "<MESH_EVENT_ROUTING_TABLE_REMOVE>remove %d, new:%d",
  220.                  event.info.routing_table.rt_size_change,
  221.                  event.info.routing_table.rt_size_new);
  222.         break;
  223.     case MESH_EVENT_NO_PARENT_FOUND:
  224.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_NO_PARENT_FOUND>scan times:%d",
  225.                  event.info.no_parent.scan_times);
  226.         /* TODO handler for the failure */
  227.         break;
  228.     case MESH_EVENT_PARENT_CONNECTED:
  229.         esp_mesh_get_id(&id);
  230.         mesh_layer = event.info.connected.self_layer;
  231.         memcpy(&mesh_parent_addr.addr, event.info.connected.connected.bssid, 6);
  232.         ESP_LOGI(MESH_TAG,
  233.                  "<MESH_EVENT_PARENT_CONNECTED>layer:%d-->%d, parent:"MACSTR"%s, ID:"MACSTR"",
  234.                  last_layer, mesh_layer, MAC2STR(mesh_parent_addr.addr),
  235.                  esp_mesh_is_root() ? "<ROOT>" :
  236.                  (mesh_layer == 2) ? "<layer2>" : "", MAC2STR(id.addr));
  237.         last_layer = mesh_layer;
  238.         mesh_connected_indicator(mesh_layer);
  239.         is_mesh_connected = true;
  240.         if (esp_mesh_is_root()) {
  241.             tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
  242.         }
  243.         esp_mesh_comm_p2p_start();
  244.         break;
  245.     case MESH_EVENT_PARENT_DISCONNECTED:
  246.         ESP_LOGI(MESH_TAG,
  247.                  "<MESH_EVENT_PARENT_DISCONNECTED>reason:%d",
  248.                  event.info.disconnected.reason);
  249.         is_mesh_connected = false;
  250.         mesh_disconnected_indicator();
  251.         mesh_layer = esp_mesh_get_layer();
  252.         break;
  253.     case MESH_EVENT_LAYER_CHANGE:
  254.         mesh_layer = event.info.layer_change.new_layer;
  255.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_LAYER_CHANGE>layer:%d-->%d%s",
  256.                  last_layer, mesh_layer,
  257.                  esp_mesh_is_root() ? "<ROOT>" :
  258.                  (mesh_layer == 2) ? "<layer2>" : "");
  259.         last_layer = mesh_layer;
  260.         mesh_connected_indicator(mesh_layer);
  261.         break;
  262.     case MESH_EVENT_ROOT_ADDRESS:
  263.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_ADDRESS>root address:"MACSTR"",
  264.                  MAC2STR(event.info.root_addr.addr));
  265.         break;
  266.     case MESH_EVENT_ROOT_GOT_IP:
  267.         /* root starts to connect to server */
  268.         ESP_LOGI(MESH_TAG,
  269.                  "<MESH_EVENT_ROOT_GOT_IP>sta ip: " IPSTR ", mask: " IPSTR ", gw: " IPSTR,
  270.                  IP2STR(&event.info.got_ip.ip_info.ip),
  271.                  IP2STR(&event.info.got_ip.ip_info.netmask),
  272.                  IP2STR(&event.info.got_ip.ip_info.gw));
  273.         break;
  274.     case MESH_EVENT_ROOT_LOST_IP:
  275.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_LOST_IP>");
  276.         break;
  277.     case MESH_EVENT_VOTE_STARTED:
  278.         ESP_LOGI(MESH_TAG,
  279.                  "<MESH_EVENT_VOTE_STARTED>attempts:%d, reason:%d, rc_addr:"MACSTR"",
  280.                  event.info.vote_started.attempts,
  281.                  event.info.vote_started.reason,
  282.                  MAC2STR(event.info.vote_started.rc_addr.addr));
  283.         break;
  284.     case MESH_EVENT_VOTE_STOPPED:
  285.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_VOTE_STOPPED>");
  286.         break;
  287.     case MESH_EVENT_ROOT_SWITCH_REQ:
  288.         ESP_LOGI(MESH_TAG,
  289.                  "<MESH_EVENT_ROOT_SWITCH_REQ>reason:%d, rc_addr:"MACSTR"",
  290.                  event.info.switch_req.reason,
  291.                  MAC2STR( event.info.switch_req.rc_addr.addr));
  292.         break;
  293.     case MESH_EVENT_ROOT_SWITCH_ACK:
  294.         /* new root */
  295.         mesh_layer = esp_mesh_get_layer();
  296.         esp_mesh_get_parent_bssid(&mesh_parent_addr);
  297.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_SWITCH_ACK>layer:%d, parent:"MACSTR"", mesh_layer, MAC2STR(mesh_parent_addr.addr));
  298.         break;
  299.     case MESH_EVENT_TODS_STATE:
  300.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_TODS_REACHABLE>state:%d",
  301.                  event.info.toDS_state);
  302.         break;
  303.     case MESH_EVENT_ROOT_FIXED:
  304.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_FIXED>%s",
  305.                  event.info.root_fixed.is_fixed ? "fixed" : "not fixed");
  306.         break;
  307.     case MESH_EVENT_ROOT_ASKED_YIELD:
  308.         ESP_LOGI(MESH_TAG,
  309.                  "<MESH_EVENT_ROOT_ASKED_YIELD>"MACSTR", rssi:%d, capacity:%d",
  310.                  MAC2STR(event.info.root_conflict.addr),
  311.                  event.info.root_conflict.rssi,
  312.                  event.info.root_conflict.capacity);
  313.         break;
  314.     case MESH_EVENT_CHANNEL_SWITCH:
  315.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_CHANNEL_SWITCH>new channel:%d", event.info.channel_switch.channel);
  316.         break;
  317.     case MESH_EVENT_SCAN_DONE:
  318.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_SCAN_DONE>number:%d",
  319.                  event.info.scan_done.number);
  320.         break;
  321.     case MESH_EVENT_NETWORK_STATE:
  322.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_NETWORK_STATE>is_rootless:%d",
  323.                  event.info.network_state.is_rootless);
  324.         break;
  325.     case MESH_EVENT_STOP_RECONNECTION:
  326.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_STOP_RECONNECTION>");
  327.         break;
  328.     case MESH_EVENT_FIND_NETWORK:
  329.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_FIND_NETWORK>new channel:%d, router BSSID:"MACSTR"",
  330.                  event.info.find_network.channel, MAC2STR(event.info.find_network.router_bssid));
  331.         break;
  332.     case MESH_EVENT_ROUTER_SWITCH:
  333.         ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROUTER_SWITCH>new router:%s, channel:%d, "MACSTR"",
  334.                  event.info.router_switch.ssid, event.info.router_switch.channel, MAC2STR(event.info.router_switch.bssid));
  335.         break;
  336.     default:
  337.         ESP_LOGI(MESH_TAG, "unknown id:%d", event.id);
  338.         break;
  339.     }
  340. }
  341.  
  342. //////////////////////////////////////////////////////////////
  343.  
  344. /* An HTTP GET handler */
  345. esp_err_t hello_get_handler(httpd_req_t *req)
  346. {
  347.     char*  buf;
  348.     size_t buf_len;
  349.  
  350.     /* Get header value string length and allocate memory for length + 1,
  351.      * extra byte for null termination */
  352.     buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1;
  353.     if (buf_len > 1) {
  354.         buf = malloc(buf_len);
  355.         /* Copy null terminated value string into buffer */
  356.         if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
  357.             ESP_LOGI(TAG, "Found header => Host: %s", buf);
  358.         }
  359.         free(buf);
  360.     }
  361.  
  362.     buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-2") + 1;
  363.     if (buf_len > 1) {
  364.         buf = malloc(buf_len);
  365.         if (httpd_req_get_hdr_value_str(req, "Test-Header-2", buf, buf_len) == ESP_OK) {
  366.             ESP_LOGI(TAG, "Found header => Test-Header-2: %s", buf);
  367.         }
  368.         free(buf);
  369.     }
  370.  
  371.     buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-1") + 1;
  372.     if (buf_len > 1) {
  373.         buf = malloc(buf_len);
  374.         if (httpd_req_get_hdr_value_str(req, "Test-Header-1", buf, buf_len) == ESP_OK) {
  375.             ESP_LOGI(TAG, "Found header => Test-Header-1: %s", buf);
  376.         }
  377.         free(buf);
  378.     }
  379.  
  380.     /* Read URL query string length and allocate memory for length + 1,
  381.      * extra byte for null termination */
  382.     buf_len = httpd_req_get_url_query_len(req) + 1;
  383.     if (buf_len > 1) {
  384.         buf = malloc(buf_len);
  385.         if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
  386.             ESP_LOGI(TAG, "Found URL query => %s", buf);
  387.             char param[32];
  388.             /* Get value of expected key from query string */
  389.             if (httpd_query_key_value(buf, "query1", param, sizeof(param)) == ESP_OK) {
  390.                 ESP_LOGI(TAG, "Found URL query parameter => query1=%s", param);
  391.             }
  392.             if (httpd_query_key_value(buf, "query3", param, sizeof(param)) == ESP_OK) {
  393.                 ESP_LOGI(TAG, "Found URL query parameter => query3=%s", param);
  394.             }
  395.             if (httpd_query_key_value(buf, "query2", param, sizeof(param)) == ESP_OK) {
  396.                 ESP_LOGI(TAG, "Found URL query parameter => query2=%s", param);
  397.             }
  398.         }
  399.         free(buf);
  400.     }
  401.  
  402.     /* Set some custom headers */
  403.     httpd_resp_set_hdr(req, "Custom-Header-1", "Custom-Value-1");
  404.     httpd_resp_set_hdr(req, "Custom-Header-2", "Custom-Value-2");
  405.  
  406.     /* Send response with custom headers and body set as the
  407.      * string passed in user context*/
  408.     const char* resp_str = (const char*) req->user_ctx;
  409.     httpd_resp_send(req, resp_str, strlen(resp_str));
  410.  
  411.     /* After sending the HTTP response the old HTTP request
  412.      * headers are lost. Check if HTTP request headers can be read now. */
  413.     if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
  414.         ESP_LOGI(TAG, "Request headers lost");
  415.     }
  416.     return ESP_OK;
  417. }
  418.  
  419. httpd_uri_t hello = {
  420.     .uri       = "/hello",
  421.     .method    = HTTP_GET,
  422.     .handler   = hello_get_handler,
  423.     /* Let's pass response string in user
  424.      * context to demonstrate it's usage */
  425.     .user_ctx  = "Hello World!"
  426. };
  427.  
  428. /* An HTTP POST handler */
  429. esp_err_t echo_post_handler(httpd_req_t *req)
  430. {
  431.     char buf[100];
  432.     int ret, remaining = req->content_len;
  433.  
  434.     while (remaining > 0) {
  435.         /* Read the data for the request */
  436.         if ((ret = httpd_req_recv(req, buf,
  437.                         MIN(remaining, sizeof(buf)))) <= 0) {
  438.             if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
  439.                 /* Retry receiving if timeout occurred */
  440.                 continue;
  441.             }
  442.             return ESP_FAIL;
  443.         }
  444.  
  445.         /* Send back the same data */
  446.         httpd_resp_send_chunk(req, buf, ret);
  447.         remaining -= ret;
  448.  
  449.         /* Log data received */
  450.         ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
  451.         ESP_LOGI(TAG, "%.*s", ret, buf);
  452.         ESP_LOGI(TAG, "====================================");
  453.     }
  454.  
  455.     // End response
  456.     httpd_resp_send_chunk(req, NULL, 0);
  457.     return ESP_OK;
  458. }
  459.  
  460. httpd_uri_t echo = {
  461.     .uri       = "/echo",
  462.     .method    = HTTP_POST,
  463.     .handler   = echo_post_handler,
  464.     .user_ctx  = NULL
  465. };
  466.  
  467. /* An HTTP PUT handler. This demonstrates realtime
  468.  * registration and deregistration of URI handlers
  469.  */
  470. esp_err_t ctrl_put_handler(httpd_req_t *req)
  471. {
  472.     char buf;
  473.     int ret;
  474.  
  475.     if ((ret = httpd_req_recv(req, &buf, 1)) <= 0) {
  476.         if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
  477.             httpd_resp_send_408(req);
  478.         }
  479.         return ESP_FAIL;
  480.     }
  481.  
  482.     if (buf == '0') {
  483.         /* Handler can be unregistered using the uri string */
  484.         ESP_LOGI(TAG, "Unregistering /hello and /echo URIs");
  485.         httpd_unregister_uri(req->handle, "/hello");
  486.         httpd_unregister_uri(req->handle, "/echo");
  487.     }
  488.     else {
  489.         ESP_LOGI(TAG, "Registering /hello and /echo URIs");
  490.         httpd_register_uri_handler(req->handle, &hello);
  491.         httpd_register_uri_handler(req->handle, &echo);
  492.     }
  493.  
  494.     /* Respond with empty body */
  495.     httpd_resp_send(req, NULL, 0);
  496.     return ESP_OK;
  497. }
  498.  
  499. httpd_uri_t ctrl = {
  500.     .uri       = "/ctrl",
  501.     .method    = HTTP_PUT,
  502.     .handler   = ctrl_put_handler,
  503.     .user_ctx  = NULL
  504. };
  505.  
  506. httpd_handle_t start_webserver(void)
  507. {
  508.     httpd_handle_t server = NULL;
  509.     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  510.  
  511.     // Start the httpd server
  512.     ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
  513.     if (httpd_start(&server, &config) == ESP_OK) {
  514.         // Set URI handlers
  515.         ESP_LOGI(TAG, "Registering URI handlers");
  516.         httpd_register_uri_handler(server, &hello);
  517.         httpd_register_uri_handler(server, &echo);
  518.         httpd_register_uri_handler(server, &ctrl);
  519.         return server;
  520.     }
  521.  
  522.     ESP_LOGI(TAG, "Error starting server!");
  523.     return NULL;
  524. }
  525.  
  526. void stop_webserver(httpd_handle_t server)
  527. {
  528.     // Stop the httpd server
  529.     httpd_stop(server);
  530. }
  531.  
  532. static esp_err_t event_handler(void *ctx, system_event_t *event)
  533. {
  534.     httpd_handle_t *server = (httpd_handle_t *) ctx;
  535.  
  536.     switch(event->event_id) {
  537.     case SYSTEM_EVENT_STA_START:
  538.         ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
  539.         ESP_ERROR_CHECK(esp_wifi_connect());
  540.         break;
  541.     case SYSTEM_EVENT_STA_GOT_IP:
  542.         ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
  543.         ESP_LOGI(TAG, "Got IP: '%s'",
  544.                 ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
  545.  
  546.         /* Start the web server */
  547.         if (*server == NULL) {
  548.             *server = start_webserver();
  549.         }
  550.         break;
  551.     case SYSTEM_EVENT_STA_DISCONNECTED:
  552.         ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
  553.         ESP_ERROR_CHECK(esp_wifi_connect());
  554.  
  555.         /* Stop the web server */
  556.         if (*server) {
  557.             stop_webserver(*server);
  558.             *server = NULL;
  559.         }
  560.         break;
  561.     default:
  562.         break;
  563.     }
  564.     return ESP_OK;
  565. }
  566.  
  567. void app_main(void)
  568. {
  569.     static httpd_handle_t server = NULL;
  570.     ESP_ERROR_CHECK(mesh_light_init());
  571.     ESP_ERROR_CHECK(nvs_flash_init());
  572.     tcpip_adapter_init();
  573.     // ESP_ERROR_CHECK(tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP));
  574.     // ESP_ERROR_CHECK(tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA));
  575.     ESP_ERROR_CHECK(esp_event_loop_init(event_handler, &server));
  576.     wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
  577.     ESP_ERROR_CHECK(esp_wifi_init(&config));
  578.     ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
  579.     wifi_config_t wifi_config = {
  580.         .sta = {
  581.             .ssid = CONFIG_MESH_ROUTER_SSID,
  582.             .password = CONFIG_MESH_ROUTER_PASSWD,
  583.         },
  584.     };
  585.     ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
  586.     ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
  587.     ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
  588.     ESP_ERROR_CHECK(esp_wifi_start());
  589.  
  590.     ESP_ERROR_CHECK(esp_mesh_init());
  591.     ESP_ERROR_CHECK(esp_mesh_set_max_layer(CONFIG_MESH_MAX_LAYER));
  592.     ESP_ERROR_CHECK(esp_mesh_set_vote_percentage(1));
  593.     ESP_ERROR_CHECK(esp_mesh_set_ap_assoc_expire(10));
  594. #ifdef MESH_FIX_ROOT
  595.     ESP_ERROR_CHECK(esp_mesh_fix_root(1));
  596. #endif
  597.     mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT();
  598.     /* mesh ID */
  599.     memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6);
  600.     /* mesh event callback */
  601.     cfg.event_cb = &mesh_event_handler;
  602.     /* router */
  603.     cfg.channel = CONFIG_MESH_CHANNEL;
  604.     cfg.router.ssid_len = strlen(CONFIG_MESH_ROUTER_SSID);
  605.     memcpy((uint8_t *) &cfg.router.ssid, CONFIG_MESH_ROUTER_SSID, cfg.router.ssid_len);
  606.     memcpy((uint8_t *) &cfg.router.password, CONFIG_MESH_ROUTER_PASSWD,
  607.            strlen(CONFIG_MESH_ROUTER_PASSWD));
  608.     /* mesh softAP */
  609.     ESP_ERROR_CHECK(esp_mesh_set_ap_authmode(CONFIG_MESH_AP_AUTHMODE));
  610.     cfg.mesh_ap.max_connection = CONFIG_MESH_AP_CONNECTIONS;
  611.     memcpy((uint8_t *) &cfg.mesh_ap.password, CONFIG_MESH_AP_PASSWD,
  612.            strlen(CONFIG_MESH_AP_PASSWD));
  613.     ESP_ERROR_CHECK(esp_mesh_set_config(&cfg));
  614.     /* mesh start */
  615.     // ESP_ERROR_CHECK(esp_mesh_start());
  616.     // ESP_LOGI(MESH_TAG, "mesh starts successfully, heap:%d, %s\n",  esp_get_free_heap_size(),
  617.     //          esp_mesh_is_root_fixed() ? "root fixed" : "root not fixed");
  618. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement