1 /* Mesh Internal Communication Example
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 #include <string.h>
10 #include "esp_wifi.h"
11 #include "esp_system.h"
12 #include "esp_event.h"
13 #include "esp_log.h"
14 #include "esp_mesh.h"
15 #include "nvs_flash.h"
16 #include "mesh_netif.h"
17 #include "driver/gpio.h"
18 #include "freertos/semphr.h"
19
20 /*******************************************************
21 * Macros
22 *******************************************************/
23 #define EXAMPLE_BUTTON_GPIO 0
24
25 // commands for internal mesh communication:
26 // <CMD> <PAYLOAD>, where CMD is one character, payload is variable dep. on command
27 #define CMD_KEYPRESSED 0x55
28 // CMD_KEYPRESSED: payload is always 6 bytes identifying address of node sending keypress event
29 #define CMD_ROUTE_TABLE 0x56
30 // CMD_KEYPRESSED: payload is a multiple of 6 listing addresses in a routing table
31 /*******************************************************
32 * Constants
33 *******************************************************/
34 static const char *MESH_TAG = "mesh_main";
35 static const uint8_t MESH_ID[6] = { 0x77, 0x77, 0x77, 0x77, 0x77, 0x76};
36
37 /*******************************************************
38 * Variable Definitions
39 *******************************************************/
40 static bool is_running = true;
41 static mesh_addr_t mesh_parent_addr;
42 static int mesh_layer = -1;
43 static esp_ip4_addr_t s_current_ip;
44 static mesh_addr_t s_route_table[CONFIG_MESH_ROUTE_TABLE_SIZE];
45 static int s_route_table_size = 0;
46 static SemaphoreHandle_t s_route_table_lock = NULL;
47 static uint8_t s_mesh_tx_payload[CONFIG_MESH_ROUTE_TABLE_SIZE*6+1];
48
49
50 /*******************************************************
51 * Function Declarations
52 *******************************************************/
53 // interaction with public mqtt broker
54 void mqtt_app_start(void);
55 void mqtt_app_publish(char* topic, char *publish_string);
56
57 /*******************************************************
58 * Function Definitions
59 *******************************************************/
60
initialise_button(void)61 static void initialise_button(void)
62 {
63 gpio_config_t io_conf = {0};
64 io_conf.intr_type = GPIO_INTR_DISABLE;
65 io_conf.pin_bit_mask = BIT64(EXAMPLE_BUTTON_GPIO);
66 io_conf.mode = GPIO_MODE_INPUT;
67 io_conf.pull_up_en = 1;
68 io_conf.pull_down_en = 0;
69 gpio_config(&io_conf);
70 }
71
recv_cb(mesh_addr_t * from,mesh_data_t * data)72 void static recv_cb(mesh_addr_t *from, mesh_data_t *data)
73 {
74 if (data->data[0] == CMD_ROUTE_TABLE) {
75 int size = data->size - 1;
76 if (s_route_table_lock == NULL || size%6 != 0) {
77 ESP_LOGE(MESH_TAG, "Error in receiving raw mesh data: Unexpected size");
78 return;
79 }
80 xSemaphoreTake(s_route_table_lock, portMAX_DELAY);
81 s_route_table_size = size / 6;
82 for (int i=0; i < s_route_table_size; ++i) {
83 ESP_LOGI(MESH_TAG, "Received Routing table [%d] "
84 MACSTR, i, MAC2STR(data->data + 6*i + 1));
85 }
86 memcpy(&s_route_table, data->data + 1, size);
87 xSemaphoreGive(s_route_table_lock);
88 } else if (data->data[0] == CMD_KEYPRESSED) {
89 if (data->size != 7) {
90 ESP_LOGE(MESH_TAG, "Error in receiving raw mesh data: Unexpected size");
91 return;
92 }
93 ESP_LOGW(MESH_TAG, "Keypressed detected on node: "
94 MACSTR, MAC2STR(data->data + 1));
95 } else {
96 ESP_LOGE(MESH_TAG, "Error in receiving raw mesh data: Unknown command");
97 }
98 }
99
check_button(void * args)100 static void check_button(void* args)
101 {
102 static bool old_level = true;
103 bool new_level;
104 bool run_check_button = true;
105 initialise_button();
106 while (run_check_button) {
107 new_level = gpio_get_level(EXAMPLE_BUTTON_GPIO);
108 if (!new_level && old_level) {
109 if (s_route_table_size && !esp_mesh_is_root()) {
110 ESP_LOGW(MESH_TAG, "Key pressed!");
111 mesh_data_t data;
112 uint8_t *my_mac = mesh_netif_get_station_mac();
113 uint8_t data_to_send[6+1] = { CMD_KEYPRESSED, };
114 esp_err_t err;
115 char print[6*3+1]; // MAC addr size + terminator
116 memcpy(data_to_send + 1, my_mac, 6);
117 data.size = 7;
118 data.proto = MESH_PROTO_BIN;
119 data.tos = MESH_TOS_P2P;
120 data.data = data_to_send;
121 snprintf(print, sizeof(print),MACSTR, MAC2STR(my_mac));
122 mqtt_app_publish("/topic/ip_mesh/key_pressed", print);
123 xSemaphoreTake(s_route_table_lock, portMAX_DELAY);
124 for (int i = 0; i < s_route_table_size; i++) {
125 if (MAC_ADDR_EQUAL(s_route_table[i].addr, my_mac)) {
126 continue;
127 }
128 err = esp_mesh_send(&s_route_table[i], &data, MESH_DATA_P2P, NULL, 0);
129 ESP_LOGI(MESH_TAG, "Sending to [%d] "
130 MACSTR ": sent with err code: %d", i, MAC2STR(s_route_table[i].addr), err);
131 }
132 xSemaphoreGive(s_route_table_lock);
133 }
134 }
135 old_level = new_level;
136 vTaskDelay(50 / portTICK_PERIOD_MS);
137 }
138 vTaskDelete(NULL);
139
140 }
141
142
esp_mesh_mqtt_task(void * arg)143 void esp_mesh_mqtt_task(void *arg)
144 {
145 is_running = true;
146 char *print;
147 mesh_data_t data;
148 esp_err_t err;
149 mqtt_app_start();
150 while (is_running) {
151 asprintf(&print, "layer:%d IP:" IPSTR, esp_mesh_get_layer(), IP2STR(&s_current_ip));
152 ESP_LOGI(MESH_TAG, "Tried to publish %s", print);
153 mqtt_app_publish("/topic/ip_mesh", print);
154 free(print);
155 if (esp_mesh_is_root()) {
156 esp_mesh_get_routing_table((mesh_addr_t *) &s_route_table,
157 CONFIG_MESH_ROUTE_TABLE_SIZE * 6, &s_route_table_size);
158 data.size = s_route_table_size * 6 + 1;
159 data.proto = MESH_PROTO_BIN;
160 data.tos = MESH_TOS_P2P;
161 s_mesh_tx_payload[0] = CMD_ROUTE_TABLE;
162 memcpy(s_mesh_tx_payload + 1, s_route_table, s_route_table_size*6);
163 data.data = s_mesh_tx_payload;
164 for (int i = 0; i < s_route_table_size; i++) {
165 err = esp_mesh_send(&s_route_table[i], &data, MESH_DATA_P2P, NULL, 0);
166 ESP_LOGI(MESH_TAG, "Sending routing table to [%d] "
167 MACSTR ": sent with err code: %d", i, MAC2STR(s_route_table[i].addr), err);
168 }
169 }
170 vTaskDelay(2 * 1000 / portTICK_RATE_MS);
171 }
172 vTaskDelete(NULL);
173 }
174
esp_mesh_comm_mqtt_task_start(void)175 esp_err_t esp_mesh_comm_mqtt_task_start(void)
176 {
177 static bool is_comm_mqtt_task_started = false;
178
179 s_route_table_lock = xSemaphoreCreateMutex();
180
181 if (!is_comm_mqtt_task_started) {
182 xTaskCreate(esp_mesh_mqtt_task, "mqtt task", 3072, NULL, 5, NULL);
183 xTaskCreate(check_button, "check button task", 3072, NULL, 5, NULL);
184 is_comm_mqtt_task_started = true;
185 }
186 return ESP_OK;
187 }
188
mesh_event_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)189 void mesh_event_handler(void *arg, esp_event_base_t event_base,
190 int32_t event_id, void *event_data)
191 {
192 mesh_addr_t id = {0,};
193 static uint8_t last_layer = 0;
194
195 switch (event_id) {
196 case MESH_EVENT_STARTED: {
197 esp_mesh_get_id(&id);
198 ESP_LOGI(MESH_TAG, "<MESH_EVENT_MESH_STARTED>ID:"MACSTR"", MAC2STR(id.addr));
199 mesh_layer = esp_mesh_get_layer();
200 }
201 break;
202 case MESH_EVENT_STOPPED: {
203 ESP_LOGI(MESH_TAG, "<MESH_EVENT_STOPPED>");
204 mesh_layer = esp_mesh_get_layer();
205 }
206 break;
207 case MESH_EVENT_CHILD_CONNECTED: {
208 mesh_event_child_connected_t *child_connected = (mesh_event_child_connected_t *)event_data;
209 ESP_LOGI(MESH_TAG, "<MESH_EVENT_CHILD_CONNECTED>aid:%d, "MACSTR"",
210 child_connected->aid,
211 MAC2STR(child_connected->mac));
212 }
213 break;
214 case MESH_EVENT_CHILD_DISCONNECTED: {
215 mesh_event_child_disconnected_t *child_disconnected = (mesh_event_child_disconnected_t *)event_data;
216 ESP_LOGI(MESH_TAG, "<MESH_EVENT_CHILD_DISCONNECTED>aid:%d, "MACSTR"",
217 child_disconnected->aid,
218 MAC2STR(child_disconnected->mac));
219 }
220 break;
221 case MESH_EVENT_ROUTING_TABLE_ADD: {
222 mesh_event_routing_table_change_t *routing_table = (mesh_event_routing_table_change_t *)event_data;
223 ESP_LOGW(MESH_TAG, "<MESH_EVENT_ROUTING_TABLE_ADD>add %d, new:%d",
224 routing_table->rt_size_change,
225 routing_table->rt_size_new);
226 }
227 break;
228 case MESH_EVENT_ROUTING_TABLE_REMOVE: {
229 mesh_event_routing_table_change_t *routing_table = (mesh_event_routing_table_change_t *)event_data;
230 ESP_LOGW(MESH_TAG, "<MESH_EVENT_ROUTING_TABLE_REMOVE>remove %d, new:%d",
231 routing_table->rt_size_change,
232 routing_table->rt_size_new);
233 }
234 break;
235 case MESH_EVENT_NO_PARENT_FOUND: {
236 mesh_event_no_parent_found_t *no_parent = (mesh_event_no_parent_found_t *)event_data;
237 ESP_LOGI(MESH_TAG, "<MESH_EVENT_NO_PARENT_FOUND>scan times:%d",
238 no_parent->scan_times);
239 }
240 /* TODO handler for the failure */
241 break;
242 case MESH_EVENT_PARENT_CONNECTED: {
243 mesh_event_connected_t *connected = (mesh_event_connected_t *)event_data;
244 esp_mesh_get_id(&id);
245 mesh_layer = connected->self_layer;
246 memcpy(&mesh_parent_addr.addr, connected->connected.bssid, 6);
247 ESP_LOGI(MESH_TAG,
248 "<MESH_EVENT_PARENT_CONNECTED>layer:%d-->%d, parent:"MACSTR"%s, ID:"MACSTR"",
249 last_layer, mesh_layer, MAC2STR(mesh_parent_addr.addr),
250 esp_mesh_is_root() ? "<ROOT>" :
251 (mesh_layer == 2) ? "<layer2>" : "", MAC2STR(id.addr));
252 last_layer = mesh_layer;
253 mesh_netifs_start(esp_mesh_is_root());
254 }
255 break;
256 case MESH_EVENT_PARENT_DISCONNECTED: {
257 mesh_event_disconnected_t *disconnected = (mesh_event_disconnected_t *)event_data;
258 ESP_LOGI(MESH_TAG,
259 "<MESH_EVENT_PARENT_DISCONNECTED>reason:%d",
260 disconnected->reason);
261 mesh_layer = esp_mesh_get_layer();
262 mesh_netifs_stop();
263 }
264 break;
265 case MESH_EVENT_LAYER_CHANGE: {
266 mesh_event_layer_change_t *layer_change = (mesh_event_layer_change_t *)event_data;
267 mesh_layer = layer_change->new_layer;
268 ESP_LOGI(MESH_TAG, "<MESH_EVENT_LAYER_CHANGE>layer:%d-->%d%s",
269 last_layer, mesh_layer,
270 esp_mesh_is_root() ? "<ROOT>" :
271 (mesh_layer == 2) ? "<layer2>" : "");
272 last_layer = mesh_layer;
273 }
274 break;
275 case MESH_EVENT_ROOT_ADDRESS: {
276 mesh_event_root_address_t *root_addr = (mesh_event_root_address_t *)event_data;
277 ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_ADDRESS>root address:"MACSTR"",
278 MAC2STR(root_addr->addr));
279 }
280 break;
281 case MESH_EVENT_VOTE_STARTED: {
282 mesh_event_vote_started_t *vote_started = (mesh_event_vote_started_t *)event_data;
283 ESP_LOGI(MESH_TAG,
284 "<MESH_EVENT_VOTE_STARTED>attempts:%d, reason:%d, rc_addr:"MACSTR"",
285 vote_started->attempts,
286 vote_started->reason,
287 MAC2STR(vote_started->rc_addr.addr));
288 }
289 break;
290 case MESH_EVENT_VOTE_STOPPED: {
291 ESP_LOGI(MESH_TAG, "<MESH_EVENT_VOTE_STOPPED>");
292 break;
293 }
294 case MESH_EVENT_ROOT_SWITCH_REQ: {
295 mesh_event_root_switch_req_t *switch_req = (mesh_event_root_switch_req_t *)event_data;
296 ESP_LOGI(MESH_TAG,
297 "<MESH_EVENT_ROOT_SWITCH_REQ>reason:%d, rc_addr:"MACSTR"",
298 switch_req->reason,
299 MAC2STR( switch_req->rc_addr.addr));
300 }
301 break;
302 case MESH_EVENT_ROOT_SWITCH_ACK: {
303 /* new root */
304 mesh_layer = esp_mesh_get_layer();
305 esp_mesh_get_parent_bssid(&mesh_parent_addr);
306 ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_SWITCH_ACK>layer:%d, parent:"MACSTR"", mesh_layer, MAC2STR(mesh_parent_addr.addr));
307 }
308 break;
309 case MESH_EVENT_TODS_STATE: {
310 mesh_event_toDS_state_t *toDs_state = (mesh_event_toDS_state_t *)event_data;
311 ESP_LOGI(MESH_TAG, "<MESH_EVENT_TODS_REACHABLE>state:%d", *toDs_state);
312 }
313 break;
314 case MESH_EVENT_ROOT_FIXED: {
315 mesh_event_root_fixed_t *root_fixed = (mesh_event_root_fixed_t *)event_data;
316 ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROOT_FIXED>%s",
317 root_fixed->is_fixed ? "fixed" : "not fixed");
318 }
319 break;
320 case MESH_EVENT_ROOT_ASKED_YIELD: {
321 mesh_event_root_conflict_t *root_conflict = (mesh_event_root_conflict_t *)event_data;
322 ESP_LOGI(MESH_TAG,
323 "<MESH_EVENT_ROOT_ASKED_YIELD>"MACSTR", rssi:%d, capacity:%d",
324 MAC2STR(root_conflict->addr),
325 root_conflict->rssi,
326 root_conflict->capacity);
327 }
328 break;
329 case MESH_EVENT_CHANNEL_SWITCH: {
330 mesh_event_channel_switch_t *channel_switch = (mesh_event_channel_switch_t *)event_data;
331 ESP_LOGI(MESH_TAG, "<MESH_EVENT_CHANNEL_SWITCH>new channel:%d", channel_switch->channel);
332 }
333 break;
334 case MESH_EVENT_SCAN_DONE: {
335 mesh_event_scan_done_t *scan_done = (mesh_event_scan_done_t *)event_data;
336 ESP_LOGI(MESH_TAG, "<MESH_EVENT_SCAN_DONE>number:%d",
337 scan_done->number);
338 }
339 break;
340 case MESH_EVENT_NETWORK_STATE: {
341 mesh_event_network_state_t *network_state = (mesh_event_network_state_t *)event_data;
342 ESP_LOGI(MESH_TAG, "<MESH_EVENT_NETWORK_STATE>is_rootless:%d",
343 network_state->is_rootless);
344 }
345 break;
346 case MESH_EVENT_STOP_RECONNECTION: {
347 ESP_LOGI(MESH_TAG, "<MESH_EVENT_STOP_RECONNECTION>");
348 }
349 break;
350 case MESH_EVENT_FIND_NETWORK: {
351 mesh_event_find_network_t *find_network = (mesh_event_find_network_t *)event_data;
352 ESP_LOGI(MESH_TAG, "<MESH_EVENT_FIND_NETWORK>new channel:%d, router BSSID:"MACSTR"",
353 find_network->channel, MAC2STR(find_network->router_bssid));
354 }
355 break;
356 case MESH_EVENT_ROUTER_SWITCH: {
357 mesh_event_router_switch_t *router_switch = (mesh_event_router_switch_t *)event_data;
358 ESP_LOGI(MESH_TAG, "<MESH_EVENT_ROUTER_SWITCH>new router:%s, channel:%d, "MACSTR"",
359 router_switch->ssid, router_switch->channel, MAC2STR(router_switch->bssid));
360 }
361 break;
362 default:
363 ESP_LOGI(MESH_TAG, "unknown id:%d", event_id);
364 break;
365 }
366 }
367
ip_event_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)368 void ip_event_handler(void *arg, esp_event_base_t event_base,
369 int32_t event_id, void *event_data)
370 {
371 ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
372 ESP_LOGI(MESH_TAG, "<IP_EVENT_STA_GOT_IP>IP:" IPSTR, IP2STR(&event->ip_info.ip));
373 s_current_ip.addr = event->ip_info.ip.addr;
374 #if !CONFIG_MESH_USE_GLOBAL_DNS_IP
375 esp_netif_t *netif = event->esp_netif;
376 esp_netif_dns_info_t dns;
377 ESP_ERROR_CHECK(esp_netif_get_dns_info(netif, ESP_NETIF_DNS_MAIN, &dns));
378 mesh_netif_start_root_ap(esp_mesh_is_root(), dns.ip.u_addr.ip4.addr);
379 #endif
380 esp_mesh_comm_mqtt_task_start();
381 }
382
383
app_main(void)384 void app_main(void)
385 {
386 ESP_ERROR_CHECK(nvs_flash_init());
387 /* tcpip initialization */
388 ESP_ERROR_CHECK(esp_netif_init());
389 /* event initialization */
390 ESP_ERROR_CHECK(esp_event_loop_create_default());
391 /* crete network interfaces for mesh (only station instance saved for further manipulation, soft AP instance ignored */
392 ESP_ERROR_CHECK(mesh_netifs_init(recv_cb));
393
394 /* wifi initialization */
395 wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
396 ESP_ERROR_CHECK(esp_wifi_init(&config));
397 ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &ip_event_handler, NULL));
398 ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH));
399 ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
400 ESP_ERROR_CHECK(esp_wifi_start());
401 /* mesh initialization */
402 ESP_ERROR_CHECK(esp_mesh_init());
403 ESP_ERROR_CHECK(esp_event_handler_register(MESH_EVENT, ESP_EVENT_ANY_ID, &mesh_event_handler, NULL));
404 ESP_ERROR_CHECK(esp_mesh_set_max_layer(CONFIG_MESH_MAX_LAYER));
405 ESP_ERROR_CHECK(esp_mesh_set_vote_percentage(1));
406 ESP_ERROR_CHECK(esp_mesh_set_ap_assoc_expire(10));
407 mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT();
408 /* mesh ID */
409 memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6);
410 /* router */
411 cfg.channel = CONFIG_MESH_CHANNEL;
412 cfg.router.ssid_len = strlen(CONFIG_MESH_ROUTER_SSID);
413 memcpy((uint8_t *) &cfg.router.ssid, CONFIG_MESH_ROUTER_SSID, cfg.router.ssid_len);
414 memcpy((uint8_t *) &cfg.router.password, CONFIG_MESH_ROUTER_PASSWD,
415 strlen(CONFIG_MESH_ROUTER_PASSWD));
416 /* mesh softAP */
417 ESP_ERROR_CHECK(esp_mesh_set_ap_authmode(CONFIG_MESH_AP_AUTHMODE));
418 cfg.mesh_ap.max_connection = CONFIG_MESH_AP_CONNECTIONS;
419 cfg.mesh_ap.nonmesh_max_connection = CONFIG_MESH_NON_MESH_AP_CONNECTIONS;
420 memcpy((uint8_t *) &cfg.mesh_ap.password, CONFIG_MESH_AP_PASSWD,
421 strlen(CONFIG_MESH_AP_PASSWD));
422 ESP_ERROR_CHECK(esp_mesh_set_config(&cfg));
423 /* mesh start */
424 ESP_ERROR_CHECK(esp_mesh_start());
425 ESP_LOGI(MESH_TAG, "mesh starts successfully, heap:%d, %s\n", esp_get_free_heap_size(),
426 esp_mesh_is_root_fixed() ? "root fixed" : "root not fixed");
427 }
428