diff --git a/components/esp32/component.mk b/components/esp32/component.mk index cdd174779..fb53bfbb4 100644 --- a/components/esp32/component.mk +++ b/components/esp32/component.mk @@ -5,7 +5,7 @@ COMPONENT_SRCDIRS := . hwcrypto LIBS ?= ifndef CONFIG_NO_BLOBS -LIBS += core rtc net80211 pp wpa smartconfig coexist wps wpa2 espnow phy +LIBS += core rtc net80211 pp wpa smartconfig coexist wps wpa2 espnow phy mesh endif #Linker scripts used to link the final application. @@ -59,4 +59,4 @@ COMPONENT_EXTRA_CLEAN := esp32_out.ld # disable stack protection in files which are involved in initialization of that feature stack_check.o: CFLAGS := $(filter-out -fstack-protector%, $(CFLAGS)) -cpu_start.o: CFLAGS := $(filter-out -fstack-protector%, $(CFLAGS)) \ No newline at end of file +cpu_start.o: CFLAGS := $(filter-out -fstack-protector%, $(CFLAGS)) diff --git a/components/esp32/esp_err_to_name.c b/components/esp32/esp_err_to_name.c index b0907d195..713252777 100644 --- a/components/esp32/esp_err_to_name.c +++ b/components/esp32/esp_err_to_name.c @@ -13,6 +13,9 @@ #if __has_include("esp_image_format.h") #include "esp_image_format.h" #endif +#if __has_include("esp_mesh.h") +#include "esp_mesh.h" +#endif #if __has_include("esp_now.h") #include "esp_now.h" #endif @@ -288,6 +291,74 @@ static const esp_err_msg_t esp_err_msg_table[] = { # endif # ifdef ESP_ERR_ESPNOW_IF ERR_TBL_IT(ESP_ERR_ESPNOW_IF), /* 12396 0x306c Interface error */ +# endif + // components/esp32/include/esp_err.h +# ifdef ESP_ERR_MESH_BASE + ERR_TBL_IT(ESP_ERR_MESH_BASE), /* 16384 0x4000 Starting number of MESH error codes */ +# endif + // components/esp32/include/esp_mesh.h +# ifdef ESP_ERR_MESH_WIFI_NOT_START + ERR_TBL_IT(ESP_ERR_MESH_WIFI_NOT_START), /* 16385 0x4001 */ +# endif +# ifdef ESP_ERR_MESH_NOT_INIT + ERR_TBL_IT(ESP_ERR_MESH_NOT_INIT), /* 16386 0x4002 */ +# endif +# ifdef ESP_ERR_MESH_NOT_CONFIG + ERR_TBL_IT(ESP_ERR_MESH_NOT_CONFIG), /* 16387 0x4003 */ +# endif +# ifdef ESP_ERR_MESH_NOT_START + ERR_TBL_IT(ESP_ERR_MESH_NOT_START), /* 16388 0x4004 */ +# endif +# ifdef ESP_ERR_MESH_NOT_SUPPORT + ERR_TBL_IT(ESP_ERR_MESH_NOT_SUPPORT), /* 16389 0x4005 */ +# endif +# ifdef ESP_ERR_MESH_NOT_ALLOWED + ERR_TBL_IT(ESP_ERR_MESH_NOT_ALLOWED), /* 16390 0x4006 */ +# endif +# ifdef ESP_ERR_MESH_NO_MEMORY + ERR_TBL_IT(ESP_ERR_MESH_NO_MEMORY), /* 16391 0x4007 */ +# endif +# ifdef ESP_ERR_MESH_ARGUMENT + ERR_TBL_IT(ESP_ERR_MESH_ARGUMENT), /* 16392 0x4008 */ +# endif +# ifdef ESP_ERR_MESH_EXCEED_MTU + ERR_TBL_IT(ESP_ERR_MESH_EXCEED_MTU), /* 16393 0x4009 */ +# endif +# ifdef ESP_ERR_MESH_TIMEOUT + ERR_TBL_IT(ESP_ERR_MESH_TIMEOUT), /* 16394 0x400a */ +# endif +# ifdef ESP_ERR_MESH_DISCONNECTED + ERR_TBL_IT(ESP_ERR_MESH_DISCONNECTED), /* 16395 0x400b */ +# endif +# ifdef ESP_ERR_MESH_QUEUE_FAIL + ERR_TBL_IT(ESP_ERR_MESH_QUEUE_FAIL), /* 16396 0x400c */ +# endif +# ifdef ESP_ERR_MESH_QUEUE_FULL + ERR_TBL_IT(ESP_ERR_MESH_QUEUE_FULL), /* 16397 0x400d */ +# endif +# ifdef ESP_ERR_MESH_NO_PARENT_FOUND + ERR_TBL_IT(ESP_ERR_MESH_NO_PARENT_FOUND), /* 16398 0x400e */ +# endif +# ifdef ESP_ERR_MESH_NO_ROUTE_FOUND + ERR_TBL_IT(ESP_ERR_MESH_NO_ROUTE_FOUND), /* 16399 0x400f */ +# endif +# ifdef ESP_ERR_MESH_OPTION_NULL + ERR_TBL_IT(ESP_ERR_MESH_OPTION_NULL), /* 16400 0x4010 */ +# endif +# ifdef ESP_ERR_MESH_OPTION_UNKNOWN + ERR_TBL_IT(ESP_ERR_MESH_OPTION_UNKNOWN), /* 16401 0x4011 */ +# endif +# ifdef ESP_ERR_MESH_XON_NO_WINDOW + ERR_TBL_IT(ESP_ERR_MESH_XON_NO_WINDOW), /* 16402 0x4012 */ +# endif +# ifdef ESP_ERR_MESH_INTERFACE + ERR_TBL_IT(ESP_ERR_MESH_INTERFACE), /* 16403 0x4013 */ +# endif +# ifdef ESP_ERR_MESH_DISCARD_DUPLICATE + ERR_TBL_IT(ESP_ERR_MESH_DISCARD_DUPLICATE), /* 16404 0x4014 */ +# endif +# ifdef ESP_ERR_MESH_DISCARD + ERR_TBL_IT(ESP_ERR_MESH_DISCARD), /* 16405 0x4015 */ # endif // components/tcpip_adapter/include/tcpip_adapter.h # ifdef ESP_ERR_TCPIP_ADAPTER_BASE diff --git a/components/esp32/event_loop.c b/components/esp32/event_loop.c index a8d41e378..d8e6a5bd2 100644 --- a/components/esp32/event_loop.c +++ b/components/esp32/event_loop.c @@ -21,6 +21,7 @@ #include "esp_event.h" #include "esp_event_loop.h" #include "esp_task.h" +#include "esp_mesh.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" @@ -76,6 +77,20 @@ esp_err_t esp_event_send(system_event_t *event) ESP_LOGE(TAG, "Event loop not initialized via esp_event_loop_init, but esp_event_send called"); return ESP_ERR_INVALID_STATE; } + + if (event->event_id == SYSTEM_EVENT_STA_GOT_IP || event->event_id == SYSTEM_EVENT_STA_LOST_IP) { + if (g_mesh_event_cb) { + mesh_event_t mevent; + if (event->event_id == SYSTEM_EVENT_STA_GOT_IP) { + mevent.id = MESH_EVENT_ROOT_GOT_IP; + memcpy(&mevent.info.got_ip, &event->event_info.got_ip, sizeof(system_event_sta_got_ip_t)); + } else { + mevent.id = MESH_EVENT_ROOT_LOST_IP; + } + g_mesh_event_cb(mevent); + } + } + portBASE_TYPE ret = xQueueSendToBack(s_event_queue, event, 0); if (ret != pdPASS) { if (event) { diff --git a/components/esp32/fast_crypto_ops.c b/components/esp32/fast_crypto_ops.c index 66c8e19af..2f28a2480 100644 --- a/components/esp32/fast_crypto_ops.c +++ b/components/esp32/fast_crypto_ops.c @@ -59,3 +59,7 @@ const wpa2_crypto_funcs_t g_wifi_default_wpa2_crypto_funcs = { .sha256_vector = (esp_sha256_vector_t)fast_sha256_vector }; +const mesh_crypto_funcs_t g_wifi_default_mesh_crypto_funcs = { + .aes_128_encrypt = (esp_aes_128_encrypt_t)fast_aes_128_cbc_encrypt, + .aes_128_decrypt = (esp_aes_128_decrypt_t)fast_aes_128_cbc_decrypt, +}; diff --git a/components/esp32/include/esp_err.h b/components/esp32/include/esp_err.h index 8bed65cd3..b38a723bc 100644 --- a/components/esp32/include/esp_err.h +++ b/components/esp32/include/esp_err.h @@ -41,6 +41,7 @@ typedef int32_t esp_err_t; #define ESP_ERR_INVALID_MAC 0x10B #define ESP_ERR_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ +#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ /** * @brief Returns string for esp_err_t error codes diff --git a/components/esp32/include/esp_mesh.h b/components/esp32/include/esp_mesh.h new file mode 100644 index 000000000..12e2d55d8 --- /dev/null +++ b/components/esp32/include/esp_mesh.h @@ -0,0 +1,1201 @@ +// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* + * Software Stack demonstrated: + * |------------------------------------------------------------------------------| + * | | | + * | | Application | + * | |-----------------------------------------------------------------| + * | | | Protocols: | | | | | + * | | Mesh Stack | HTTP, DNS, | | | Other | | + * | RTOS: | (Networking, | DHCP, ... | | | Components | | + * | (freeRTOS) | self-healing, |------------| | | | | + * | | flow control, | Network Stack: | | | | + * | | ...) | (LwIP) | | | | + * | |-----------------------------------| |---------------| | + * | | | | + * | | WiFi Driver | | + * | |--------------------------------------------------| | + * | | | + * | | Platform HAL | + * |------------------------------------------------------------------------------| + * + * System Events delivery: + * + * |---------------| + * | | default handler + * | WiFi stack | events |---------------------| + * | | -------------> | | + * |---------------| | | + * | event task | + * |---------------| events | | + * | | -------------> | | + * | LwIP stack | |---------------------| + * | |--------| + * |---------------| | + * | mesh event callback handler + * | |----------------------------| + * |-----> | | + * |---------------| | application | + * | | events | task | + * | mesh stack | -------------> | | + * | | |----------------------------| + * |---------------| + * + * + * Mesh Stack + * + * Mesh event defines almost all system events applications tasks need. + * Mesh event contains WiFi connection states on station interface, children connection states on softAP interface and etc.. + * Applications need to register a mesh event callback handler by API esp_mesh_set_config() firstly. + * This handler is to receive events posted from mesh stack and LwIP stack. + * Applications could add relative handler for each event. + * Examples: + * (1)Applications could use WiFi station connect states to decide when to send data to its parent, to root or to external IP network; + * (2)Applications could use WiFi softAP states to decide when to send data to its children. + * + * In present implementation, applications are able to access mesh stack directly without having to go through LwIP stack. + * Applications use esp_mesh_send() and esp_mesh_recv() to send and receive messages over the mesh network. + * In mesh stack design, normal nodes don't require LwIP stack. But since IDF hasn't supported system without initializing LwIP stack yet, + * applications still need to do LwIP initialization and two more things are required to be done + * (1)stop DHCP server on softAP interface by default + * (2)stop DHCP client on station interface by default. + * Examples: + * tcpip_adapter_init(); + * tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); + * tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); + * + * Over the mesh network, only root is able to access external IP network. + * In application mesh event handler, once a node becomes a root, start DHCP client immediately if DHCP is chosen. + */ + +#ifndef __ESP_MESH_H__ +#define __ESP_MESH_H__ + +#include "esp_err.h" +#include "esp_wifi.h" +#include "esp_wifi_types.h" +#include "esp_mesh_internal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************* + * Constants + *******************************************************/ +#define MESH_ROOT_LAYER (1) /**< root layer value */ +#define MESH_MTU (1500) /**< max transmit unit(in bytes) */ +#define MESH_MPS (1472) /**< max payload size(in bytes) */ +/** + * @brief mesh error code definition + */ +#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< WiFi isn't started */ +#define ESP_ERR_MESH_NOT_INIT (ESP_ERR_MESH_BASE + 2) /**< mesh isn't initialized */ +#define ESP_ERR_MESH_NOT_CONFIG (ESP_ERR_MESH_BASE + 3) /**< mesh isn't configured */ +#define ESP_ERR_MESH_NOT_START (ESP_ERR_MESH_BASE + 4) /**< mesh isn't started */ +#define ESP_ERR_MESH_NOT_SUPPORT (ESP_ERR_MESH_BASE + 5) /**< not supported yet */ +#define ESP_ERR_MESH_NOT_ALLOWED (ESP_ERR_MESH_BASE + 6) /**< operation is not allowed */ +#define ESP_ERR_MESH_NO_MEMORY (ESP_ERR_MESH_BASE + 7) /**< out of memory */ +#define ESP_ERR_MESH_ARGUMENT (ESP_ERR_MESH_BASE + 8) /**< illegal argument */ +#define ESP_ERR_MESH_EXCEED_MTU (ESP_ERR_MESH_BASE + 9) /**< packet size exceeds MTU */ +#define ESP_ERR_MESH_TIMEOUT (ESP_ERR_MESH_BASE + 10) /**< timeout */ +#define ESP_ERR_MESH_DISCONNECTED (ESP_ERR_MESH_BASE + 11) /**< disconnected with parent on station interface */ +#define ESP_ERR_MESH_QUEUE_FAIL (ESP_ERR_MESH_BASE + 12) /**< queue fail */ +#define ESP_ERR_MESH_QUEUE_FULL (ESP_ERR_MESH_BASE + 13) /**< queue full */ +#define ESP_ERR_MESH_NO_PARENT_FOUND (ESP_ERR_MESH_BASE + 14) /**< no parent found to join the mesh network */ +#define ESP_ERR_MESH_NO_ROUTE_FOUND (ESP_ERR_MESH_BASE + 15) /**< no route found to forward the packet */ +#define ESP_ERR_MESH_OPTION_NULL (ESP_ERR_MESH_BASE + 16) /**< no option found */ +#define ESP_ERR_MESH_OPTION_UNKNOWN (ESP_ERR_MESH_BASE + 17) /**< unknown option */ +#define ESP_ERR_MESH_XON_NO_WINDOW (ESP_ERR_MESH_BASE + 18) /**< no window for software flow control on upstream */ +#define ESP_ERR_MESH_INTERFACE (ESP_ERR_MESH_BASE + 19) /**< low-level WiFi interface error */ +#define ESP_ERR_MESH_DISCARD_DUPLICATE (ESP_ERR_MESH_BASE + 20) /**< discard the packet due to the duplicate sequence number */ +#define ESP_ERR_MESH_DISCARD (ESP_ERR_MESH_BASE + 21) /**< discard the packet */ + +/** + * @brief flags used with esp_mesh_send() and esp_mesh_recv() + */ +#define MESH_DATA_ENC (0x01) /**< data encrypted(Unimplemented) */ +#define MESH_DATA_P2P (0x02) /**< point-to-point delivery over the mesh network */ +#define MESH_DATA_FROMDS (0x04) /**< receive from external IP network */ +#define MESH_DATA_TODS (0x08) /**< identify this packet is target to external IP network */ +#define MESH_DATA_NONBLOCK (0x10) /**< esp_mesh_send() non-block */ +#define MESH_DATA_DROP (0x20) /**< in the situation of root having been changed, identify this packet can be dropped by new root */ +#define MESH_DATA_GROUP (0x40) /**< identify this packet is target to a group address */ + +/** + * @brief option definitions for esp_mesh_send() and esp_mesh_recv() + */ +#define MESH_OPT_SEND_GROUP (7) /**< data transmission by group; used with esp_mesh_send() and must have payload */ +#define MESH_OPT_RECV_DS_ADDR (8) /**< return a remote IP address; used with esp_mesh_send() and esp_mesh_recv() */ + +/******************************************************* + * Enumerations + *******************************************************/ +/** + * @brief enumerated list of mesh event id + */ +typedef enum { + MESH_EVENT_STARTED, /**< mesh is started */ + MESH_EVENT_STOPPED, /**< mesh is stopped */ + MESH_EVENT_CHANNEL_SWITCH, /**< channel switch */ + MESH_EVENT_CHILD_CONNECTED, /**< a child is connected on softAP interface */ + MESH_EVENT_CHILD_DISCONNECTED, /**< a child is disconnected on softAP interface */ + MESH_EVENT_ROUTING_TABLE_ADD, /**< routing table is changed by adding newly joined children */ + MESH_EVENT_ROUTING_TABLE_REMOVE, /**< routing table is changed by removing leave children */ + MESH_EVENT_PARENT_CONNECTED, /**< parent is connected on station interface */ + MESH_EVENT_PARENT_DISCONNECTED, /**< parent is disconnected on station interface */ + MESH_EVENT_NO_PARNET_FOUND, /**< no parent found */ + MESH_EVENT_LAYER_CHANGE, /**< layer changes over the mesh network */ + MESH_EVENT_TODS_STATE, /**< state represents if root is able to access external IP network */ + MESH_EVENT_VOTE_STARTED, /**< the process of voting a new root is started either by children or by root */ + MESH_EVENT_VOTE_STOPPED, /**< the process of voting a new root is stopped */ + MESH_EVENT_ROOT_ADDRESS, /**< the root address is obtained. It is posted by mesh stack automatically. */ + MESH_EVENT_ROOT_SWITCH_REQ, /**< root switch request sent from a new voted root candidate */ + MESH_EVENT_ROOT_SWITCH_ACK, /**< root switch acknowledgment responds the above request sent from current root */ + MESH_EVENT_ROOT_GOT_IP, /**< root obtains the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_LOST_IP, /**< root loses the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_ASKED_YIELD, /**< root is asked yield by a more powerful existing root. If self organized is disabled + and this device is specified to be a root by users, users should set a new parent + for this device. if self organized is enabled, this device will find a new parent + by itself, users could ignore this event. */ + MESH_EVENT_MAX, +} mesh_event_id_t; + +/** + * @brief node type + */ +typedef enum { + MESH_IDLE, /**< hasn't joined the mesh network yet */ + MESH_ROOT, /**< the only sink of the mesh network. Has the ability to access external IP network */ + MESH_NODE, /**< intermediate node. Has the ability to forward packets over the mesh network */ + MESH_LEAF, /**< has no forwarding ability */ +} mesh_type_t; + +/** + * @brief protocol of transmitted application data + */ +typedef enum { + MESH_PROTO_BIN, /**< binary */ + MESH_PROTO_HTTP, /**< HTTP protocol */ + MESH_PROTO_JSON, /**< JSON format */ + MESH_PROTO_MQTT, /**< MQTT protocol */ +} mesh_proto_t; + +/** + * @brief for reliable transmission, mesh stack provides three type of services + */ +typedef enum { + MESH_TOS_P2P, /**< provide P2P(point-to-point) retransmission on mesh stack by default */ + MESH_TOS_E2E, /**< provide E2E(end-to-end) retransmission on mesh stack (Unimplemented) */ + MESH_TOS_DEF, /**< no retransmission on mesh stack */ +} mesh_tos_t; + +/** + * @brief vote reason + */ +typedef enum { + MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by root */ + MESH_VOTE_REASON_CHILD_INITIATED, /**< vote is initiated by children */ +} mesh_vote_reason_t; + +/** + * @brief mesh disconnect reason code + */ +typedef enum { + MESH_REASON_CYCLIC = 100, /**< cyclic is detected */ + MESH_REASON_PARENT_IDLE, /**< parent is idle */ + MESH_REASON_LEAF, /**< the connected node is changed to a leaf */ + MESH_REASON_DIFF_ID, /**< in different mesh ID */ + MESH_REASON_ROOTS, /**< root conflict is detected */ + MESH_REASON_PARENT_STOPPED, /**< parent has stopped the mesh */ + MESH_REASON_SCAN_FAIL, /**< scan fail */ +} mesh_disconnect_reason_t; + +/******************************************************* + * Structures + *******************************************************/ +/** + * @brief IP address and port + */ +typedef struct { + ip4_addr_t ip4; /**< IP address */ + uint16_t port; /**< port */ +} __attribute__((packed)) mip_t; + +/** + * @brief mesh address + */ +typedef union { + uint8_t addr[6]; /**< mac address */ + mip_t mip; /**< mip address */ +} mesh_addr_t; + +/** + * @brief channel switch information + */ +typedef struct { + uint8_t channel; /**< new channel */ +} mesh_event_channel_switch_t; + +/** + * @brief parent connected information + */ +typedef struct { + system_event_sta_connected_t connected; /**< parent information, same as WiFi event SYSTEM_EVENT_STA_CONNECTED does */ + uint8_t self_layer; /**< layer */ +} mesh_event_connected_t; + +/** + * @brief no parent found information + */ +typedef struct { + int scan_times; /**< scan times being through */ +} mesh_event_no_parent_found_t; + +/** + * @brief layer change information + */ +typedef struct { + uint8_t new_layer; /**< new layer */ +} mesh_event_layer_change_t; + +/** + * @brief the reachability of root to a DS(distribute system) + */ +typedef enum { + MESH_TODS_UNREACHABLE, /**< root isn't able to access external IP network */ + MESH_TODS_REACHABLE, /**< root is able to access external IP network */ +} mesh_event_toDS_state_t; + +/** + * @brief vote started information + */ +typedef struct { + int reason; /**< vote reason, vote could be initiated by children or by root itself */ + int attempts; /**< max vote attempts before stopped */ + mesh_addr_t rc_addr; /**< root address specified by users via API esp_mesh_waive_root() */ +} mesh_event_vote_started_t; + +/** + * @brief IP settings from LwIP stack + */ +typedef system_event_sta_got_ip_t mesh_event_root_got_ip_t; + +/** + * @brief root address + */ +typedef mesh_addr_t mesh_event_root_address_t; + +/** + * @brief parent disconnected information + */ +typedef system_event_sta_disconnected_t mesh_event_disconnected_t; + +/** + * @brief child connected information + */ +typedef system_event_ap_staconnected_t mesh_event_child_connected_t; + +/** + * @brief child disconnected information + */ +typedef system_event_ap_stadisconnected_t mesh_event_child_disconnected_t; + +/** + * @brief root switch request information + */ +typedef struct { + int reason; /**< root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() */ + mesh_addr_t rc_addr; /**< the address of root switch requester */ +} mesh_event_root_switch_req_t; + +/** + * @brief other powerful root address + */ +typedef struct { + int8_t rssi; /**< rssi with router */ + uint16_t capacity; /**< the number of nodes in its network */ + uint8_t addr[6]; /**< other powerful root address */ +} mesh_event_root_conflict_t; + +/** + * @brief routing table change + */ +typedef struct { + uint16_t rt_size_new; /**< the new value */ + uint16_t rt_size_change; /**< the changed value */ +} mesh_event_routing_table_change_t; + +/** + * @brief mesh event information + */ +typedef union { + mesh_event_channel_switch_t channel_switch; /**< channel switch */ + mesh_event_child_connected_t child_connected; /**< child connected */ + mesh_event_child_disconnected_t child_disconnected; /**< child disconnected */ + mesh_event_routing_table_change_t routing_table; /**< routing table change */ + mesh_event_connected_t connected; /**< parent connected */ + mesh_event_disconnected_t disconnected; /**< parent disconnected */ + mesh_event_no_parent_found_t no_parent; /**< no parent found */ + mesh_event_layer_change_t layer_change; /**< layer change */ + mesh_event_toDS_state_t toDS_state; /**< toDS state, nodes should check this state firstly before trying to send packets to + external IP network. This state indicates right now if root is capable + of sending packets out. If not, nodes had better to wait until this state changes + to be MESH_TODS_REACHABLE. */ + mesh_event_vote_started_t vote_started; /**< vote started */ + mesh_event_root_got_ip_t got_ip; /**< root obtains IP address */ + mesh_event_root_address_t root_addr; /**< root address */ + mesh_event_root_switch_req_t switch_req; /**< root switch request */ + mesh_event_root_conflict_t root_conflict; /**< other powerful root */ +} mesh_event_info_t; + +/** + * @brief mesh event + */ +typedef struct { + mesh_event_id_t id; /**< mesh event id */ + mesh_event_info_t info; /**< mesh event info */ +} mesh_event_t; + +/** + * @brief mesh event callback handler prototype definition + * + * @param event mesh_event_t + */ +typedef void (*mesh_event_cb_t)(mesh_event_t event); + +/** + * @brief mesh option + */ +typedef struct { + uint8_t type; /**< option type */ + uint16_t len; /**< option length */ + uint8_t *val; /**< option value */ +} __attribute__((packed)) mesh_opt_t; + +/** + * @brief mesh data for esp_mesh_send() and esp_mesh_recv() + */ +typedef struct { + uint8_t *data; /**< data */ + uint16_t size; /**< data size */ + mesh_proto_t proto; /**< data protocol */ + mesh_tos_t tos; /**< data type of service */ +} mesh_data_t; + +/** + * @brief router configuration + */ +typedef struct { + uint8_t ssid[32]; /**< SSID */ + uint8_t ssid_len; /**< length of SSID */ + uint8_t bssid[6]; /**< BSSID, if router is hidden, this value is mandatory */ + uint8_t password[64]; /**< password */ +} mesh_router_t; + +/** + * @brief mesh softAP configuration + */ +typedef struct { + uint8_t password[64]; /**< mesh softAP password */ + uint8_t max_connection; /**< max number of stations allowed to connect in, max 10 */ +} mesh_ap_cfg_t; + +/** + * @brief mesh initialization configuration + */ +typedef struct { + uint8_t channel; /**< channel, the mesh network on */ + mesh_event_cb_t event_cb; /**< mesh event callback */ + mesh_addr_t mesh_id; /**< mesh network identification */ + mesh_router_t router; /**< router configuration */ + mesh_ap_cfg_t mesh_ap; /**< mesh softAP configuration */ + const mesh_crypto_funcs_t *crypto_funcs; /**< crypto functions */ +} mesh_cfg_t; + +/** + * @brief vote + */ +typedef union { + int attempts; /**< max vote attempts */ + mesh_addr_t rc_addr; /**< root address specified by users for API esp_mesh_waive_root() */ +} mesh_vote_t; + +/** + * @brief the number of packets pending in the queue waiting to be sent by the mesh stack + */ +typedef struct { + int to_parent; /**< to parent queue */ + int to_parent_p2p; /**< to parent(P2P) queue */ + int to_child; /**< to child queue */ + int to_child_p2p; /**< to child(P2P) queue */ + int mgmt; /**< management queue */ + int broadcast; /**< broadcast and multicast queue */ +} mesh_tx_pending_t; + +/** + * @brief the number of packets available in the queue waiting to be received by applications + */ +typedef struct { + int toDS; /**< to external DS */ + int toSelf; /**< to self */ +} mesh_rx_pending_t; + +/******************************************************* + * Variable Declaration + *******************************************************/ +/* mesh vendor IE crypto callback function */ +extern const mesh_crypto_funcs_t g_wifi_default_mesh_crypto_funcs; + +/* mesh event callback handler */ +extern mesh_event_cb_t g_mesh_event_cb; + +#define MESH_INIT_CONFIG_DEFAULT() { \ + .crypto_funcs = &g_wifi_default_mesh_crypto_funcs, \ +} + +/******************************************************* + * Function Definitions + *******************************************************/ +/** + * @brief mesh initialization + * Check if WiFi is started. + * Initialize mesh global variables with default values. + * + * @attention This API should be called after WiFi is started. + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_init(void); + +/** + * @brief mesh de-initialization + * Release resources and stop the mesh + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_deinit(void); + +/** + * @brief start mesh + * Initialize mesh vendor IE + * Start mesh network management service + * Create TX and RX queues according to the configuration + * Register mesh packets receive callback + * + * @attention This API should be called after esp_mesh_init() and esp_mesh_set_config(). + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_MESH_NOT_INIT + * - ESP_ERR_MESH_NOT_CONFIG + * - ESP_ERR_MESH_NO_MEMORY + */ +esp_err_t esp_mesh_start(void); + +/** + * @brief stop mesh + * Deinitialize mesh vendor IE + * Disconnect with current parent + * Disassociate all currently associated children + * Stop mesh network management service + * Unregister mesh packets receive callback + * Delete TX and RX queues + * Release resources + * Restore WiFi softAP to default settings if WiFi dual mode is enabled + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_stop(void); + +/** + * @brief send a packet over the mesh network + * Send a packet to any node in the mesh network. + * Send a packet to external IP network. + * + * @attention This API is not reentrant. + * + * @param to the address of the final destination of the packet + * (1)if the packet is to root, just set "to" to NULL and set flag to zero. + * (2)if the packet is outgoing to external IP network such as an IP server address, translate IPv4:PORT known as "to". + * This packet will be delivered to root firstly, then root will forward this packet to the final IP server address. + * @param data pointer to a sending mesh packet + * Should specify the data protocol applications used, binary by default. + * Should specify the transmission tos(type of service), P2P reliable by default. + * @param flag + * (1)used to speed up the route selection + * if the packet is target to an internal node, MESH_DATA_P2P should be set. + * if the packet is outgoing to root or to external IP network, MESH_DATA_TODS should be set. + * if the packet is from root to an internal node, MESH_DATA_FROMDS should be set. + * (2)specify if this API is block or non-block, block by default + * if needs non-block, MESH_DATA_NONBLOCK should be set. + * (3)in the situation of root having been changed, MESH_DATA_DROP identifies this packet can be dropped by new root + * for upstream data to external IP network, we try our best to avoid data loss caused by root having been changed, but + * there is a risk that new root is running out of memory because most of memory is occupied by the pending data which + * isn't read out in time by esp_mesh_recv_toDS(). + * Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing + * to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. + * + * @param opt options + * (1)in case of sending a packet to a specified group, MESH_OPT_SEND_GROUP is a good choice. + * In this option, the value field should specify the target receiver addresses in this group. + * (2)root sends a packet to an internal node, this packet is from external IP network in case the receiver node responds + * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. + * @param opt_count option count + * Currently, this API only takes one option, so opt_count is only supported to be 1. + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_DISCONNECTED + * - ESP_ERR_MESH_OPT_UNKNOWN + * - ESP_ERR_MESH_EXCEED_MTU + * - ESP_ERR_MESH_NO_MEMORY + * - ESP_ERR_MESH_TIMEOUT + * - ESP_ERR_MESH_QUEUE_FULL + * - ESP_ERR_MESH_NO_ROUTE_FOUND + * - ESP_ERR_MESH_DISCARD + */ +esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, + const int flag, const mesh_opt_t opt[], const int opt_count); + +/** + * @brief receive a packet targeted to self over the mesh network + * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications in case of running out of memory. + * + * @param from the address of the original source of the packet + * @param data pointer to the received mesh packet + * Contain the protocol and applications should follow it to parse the data. + * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) + * @param flag + * MESH_DATA_FROMDS represents data from external IP network + * MESH_DATA_TODS represents data directed upward within the mesh network + * @param opt options desired to receive + * MESH_OPT_RECV_DS_ADDR attaches the DS address + * @param opt_count option count desired to receive + * Currently, this API only takes one option, so opt_count is only supported to be 1. + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_TIMEOUT + * - ESP_ERR_MESH_DISCARD + */ +esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, + int *flag, mesh_opt_t opt[], int opt_count); + +/** + * @brief receive a packet targeted to external IP network + * root uses this API to receive packets destined to external IP network + * root forwards the received packets to the final destination via socket. + * if no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() + * hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. + * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications in case of running out of memory in root. + * Use esp_mesh_set_xon_qsize() could configure the RX queue size, default:72. If this size is too large, + * and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied + * by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to + * decide this value depends on the specific application scenarios. + * + * @attention This API is only called by root. + * + * @param from the address of the original source of the packet + * @param to the address contains remote IP address and port(IPv4:PORT) + * @param data pointer to the received packet + * Contain the protocol and applications should follow it to parse the data. + * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) + * @param flag + * MESH_DATA_TODS represents data to external IP network + * @param opt options desired to receive + * @param opt_count option count desired to receive + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_TIMEOUT + * - ESP_ERR_MESH_DISCARD + */ +esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, + mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], + int opt_count); + +/** + * @brief set mesh stack configuration + * Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh vendor IE is encrypted by default. + * mesh network is established on a fixed channel(1-14). + * mesh event callback is mandatory. + * mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. + * Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. + * If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more + * roots than one connected with different BSSID will appear. It means more than one mesh network is established + * with the same mesh ID. + * Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots + * connected with different BSSID. Because users might have such requirements of setting up routers with same SSID + * for the future replacement. But in that case, if the above situations happen, please make sure applications + * implement forward functions on root to guarantee nodes in different mesh network could communicate with each other. + * max_connection of mesh softAP is limited by the max number of WiFi softAP supported(max:10). + * + * @attention This API should be called between esp_mesh_init() and esp_mesh_start(). + * + * @param config pointer to mesh stack configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); + +/** + * @brief get mesh stack configuration + * + * @param config pointer to mesh stack configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_config(mesh_cfg_t *config); + +/** + * @brief set router configuration + * + * @attention This API should be called between esp_mesh_init() and esp_mesh_start(). + * + * @param router pointer to router configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_router(const mesh_router_t *router); + +/** + * @brief get router configuration + * + * @param router pointer to router configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_router(mesh_router_t *router); + +/** + * @brief set mesh network ID + * + * @attention This API should be called between esp_mesh_init() and esp_mesh_start(). + * + * @param id pointer to mesh network ID + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT: invalid argument + */ +esp_err_t esp_mesh_set_id(const mesh_addr_t *id); + +/** + * @brief get mesh network ID + * + * @param id pointer to mesh network ID + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_id(mesh_addr_t *id); + +/** + * @brief set node type over the mesh network(Unimplemented) + * + * @param type node type + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_type(const mesh_type_t type); + +/** + * @brief get node type over mesh network + * + * @attention This API should be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @return mesh type + * + */ +mesh_type_t esp_mesh_get_type(void); + +/** + * @brief set max layer configuration(max:15, default:15) + * + * @attention This API should be called before esp_mesh_start(). + * + * @param max_layer max layer value + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_max_layer(const int max_layer); + +/** + * @brief get max layer configuration + * + * @return max layer value + */ +int esp_mesh_get_max_layer(void); + +/** + * @brief set mesh softAP password + * + * @attention This API should be called before esp_mesh_start(). + * + * @param pwd pointer to the password + * @param len password length + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, const int len); + +/** + * @brief set mesh softAP authentication mode value + * + * @attention This API should be called before esp_mesh_start(). + * + * @param authmode authentication mode + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_ap_authmode(const wifi_auth_mode_t authmode); + +/** + * @brief get mesh softAP authentication mode + * + * @return authentication mode + * + */ +wifi_auth_mode_t esp_mesh_get_ap_authmode(void); + +/** + * @brief set mesh softAP max connection value + * + * @attention This API should be called before esp_mesh_start(). + * + * @param connections the number of max connections + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_ap_connections(const int connections); + +/** + * @brief get mesh softAP max connection configuration + * + * @return the number of max connections + * + */ +int esp_mesh_get_ap_connections(void); + +/** + * @brief get current layer value over the mesh network + * + * @attention This API should be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @return layer value + * + */ +int esp_mesh_get_layer(void); + +/** + * @brief get parent BSSID + * + * @attention This API should be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @param bssid pointer to parent BSSID + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid); + +/** + * @brief return if the node is root + * + * @return true/false + * + */ +bool esp_mesh_is_root(void); + +/** + * @brief enable/disable mesh networking self-organized, self-organized by default + * if self-organized is disabled, users should set a parent for this node via + * esp_mesh_set_parent()(Unimplemented); + * + * @param enable + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_self_organized(const bool enable); + +/** + * @brief return if mesh networking is self-organized or not + * + * @return true/false + * + */ +bool esp_mesh_get_self_organized(void); + +/** + * @brief root waive itself + * A node is elected to be a root during the networking mostly because it has a strong RSSI with router. + * If such superior conditions change, users could call this API to perform a root switch. + * + * In this API, users could specify a desired root address to replace itself or specify an attempts value + * to ask current root to initiate a new round of voting. During the voting, a better root candidate would + * be expected to find to replace the current one. + * If no desired root candidate, the vote will try a specified attempts(at least 10 times), if no better + * root candidate is found, keep the current one. If a better candidate is found, the new better one will + * send a root switch request to the current root, current root will respond with a root switch acknowledgement. + * After that, the new candidate will connect to the router to be a new root, the previous root will disconnect + * with the router and choose another parent instead. + * So far, root switch is completed with minimal disruption to the whole mesh network. + * + * @attention This API is only called by root. + * + * @param vote vote configuration + * Specify a desired root address(Unimplemented) + * Attempts should be at least 10 times. + * if "vote" is set NULL, the vote will perform the default 10 times. + * @param reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, const int reason); + +/** + * @brief set vote percentage threshold for approval of being a root + * During the networking, only obtaining vote percentage reaches this threshold, + * the node could be a root. + * + * @attention This API should be called before esp_mesh_start(). + * + * @param percentage vote percentage threshold + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_vote_percentage(const float percentage); + +/** + * @brief get vote percentage threshold for approval of being a root + * + * @return percentage threshold + */ +float esp_mesh_get_vote_percentage(void); + +/** + * @brief set mesh softAP associate expired time + * If mesh softAP hasn't received any data from an associated child within this time, + * mesh softAP will take this child inactive and disassociate it. + * + * @param seconds + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_ap_assoc_expire(const int seconds); + +/** + * @brief get mesh softAP associate expired time + * + * @return seconds + */ +int esp_mesh_get_ap_assoc_expire(void); + +/** + * @brief get total number of nodes over the mesh network(including root) + * + * @attention The returned value might be incorrect when the network is changing. + ** + * @return total number of nodes(including root) + */ +int esp_mesh_get_total_node_num(void); + +/** + * @brief get the number of nodes in routing table(including self) + * + * @return the number of nodes in routing table(including self) + */ +int esp_mesh_get_routing_table_size(void); + +/** + * @brief get routing table(including itself) + * + * @param mac pointer to routing table + * @param len routing table size(in bytes) + * @param size pointer to the number of nodes in routing table(including itself) + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size); + +/** + * @brief post the toDS state to the mesh stack + * + * @attention This API is only for root. + * + * @param reachable this state represents if root is able to access external IP network + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_post_toDS_state(const bool reachable); + +/** + * @brief return the number of packets pending in the queue waiting to be sent by the mesh stack + * + * @param pending pointer to the TX pending + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); + +/** + * @brief return the number of packets available in the queue waiting to be received by applications + * + * @param pending pointer to the RX pending + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending); + +/** + * @brief return the number of packets could be accepted from the specified address + * + * @param addr self address or an associate children address + * @param xseqno_in sequence number of the last received packet from the specified address + * + * @return the number of upQ for a specified address + */ +int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); + +/** + * @brief set queue size + * + * @attention This API should be called before esp_mesh_start(). + * + * @param qsize default:72(min:36, max:105) + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_xon_qsize(int qsize); + +/** + * @brief get queue size + * + * @return qsize + */ +int esp_mesh_get_xon_qsize(void); + +/** + * @brief set if allow more than one root existing in one network + * + * @param allowed allow or not + * + * @return + * - ESP_OK + * - ESP_WIFI_ERR_NOT_INIT + * - ESP_WIFI_ERR_NOT_START + */ +esp_err_t esp_mesh_allow_root_conflicts(const bool allowed); + +/** + * @brief set group ID addresses + * + * @param addr pointer to new addresses + * @param num number of addresses + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, const int num); + +/** + * @brief delete group ID addresses + * + * @param addr pointer to deleted address + * @param num number of addresses + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, const int num); + +/** + * @brief get the number of group ID addresses + * + * @return the number of group ID addresses + */ +int esp_mesh_get_group_num(void); + +/** + * @brief get group ID addresses + * + * @param addr pointer to group address + * @param num number of addresses + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, const int num); + +/** + * @brief check if the specified group address is my group + * + * @return true/false + */ +bool esp_mesh_is_my_group(const mesh_addr_t *addr); + +/** + * @brief set mesh network capacity + * + * @attention This API should be called before esp_mesh_start(). + * + * @param num mesh network capacity + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_ALLOWED + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_capacity_num(int num); + +/** + * @brief get mesh network capacity + * + * @return mesh network capacity + */ +int esp_mesh_get_capacity_num(void); + +/** + * @brief set mesh ie crypto functions + * + * @param crypto_funcs crypto functions for mesh ie + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs); + +/** + * @brief set mesh ie crypto key + * + * @attention This API should be called before esp_mesh_start(). + * + * @param key crypto key + * @param len the present implementation only supports 32 + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_ALLOWED + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_ie_crypto_key(const uint8_t *key, int len); + +/** + * @brief get mesh ie crypto key + * + * @param key crypto key + * @param len the present implementation only supports 32 + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_get_ie_crypto_key(uint8_t *key, int len); + +/** + * @brief set delay time before starting root healing + * + * @param delay_ms delay time in milliseconds + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_root_healing_delay(int delay_ms); + +/** + * @brief get delay time before starting root healing + * + * @return delay time in milliseconds + */ +int esp_mesh_get_root_healing_delay(void); + +/** + * @brief set mesh event callback + * + * @param event_cb mesh event call back + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_event_cb(const mesh_event_cb_t event_cb); + + +#ifdef __cplusplus +} +#endif +#endif /* __ESP_MESH_H__ */ diff --git a/components/esp32/include/esp_mesh_internal.h b/components/esp32/include/esp_mesh_internal.h new file mode 100644 index 000000000..19273ba06 --- /dev/null +++ b/components/esp32/include/esp_mesh_internal.h @@ -0,0 +1,162 @@ +// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef __ESP_MESH_INTERNAL_H__ +#define __ESP_MESH_INTERNAL_H__ + +#include "esp_err.h" +#include "esp_wifi.h" +#include "esp_wifi_types.h" +#include "esp_wifi_internal.h" +#include "esp_wifi_crypto_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************* + * Constants + *******************************************************/ + +/******************************************************* + * Structures + *******************************************************/ +typedef struct { + int scan; /**< minimum scan times before being a root, default:10 */ + int vote; /**< max vote times in self-healing, default:10000 */ + int fail; /**< parent selection fail times, if the scan times reach this value, + will disconnect with associated children and join self-healing. default:60 */ + int monitor_ie; /**< acceptable times of parent ie change before update self ie, default:3 */ +} mesh_attempts_t; + +typedef struct { + int duration_ms; /* parent weak RSSI monitor duration, if the RSSI continues to be weak during this duration_ms, + will switch to a better parent */ + int cnx_rssi; /* RSSI threshold for keeping a good connection with parent */ + int select_rssi; /* RSSI threshold for parent selection, should be a value greater than switch_rssi */ + int switch_rssi; /* RSSI threshold for action to reselect a better parent */ + int backoff_rssi; /* RSSI threshold for connecting to the root */ +} mesh_switch_parent_t; + +/******************************************************* + * Function Definitions + *******************************************************/ +/** + * @brief set mesh softAP beacon interval + * + * @param interval beacon interval(ms) (100ms ~ 60000ms) + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_WIFI_ARG + */ +esp_err_t esp_mesh_set_beacon_interval(int interval_ms); + +/** + * @brief get mesh softAP beacon interval + * + * @param interval beacon interval(ms) + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); + +/** + * @brief set attempts for mesh self-organized networking + * + * @param attempts + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_attempts(mesh_attempts_t *attempts); + +/** + * @brief get attempts for mesh self-organized networking + * + * @param attempts + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_attempts(mesh_attempts_t *attempts); + +/** + * @brief set parameters for parent switch + * + * @param paras parameters for parent switch + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_switch_parent_paras(mesh_switch_parent_t *paras); + +/** + * @brief get parameters for parent switch + * + * @param paras parameters for parent switch + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); + +/** + * @brief print the number of txQ waiting + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_print_txQ_waiting(void); + +/** + * @brief print the number of rxQ waiting + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_print_rxQ_waiting(void); + +/** + * @brief set passive scan time + * + * @param interval_ms passive scan time(ms) + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_passive_scan_time(int time_ms); + +/** + * @brief get passive scan time + * + * @return interval_ms passive scan time(ms) + */ +int esp_mesh_get_passive_scan_time(void); + + +#ifdef __cplusplus +} +#endif +#endif /* __ESP_MESH_INTERNAL_H__ */ diff --git a/components/esp32/include/esp_wifi_crypto_types.h b/components/esp32/include/esp_wifi_crypto_types.h index 63f7b1db9..c97682daf 100644 --- a/components/esp32/include/esp_wifi_crypto_types.h +++ b/components/esp32/include/esp_wifi_crypto_types.h @@ -300,6 +300,16 @@ typedef struct { esp_sha256_vector_t sha256_vector; /**< function used to do X.509v3 certificate parsing and processing */ } wpa2_crypto_funcs_t; +/** + * @brief The crypto callback function structure used in mesh vendor IE encryption. The + * structure can be set as software crypto or the crypto optimized by ESP32 + * hardware. + */ +typedef struct{ + esp_aes_128_encrypt_t aes_128_encrypt; /**< function used in mesh vendor IE encryption */ + esp_aes_128_decrypt_t aes_128_decrypt; /**< function used in mesh vendor IE decryption */ +} mesh_crypto_funcs_t; + #ifdef __cplusplus } #endif diff --git a/components/esp32/lib b/components/esp32/lib index 152e29aa9..6657b2f40 160000 --- a/components/esp32/lib +++ b/components/esp32/lib @@ -1 +1 @@ -Subproject commit 152e29aa93a3d3f95fd6ed53a924a92c98fcc13c +Subproject commit 6657b2f40e498667fde7d31cdbc17b8ef581f93c diff --git a/components/esp32/wifi_init.c b/components/esp32/wifi_init.c index 84bb4fc55..be0ba781c 100644 --- a/components/esp32/wifi_init.c +++ b/components/esp32/wifi_init.c @@ -18,6 +18,10 @@ #include "esp_wifi_internal.h" #include "esp_pm.h" #include "soc/rtc.h" +#include "esp_mesh.h" + +/* mesh event callback handler */ +mesh_event_cb_t g_mesh_event_cb = NULL; #ifdef CONFIG_PM_ENABLE static esp_pm_lock_handle_t s_wifi_modem_sleep_lock; diff --git a/docs/Doxyfile b/docs/Doxyfile index 3cfb49d37..9e9f37780 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -28,6 +28,8 @@ INPUT = \ ../../components/esp32/include/esp_wifi_types.h \ ../../components/esp32/include/esp_smartconfig.h \ ../../components/esp32/include/esp_now.h \ + ## Mesh - API Reference + ../../components/esp32/include/esp_mesh.h \ ## Bluetooth - API Reference ## Controller && VHCI ../../components/bt/include/bt.h \ diff --git a/docs/_static/mesh_events_delivery.png b/docs/_static/mesh_events_delivery.png new file mode 100644 index 000000000..40341bb1d Binary files /dev/null and b/docs/_static/mesh_events_delivery.png differ diff --git a/docs/_static/mesh_network_architecture.png b/docs/_static/mesh_network_architecture.png new file mode 100644 index 000000000..4c54db128 Binary files /dev/null and b/docs/_static/mesh_network_architecture.png differ diff --git a/docs/_static/mesh_network_topology.png b/docs/_static/mesh_network_topology.png new file mode 100644 index 000000000..5bdf7a145 Binary files /dev/null and b/docs/_static/mesh_network_topology.png differ diff --git a/docs/_static/mesh_software_stack.png b/docs/_static/mesh_software_stack.png new file mode 100644 index 000000000..37bbf1931 Binary files /dev/null and b/docs/_static/mesh_software_stack.png differ diff --git a/docs/en/api-guides/index.rst b/docs/en/api-guides/index.rst index fcacd187d..e219ab116 100644 --- a/docs/en/api-guides/index.rst +++ b/docs/en/api-guides/index.rst @@ -21,4 +21,5 @@ API Guides Console Component ROM debug console WiFi Driver + Mesh Stack External SPI-connected RAM diff --git a/docs/en/api-guides/mesh.rst b/docs/en/api-guides/mesh.rst new file mode 100644 index 000000000..4c252e792 --- /dev/null +++ b/docs/en/api-guides/mesh.rst @@ -0,0 +1,281 @@ +ESP-MESH +======== + +Overview +-------- +ESP-MESH is a "multi-hop" network, meaning that two or more wireless hops (intermediate connections of two Internet devices) are needed for conveying information from a source to a destination. Mesh networking (or mesh routing) is a type of network topology in which a device (node) transmits its own data, while serving as a relay for other nodes at the same time. The prerequisite for successful wireless mesh routing is that all mesh nodes need to be interconnected on the physical layer first. The mesh routing algorithm, then, chooses the transmission path among these physical-layer links. As a highly reliable, widely-covered Wireless Local-Area Network (WLAN) network, the ESP-MESH is ideal for wireless solutions covering a large open area (both outdoors and indoors). + +ESP-MESH network is different from traditional wireless networks. The traditional wireless access technology implements a point-to-point or multipoint topology. There is generally one central node in such a topology, for example, a base station in a mobile communication system or an access point (AP) in an 802.11 WLAN. The central node and each wireless terminal are connected through single-hop wireless routing which controls each wireless terminal's access to the wireless network. Besides, the central node is connected to the backbone network through a wired link. In comparison, the ESP-MESH adopts a tree topology, with a root node, intermediate nodes and leaf nodes, making the network more expandable and fault-tolerant. Any mesh device on the network can compete to be the root node. Should the root node break down, the network will automatically select a new root node. This effectively decreases the tree topology’s dependence on a single node and allows every node to participate in the relay of information. + +.. figure:: ../../_static/mesh_network_architecture.png + :align: center + :alt: Mesh Network Architecture + + ESP-MESH Network Architecture + +Introduction +------------ +ESP-MESH defines a network that organizes and heals itself, enabling faster networking and better control. + +There are three types of nodes in a mesh network, in terms of their function within the mesh network: root node, intermediate node and leaf node. + +- Root node: this is the top node in the mesh network, which serves as the only interface between the mesh network and an external IP network. It functions as a gateway that relays packets outside the mesh network. + +- Intermediate node: a mesh node other than the root node and leaf nodes in a mesh network. An intermediate node can receive, send and forward the packets coming from its parent (immediately preceding) node, as well as its child (immediately following) nodes. + +- Leaf node: this is a mesh node that can only receive or send packets, but cannot forward packets. + +Each node that forwards data forms a parent/child node relationship with other nodes according to their position in the mesh network. The root node, through which the mesh network can communicate with an external IP network, is a node directly connected to the router and can transmit data between its child nodes and the router. The number of access devices and the bandwidth of the router directly affect the throughput of the root-node device, when accessing the external IP network. + +.. figure:: ../../_static/mesh_network_topology.png + :align: center + :alt: Mesh Network Topology + + ESP-MESH Network Topology and Data Stream + +As the above figure shows, node C and node D are intermediate nodes, while also being child nodes to the root node. Leaf E is the child node of node D. Leaf nodes A, B, and E have no child nodes. ESP-MESH is based on data link layer packet-forwarding, and no TCP/IP layer is needed in the mesh system except for the root node. See the figure “ESP-MESH Software Stack” for reference. + +Function Description +-------------------- + +1. Mesh Networking +^^^^^^^^^^^^^^^^^^^^^ +**(1) Mesh Configuration** + +A router is mandatory during the ESP-MESH networking. Users need to configure the Service Set Identification (SSID), password and channel of the router for each node. If the router is hidden, users will need to configure the Basic Service Set Identification (BSSID) for the nodes.(For mesh configuration solutions, please refer to the link to Mesh IoT solutions. The link will be released soon.) + +The information needed for mesh networking is carried by the Vendor Information Element (VIE) in beacon frame, which includes the node type, the layer of the node in the network, the maximum number of layers allowed in the network, the number of child nodes, the maximum number of nodes allowed to be connected to a single node, and more. + +**(2) Root Node Election** + +If there is no root node in the network, all the mesh devices will broadcast the real-time signal strength (RSSI) with the router. Each device networking information, including the signal strength with the router, is transmitted to the entire mesh network, so that all mesh devices can use that infromation to choose the one with the strongest signal as the root node. + +POR, all devices are scanned separately. Each device selects the device with the greatest real-time signal strength, compared to the signal received by other devices from the router as well as to the strength of the router itself. The selection is, then, broadcast as a root-node candidate. + +Subsequently, each mesh device scans the mesh network for a second time, and selects the device with the greatest real-time signal strength as root-node candidate. The selection is broadcast again. This process is repeated until only one root-node candidate remains in the end. + +ESP-MESH also employs methods to accelerate the convergence of the root node election. + +**(3) Parent Node Selection** + +ESP-MESH provides a method for selecting the strongest parent node in a mesh network. According to this method, a node obtains information about other nodes from received VIE messages, and generates a set of parent nodes. If the parent set comprises at least two nodes, the one with the highest performance parameter is selected as the preferred parent. According to this method, a preferred parent node is selected because of the node type and the performance parameter of each node in the parent set. This method ensures that the preferred parent is the optimal one, thus reducing packet loss rate which, in turn, improves network performance. + +2. Routing Generation and Maintenance +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + +3. Network Management +^^^^^^^^^^^^^^^^^^^^^ + ++-----------------------+------------------------------------------------------------------------------------------+ +| Function | Description | ++=======================+==========================================================================================+ +|Self-healing |Self-healing allows such routing-based network to operate when a node breaks down or when | +| |a connection becomes unreliable. | +| | | +| |If a root node breaks down, the nodes directly connected with it on the second layer will | +| |detect the root-node failure quickly and initialize a new round of root node election. If | +| |the root node and all the nodes on the second layer break down, the nodes on the third | +| |layer will initialize root node election and a new root node will be elected eventually. | +| | | +| |In the event of a failure of the intermediate nodes and the leaf nodes, failed nodes will | +| |reconnect their parent nodes respectively for a predefined number of times and will, then,| +| |reselect a new parent node to join the mesh network. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Root node switch |Users can call :cpp:func:`esp_mesh_waive_root` to switch root nodes in the network. | +| |The new root node can be specified by the users or be automatically elected by the | +| |network. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Root conflicts handling|Only the conflicts of root nodes connecting to the same router are handled. Conflicts of | +| |root nodes having the same router SSID, but different router BSSID, are not handled. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Parent node switch |Changing the physical position of a node in the mesh network will lead to declined signal | +| |strength of the parent node and problematic communication. Upon detecting such a problem, | +| |this function will automatically choose a better parent node for this node. | +| | | +| |When the position of a mobile node changes constantly, communication with the parent node | +| |deteriorates or even drops. After such a situation is detected, the parent of the mobile | +| |node is automatically reselected, so that communication with the network is maintained. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Loopback avoidance, |During the parent selection, the nodes covered in its own routing table are excluded, | +|detection and handling |so that the occurrence of a loopback is avoided. | +| | | +| |The path verification mechanism and the energy transfer mechanism are used for detecting | +| |the loopback. | +| | | +| |When a loopback is detected, the parent node will disconnect with the child node and | +| |inform it about the occurrence of the loop with a predefined reason code. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Channel switch |TO-DO | ++-----------------------+------------------------------------------------------------------------------------------+ +|Isolated node avoidance|TO-DO | +|and handling | | ++-----------------------+------------------------------------------------------------------------------------------+ + +4. Data Transmission +^^^^^^^^^^^^^^^^^^^^ + ++-----------------------+------------------------------------------------------------------------------------------+ +| Function | Description | ++=======================+==========================================================================================+ +|Reliability |ESP-MESH provides P2P(point-to-point) retransmission on mesh layer. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Upstream flow control |When a node in the mesh network is chosen as a parent node, the upstream data of each of | +| |its child nodes is allocated a receiving window, the size of which can be dynamically | +| |adjusted. The child node sends a window request to the parent node before sending data | +| |packets. The parent node compares the request’s sequence number, which corresponds to the | +| |child node's pending packet in the window request, with the sequence number of the parent | +| |node's most recently received packet from the child node. The size of the receiving window| +| |is calculated and returned to the child node. The child node, then, sends the packet, | +| |according to the reply’s receiving-window size. | +| | | +| |In addition, considering that there is only one exit from the entire mesh network, which | +| |is the root node, it is only the root node which can access external IP networks. If the | +| |other nodes are uninformed of the connection status between the root node and the external| +| |network, and keep sending packets to the root node, there is a possibility of packet loss | +| |or unnecessary packet-sending. ESP-MESH provides a method of flow control on the upstream | +| |data, which stabilizes the throughput of the mesh network’s exit by monitoring the | +| |connection status between the root node and the external network, thus avoiding packet | +| |loss or unnecessary packet-sending. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Supporting multicast |Only specified devices can receive multicast packets. Thus, users need to specify these | +|packets |devices by configuring the relevant input parameters for the API :cpp:func:`esp_mesh_send`| ++-----------------------+------------------------------------------------------------------------------------------+ +|Supporting broadcast |ESP-MESH provides a method to avoid a waste of bandwidth. | +|packets | | +| |1. When the broadcast packet transmitted by the intermediate node has been received from | +| |its parent node, the intermediate node sends itself a copy of the broadcast packet, while | +| |sending the original broadcast packet to its child nodes. | +| | | +| |2. When a broadcast packet transmitted by an intermediate node has been generated by | +| |itself, the broadcast packet is sent both to its parent and child nodes. | +| | | +| |3. When a broadcast packet transmitted by an intermediate node has been received from its | +| |child node, the broadcast packet is delivered to the intermediate node itself and its | +| |remaining child nodes, while a copy of the broadcast packet is transmitted to the | +| |intermediate’s parent node. | +| | | +| |4. When a leaf node generates a broadcast packet, the leaf node sends the broadcast packet| +| |to its parent node directly. | +| | | +| |5. When the broadcast packet transmitted by the root node has been generated by the root | +| |node itself, the broadcast packet is delivered to the root’s child node. | +| | | +| |6. When the broadcast packet transmitted by the root node has been received from its child| +| |node, the broadcast packet is sent to the remaining child nodes of the root node. | +| | | +| |7. When a node receives a broadcast packet initially sent from the address of the node | +| |itself, it discards this broadcast packet. | +| | | +| |8. When a node receives a broadcast packet from its parent node, which has been originally| +| |sent from its own child node, it discards this broadcast packet. | ++-----------------------+------------------------------------------------------------------------------------------+ +|Group control |Firsty users must specify a group ID for the device via :cpp:func:`esp_mesh_set_group_id`.| +| |Then when one packet is sent target to this group, only devices in this group can receive | +| |it. | ++-----------------------+------------------------------------------------------------------------------------------+ + +5. Performance +^^^^^^^^^^^^^^ + ++--------------------+------------------------------------------------------------------------------------------+ +| Function | Description | ++====================+==========================================================================================+ +|Networking time |Less than 15 seconds. The time is from tests executed on a network with 50 devices. | ++--------------------+------------------------------------------------------------------------------------------+ +|Healing time |If a root node breaks down, less than 10 seconds is taken for the network to detect that | +| |and generate a new root. If a parent node breaks down, less than 5 seconds is taken for | +| |its child nodes to detect that and reselect a new parent node. | +| |The time is also from tests executed on a network with 50 devices. | ++--------------------+------------------------------------------------------------------------------------------+ +|Layer forward delay |30ms. The delay is from tests executed on a network with 100 devices and all devices did | +| |not enable AMPDU. | ++--------------------+------------------------------------------------------------------------------------------+ +|Packet loss rate |max: %0.32 in data transmitted from layer 2 to layer 4; min: %0.00 | +| |The results are also from tests executed on a network with 100 devices. | ++--------------------+------------------------------------------------------------------------------------------+ +|Network capacity |The network capacity is terminated by the maximum number of devices allowed to be | +| |connected to the softAP, and by the maximum number of network layers allowed in the | +| |network. | ++--------------------+------------------------------------------------------------------------------------------+ + +**Note:** All device are configured 6 connections and 6 layers during the above mentioned tests. + +6. Security and Encryption +^^^^^^^^^^^^^^^^^^^^^^^^^^ +**(1) Uses WPA2-PSK** + +**(2) AES Encryption for Mesh VIE** + +7. Power Management (TO-DO) +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +**(1) Network Sleep** + +**(2) Standalone Station** + +8. User Intervention Network (TO-DO) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++-----------------------+---------------------------------------------------------------------------------------+ +| Function | Description | ++=======================+=======================================================================================+ +|Specifying the node |The user designates a node in the network as the root node, intermediate node or leaf | +|type |node. | ++-----------------------+---------------------------------------------------------------------------------------+ +|Specifying the parent |The user designates a parent node for a certain node. | +|type | | ++-----------------------+---------------------------------------------------------------------------------------+ +|Specifying the layer |The user designates the layer in which the above-mentioned node is to be located. | ++-----------------------+---------------------------------------------------------------------------------------+ + +How to Write a Mesh Application +------------------------------- + +**ESP-MESH API Error Code** + +We suggest that users regularly check the error code and add relevant handlers accordingly. + +ESP-MESH Programming Model +-------------------------- + +**Software Stack is demonstrated below:** + +.. figure:: ../../_static/mesh_software_stack.png + :align: center + :alt: ESP-MESH Software Stack + + ESP-MESH Software Stack + +**System Events delivery is demonstrated below:** + +.. figure:: ../../_static/mesh_events_delivery.png + :align: center + :alt: System Events Delivery + + ESP-MESH System Events Delivery + + +ESP-MESH events define almost all system events for any application tasks needed. The events include the Wi-Fi connection status of the station interface, the connection status of child nodes on the softAP interface, and the like. Firstly, application tasks need to register a mesh event callback handler via the API :cpp:func:`esp_mesh_set_config`. This handler is used for receiving events posted from the mesh stack and the LwIP stack. Application tasks can add relevant handlers to each event. + +**Examples:** + +(1) Application tasks can use Wi-Fi station connect statuses to determine when to send data to a parent node, to a root node or to external IP network. +(2) Application tasks can use Wi-Fi softAP statuses to determine when to send data to child nodes. + +Application tasks can access the mesh stack directly without having to go through the LwIP stack. The LwIP stack is not necessery for non-root nodes. +:cpp:func:`esp_mesh_send` and :cpp:func:`esp_mesh_recv` are used in the application tasks to send and receive messages over the mesh network. + +**Notes:** + +Since current ESP-IDF does not support system initializing without calling :cpp:func:`tcpip_adapter_init`, application tasks still need to perform the LwIP initialization and do remember firstly +1. stoping the DHCP server service on the softAP interface +2. stoping the DHCP client service on the station interface. + +Code Example: + +:cpp:func:`tcpip_adapter_init`; + +:cpp:func:`tcpip_adapter_dhcps_stop`; + +:cpp:func:`tcpip_adapter_dhcpc_stop`; + +The root node is connected with a router. Thus, in the application mesh event handler, once a node becomes the root, the DHCP client service must be started immediately to obtain IP address unless static IP settings is used. diff --git a/docs/en/api-reference/index.rst b/docs/en/api-reference/index.rst index 88f59d519..60917a867 100644 --- a/docs/en/api-reference/index.rst +++ b/docs/en/api-reference/index.rst @@ -6,6 +6,7 @@ API Reference :maxdepth: 2 Wi-Fi + Mesh Bluetooth Ethernet Peripherals diff --git a/docs/en/api-reference/mesh/esp_mesh.rst b/docs/en/api-reference/mesh/esp_mesh.rst new file mode 100644 index 000000000..d22e86d67 --- /dev/null +++ b/docs/en/api-reference/mesh/esp_mesh.rst @@ -0,0 +1,13 @@ +Mesh +===== + +Application Examples +-------------------- + +See :example:`mesh` directory of ESP-IDF examples that contains the following applications. + + +API Reference +-------------- + +.. include:: /_build/inc/esp_mesh.inc diff --git a/docs/en/api-reference/mesh/index.rst b/docs/en/api-reference/mesh/index.rst new file mode 100644 index 000000000..a988ad8b0 --- /dev/null +++ b/docs/en/api-reference/mesh/index.rst @@ -0,0 +1,9 @@ +Mesh API +********* + +.. toctree:: + :maxdepth: 1 + + ESP Mesh + +Example code for this API section is provided in :example:`mesh` directory of ESP-IDF examples. diff --git a/docs/zh_CN/api-guides/mesh.rst b/docs/zh_CN/api-guides/mesh.rst new file mode 100644 index 000000000..1c2834d5d --- /dev/null +++ b/docs/zh_CN/api-guides/mesh.rst @@ -0,0 +1 @@ +.. include:: ../../en/api-guides/mesh.rst \ No newline at end of file diff --git a/docs/zh_CN/api-reference/mesh/esp_mesh.rst b/docs/zh_CN/api-reference/mesh/esp_mesh.rst new file mode 100644 index 000000000..658aa16a7 --- /dev/null +++ b/docs/zh_CN/api-reference/mesh/esp_mesh.rst @@ -0,0 +1 @@ +.. include:: ../../../en/api-reference/mesh/esp_mesh.rst diff --git a/docs/zh_CN/api-reference/mesh/index.rst b/docs/zh_CN/api-reference/mesh/index.rst new file mode 100644 index 000000000..34515650e --- /dev/null +++ b/docs/zh_CN/api-reference/mesh/index.rst @@ -0,0 +1 @@ +.. include:: ../../../en/api-reference/mesh/index.rst \ No newline at end of file diff --git a/examples/mesh/internal_transceiver/Makefile b/examples/mesh/internal_transceiver/Makefile new file mode 100644 index 000000000..c5ade206b --- /dev/null +++ b/examples/mesh/internal_transceiver/Makefile @@ -0,0 +1,9 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := internal_transceiver + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/mesh/internal_transceiver/README.md b/examples/mesh/internal_transceiver/README.md new file mode 100644 index 000000000..6bfb8983a --- /dev/null +++ b/examples/mesh/internal_transceiver/README.md @@ -0,0 +1,23 @@ +# Mesh Internal Transceiver Example + +This example demonstrates how to use the mesh APIs to set up a mesh network, send and receive messages over the mesh network and etc. + +Features Demonstrated + +- mesh initialization + +- mesh configuration + +- mesh start + +- mesh event handler + +- root send and receive + +- other nodes receive + +Run `make menuconfig` to configure the mesh network channel, router SSID, router password and mesh softAP settings. + +When the mesh network is established and if you happen to run this example on ESP-WROVER-KIT boards, the RGB light indicator will show you on which layer devices are. +The pink reprents root; the yellow reprents layer 2; the red reprents layer 3; the blue reprents layer 4; the green reprents layer 5; the white reprents layer greater than 5. +Root continuously sends an On / Off control message to all devices in its routing table. Devices including root itself receive this message and do the On / Off. diff --git a/examples/mesh/internal_transceiver/main/Kconfig.projbuild b/examples/mesh/internal_transceiver/main/Kconfig.projbuild new file mode 100644 index 000000000..74dee1a28 --- /dev/null +++ b/examples/mesh/internal_transceiver/main/Kconfig.projbuild @@ -0,0 +1,74 @@ +menu "Example Configuration" + +config MESH_CHANNEL + int "channel" + range 1 14 + default 1 + help + mesh network channel. + +config MESH_ROUTER_SSID + string "Router SSID" + default "ROUTER_SSID" + help + Router SSID. + +config MESH_ROUTER_PASSWD + string "Router password" + default "ROUTER_PASSWD" + help + Router password. + +choice + bool "Mesh AP Authentication Mode" + default MAP_AUTH_MODE_OPEN + help + Authentication mode. + +config WIFI_AUTH_OPEN + bool "WIFI_AUTH_OPEN" +config WIFI_AUTH_WPA_PSK + bool "WIFI_AUTH_WPA_PSK" +config WIFI_AUTH_WPA2_PSK + bool "WIFI_AUTH_WPA2_PSK" +config WIFI_AUTH_WPA_WPA2_PSK + bool "WIFI_AUTH_WPA_WPA2_PSK" +endchoice + +config MESH_AP_AUTHMODE + int + default 0 if WIFI_AUTH_OPEN + default 2 if WIFI_AUTH_WPA_PSK + default 3 if WIFI_AUTH_WPA2_PSK + default 4 if WIFI_AUTH_WPA_WPA2_PSK + help + Mesh AP authentication mode. + +config MESH_AP_PASSWD + string "Mesh AP Password" + default "MAP_PASSWD" + help + Mesh AP password. + +config MESH_AP_CONNECTIONS + int "Mesh AP Connections" + range 1 10 + default 6 + help + The number of stations allowed to connect in. + +config MESH_MAX_LAYER + int "Mesh Max Layer" + range 1 15 + default 6 + help + Max layer allowed in mesh network. + +config MESH_ROUTE_TABLE_SIZE + int "Mesh Routing Table Size" + range 1 300 + default 50 + help + The number of devices over the network(max: 300). +endmenu + diff --git a/examples/mesh/internal_transceiver/main/component.mk b/examples/mesh/internal_transceiver/main/component.mk new file mode 100644 index 000000000..a98f634ea --- /dev/null +++ b/examples/mesh/internal_transceiver/main/component.mk @@ -0,0 +1,4 @@ +# +# "main" pseudo-component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/examples/mesh/internal_transceiver/main/include/mesh_light.h b/examples/mesh/internal_transceiver/main/include/mesh_light.h new file mode 100644 index 000000000..8290e6d4d --- /dev/null +++ b/examples/mesh/internal_transceiver/main/include/mesh_light.h @@ -0,0 +1,57 @@ +/* Mesh Internal Transceiver Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +#ifndef __MESH_LIGHT_H__ +#define __MESH_LIGHT_H__ + +#include "esp_err.h" + +/******************************************************* + * Constants + *******************************************************/ +#define MESH_LIGHT_RED (0xff) +#define MESH_LIGHT_GREEN (0xfe) +#define MESH_LIGHT_BLUE (0xfd) +#define MESH_LIGHT_YELLOW (0xfc) +#define MESH_LIGHT_PINK (0xfb) +#define MESH_LIGHT_INIT (0xfa) +#define MESH_LIGHT_WARNING (0xf9) + +#define MESH_TOKEN_ID (0x0) +#define MESH_TOKEN_VALUE (0xbeef) +#define MESH_CONTROL_CMD (0x2) + +/******************************************************* + * Type Definitions + *******************************************************/ + +/******************************************************* + * Structures + *******************************************************/ +typedef struct { + uint8_t cmd; + bool on; + uint8_t token_id; + uint16_t token_value; +} mesh_light_ctl_t; + +/******************************************************* + * Variables Declarations + *******************************************************/ + +/******************************************************* + * Function Definitions + *******************************************************/ +esp_err_t mesh_light_init(void); +esp_err_t mesh_light_set(int color); +esp_err_t mesh_light_process(mesh_addr_t *from, uint8_t *buf, uint16_t len); +void mesh_connected_indicator(int layer); +void mesh_disconnected_indicator(void); + +#endif /* __MESH_LIGHT_H__ */ diff --git a/examples/mesh/internal_transceiver/main/mesh_light.c b/examples/mesh/internal_transceiver/main/mesh_light.c new file mode 100644 index 000000000..15e548351 --- /dev/null +++ b/examples/mesh/internal_transceiver/main/mesh_light.c @@ -0,0 +1,174 @@ +/* Mesh Internal Transceiver Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +#include +#include "esp_err.h" +#include "esp_mesh.h" +#include "mesh_light.h" +#include "driver/gpio.h" +#include "driver/ledc.h" + +/******************************************************* + * Constants + *******************************************************/ +/* RGB configuration on ESP-WROVER-KIT board */ +#define LEDC_IO_0 (0) +#define LEDC_IO_1 (2) +#define LEDC_IO_2 (4) +#define LEDC_IO_3 (5) + +/******************************************************* + * Variable Definitions + *******************************************************/ +static bool bool_light_inited = false; + +/******************************************************* + * Function Definitions + *******************************************************/ +esp_err_t mesh_light_init(void) +{ + if (bool_light_inited == true) { + return ESP_OK; + } + bool_light_inited = true; + + ledc_timer_config_t ledc_timer = { + .bit_num = LEDC_TIMER_13_BIT, .freq_hz = 5000, .speed_mode = + LEDC_HIGH_SPEED_MODE, .timer_num = LEDC_TIMER_0 + }; + ledc_timer_config(&ledc_timer); + + ledc_channel_config_t ledc_channel = { .channel = LEDC_CHANNEL_0, .duty = + 100, .gpio_num = LEDC_IO_0, .intr_type = LEDC_INTR_FADE_END, + .speed_mode = LEDC_HIGH_SPEED_MODE, .timer_sel = LEDC_TIMER_0 + }; + ledc_channel_config(&ledc_channel); + ledc_channel.channel = LEDC_CHANNEL_1; + ledc_channel.gpio_num = LEDC_IO_1; + ledc_channel_config(&ledc_channel); + ledc_channel.channel = LEDC_CHANNEL_2; + ledc_channel.gpio_num = LEDC_IO_2; + ledc_channel_config(&ledc_channel); + ledc_channel.channel = LEDC_CHANNEL_3; + ledc_channel.gpio_num = LEDC_IO_3; + ledc_channel_config(&ledc_channel); + ledc_fade_func_install(0); + + mesh_light_set(MESH_LIGHT_INIT); + return ESP_OK; +} + +esp_err_t mesh_light_set(int color) +{ + switch (color) { + case MESH_LIGHT_RED: + /* Red */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 0); + break; + case MESH_LIGHT_GREEN: + /* Green */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 0); + break; + case MESH_LIGHT_BLUE: + /* Blue */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 3000); + break; + case MESH_LIGHT_YELLOW: + /* Yellow */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 0); + break; + case MESH_LIGHT_PINK: + /* Pink */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 3000); + break; + case MESH_LIGHT_INIT: + /* can't say */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 3000); + break; + case MESH_LIGHT_WARNING: + /* warning */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 3000); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 3000); + break; + default: + /* off */ + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, 0); + ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, 0); + } + + ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0); + ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1); + ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2); + + return ESP_OK; +} + +void mesh_connected_indicator(int layer) +{ + switch (layer) { + case 1: + mesh_light_set(MESH_LIGHT_PINK); + break; + case 2: + mesh_light_set(MESH_LIGHT_YELLOW); + break; + case 3: + mesh_light_set(MESH_LIGHT_RED); + break; + case 4: + mesh_light_set(MESH_LIGHT_BLUE); + break; + case 5: + mesh_light_set(MESH_LIGHT_GREEN); + break; + case 6: + mesh_light_set(MESH_LIGHT_WARNING); + break; + default: + mesh_light_set(0); + } +} + +void mesh_disconnected_indicator(void) +{ + mesh_light_set(MESH_LIGHT_WARNING); +} + +esp_err_t mesh_light_process(mesh_addr_t *from, uint8_t *buf, uint16_t len) +{ + mesh_light_ctl_t *in = (mesh_light_ctl_t *) buf; + if (!from || !buf || len < sizeof(mesh_light_ctl_t)) { + return ESP_FAIL; + } + if (in->token_id != MESH_TOKEN_ID || in->token_value != MESH_TOKEN_VALUE) { + return ESP_FAIL; + } + if (in->cmd == MESH_CONTROL_CMD) { + if (in->on) { + mesh_connected_indicator(esp_mesh_get_layer()); + } else { + mesh_light_set(0); + } + } + return ESP_OK; +} diff --git a/examples/mesh/internal_transceiver/main/mesh_main.c b/examples/mesh/internal_transceiver/main/mesh_main.c new file mode 100644 index 000000000..936a87da4 --- /dev/null +++ b/examples/mesh/internal_transceiver/main/mesh_main.c @@ -0,0 +1,400 @@ +/* Mesh Internal Transceiver Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +#include +#include "esp_wifi.h" +#include "esp_system.h" +#include "esp_event_loop.h" +#include "esp_log.h" +#include "esp_mesh.h" +#include "esp_mesh_internal.h" +#include "mesh_light.h" +#include "nvs_flash.h" + +/******************************************************* + * Macros + *******************************************************/ +//#define MESH_P2P_TOS_OFF +//#define MESH_ROOT_TO_GROUP + +/******************************************************* + * Constants + *******************************************************/ +#define RX_SIZE (1500) +#define TX_SIZE (1460) + +/******************************************************* + * Variable Definitions + *******************************************************/ +static const char *MESH_TAG = "mesh_main"; +static const uint8_t MESH_ID[6] = { 0x77, 0x77, 0x77, 0x77, 0x77, 0x77 }; +static uint8_t tx_buf[TX_SIZE] = { 0, }; +static uint8_t rx_buf[RX_SIZE] = { 0, }; +static bool is_running = true; +static bool is_mesh_connected = false; +static mesh_addr_t mesh_parent_addr; +static int mesh_layer = -1; + +mesh_light_ctl_t light_on = { + .cmd = MESH_CONTROL_CMD, + .on = 1, + .token_id = MESH_TOKEN_ID, + .token_value = MESH_TOKEN_VALUE, +}; + +mesh_light_ctl_t light_off = { + .cmd = MESH_CONTROL_CMD, + .on = 0, + .token_id = MESH_TOKEN_ID, + .token_value = MESH_TOKEN_VALUE, +}; + +/******************************************************* + * Function Declarations + *******************************************************/ + +/******************************************************* + * Function Definitions + *******************************************************/ +void mesh_send_to_group(const mesh_data_t *data, const mesh_addr_t *group, int seqno) +{ + + esp_err_t err = esp_mesh_send(group, data, + MESH_DATA_P2P | MESH_DATA_GROUP, + NULL, 0); + if (err) { + ESP_LOGE(MESH_TAG, + "[GROUP:%d][L:%d][rtableSize:%d]parent:"MACSTR" to "MACSTR", heap:%d[err:0x%x, proto:%d, tos:%d]", + seqno, mesh_layer, esp_mesh_get_routing_table_size(), + MAC2STR(mesh_parent_addr.addr), MAC2STR(group->addr), + esp_get_free_heap_size(), err, data->proto, data->tos) + } else { + ESP_LOGW(MESH_TAG, + "[GROUP:%d][L:%d][rtableSize:%d]parent:"MACSTR" to "MACSTR", heap:%d[err:0x%x, proto:%d, tos:%d]", + seqno, mesh_layer, esp_mesh_get_routing_table_size(), + MAC2STR(mesh_parent_addr.addr), MAC2STR(group->addr), + esp_get_free_heap_size(), err, data->proto, data->tos) + } +} + +void esp_mesh_p2p_tx_main(void *arg) +{ + int i; + esp_err_t err; + int send_count = 0; + mesh_addr_t route_table[CONFIG_MESH_ROUTE_TABLE_SIZE]; + int route_table_size = 0; + mesh_data_t data; + data.data = tx_buf; + data.size = sizeof(tx_buf); + data.proto = MESH_PROTO_BIN; +#ifdef MESH_P2P_TOS_OFF + data.tos = MESH_TOS_DEF; +#endif /* MESH_P2P_TOS_OFF */ + + is_running = true; + while (is_running) { + /* normal nodes rather than root do nothing but print */ + if (!esp_mesh_is_root()) { + ESP_LOGI(MESH_TAG, "[layer:%d]%s%s[rtableSize:%d]", mesh_layer, + is_mesh_connected ? "CONNECT" : "DISCONNECT", + esp_mesh_is_root() ? "" : "[NODE]", + esp_mesh_get_routing_table_size()) + vTaskDelay(10 * 1000 / portTICK_RATE_MS); + continue; + } + + esp_mesh_get_routing_table((mesh_addr_t *) &route_table, + CONFIG_MESH_ROUTE_TABLE_SIZE * 6, &route_table_size); + if (send_count && !(send_count % 100)) { + ESP_LOGI(MESH_TAG, "size:%d/%d,send_count:%d", route_table_size, + esp_mesh_get_routing_table_size(), send_count) + } + send_count++; + tx_buf[25] = (send_count >> 24) & 0xff; + tx_buf[24] = (send_count >> 16) & 0xff; + tx_buf[23] = (send_count >> 8) & 0xff; + tx_buf[22] = (send_count >> 0) & 0xff; + if (send_count % 2) { + memcpy(tx_buf, (uint8_t *)&light_on, sizeof(light_on)); + } else { + memcpy(tx_buf, (uint8_t *)&light_off, sizeof(light_off)); + } + +#ifdef MESH_ROOT_TO_GROUP + mesh_send_to_group(&data, (mesh_addr_t *)MESH_GROUP_ID, send_count); + vTaskDelay(1 * 1000 / portTICK_RATE_MS); + continue; +#endif + for (i = 0; i < route_table_size; i++) { + err = esp_mesh_send(&route_table[i], &data, MESH_DATA_P2P, NULL, 0); + if (err) { + ESP_LOGE(MESH_TAG, + "[ROOT-2-UNICAST:%d][L:%d]parent:"MACSTR" to "MACSTR", heap:%d[err:0x%x, proto:%d, tos:%d]", + send_count, mesh_layer, MAC2STR(mesh_parent_addr.addr), + MAC2STR(route_table[i].addr), esp_get_free_heap_size(), + err, data.proto, data.tos) + } else if (!(send_count % 100)) { + ESP_LOGW(MESH_TAG, + "[ROOT-2-UNICAST:%d][L:%d][rtableSize:%d]parent:"MACSTR" to "MACSTR", heap:%d[err:0x%x, proto:%d, tos:%d]", + send_count, mesh_layer, + esp_mesh_get_routing_table_size(), + MAC2STR(mesh_parent_addr.addr), + MAC2STR(route_table[i].addr), esp_get_free_heap_size(), + err, data.proto, data.tos) + } + } + vTaskDelay(1 * 1000 / portTICK_RATE_MS); + } + vTaskDelete(NULL); +} + +void esp_mesh_p2p_rx_main(void *arg) +{ + int recv_count = 0; + esp_err_t err; + mesh_addr_t from; + int send_count = 0; + mesh_data_t data; + int flag = 0; + data.data = rx_buf; + data.size = RX_SIZE; + + is_running = true; + while (is_running) { + data.size = RX_SIZE; + err = esp_mesh_recv(&from, &data, portMAX_DELAY, &flag, NULL, 0); + if (err != ESP_OK || !data.size) { + ESP_LOGE(MESH_TAG, "err:0x%x, size:%d", err, data.size) + continue; + } + /* extract send count */ + if (data.size >= sizeof(send_count)) { + send_count = (data.data[25] << 24) | (data.data[24] << 16) + | (data.data[23] << 8) | data.data[22]; + } + recv_count++; + /* process light control */ + mesh_light_process(&from, data.data, data.size); + if (!(recv_count % 1)) { + ESP_LOGW(MESH_TAG, + "[#RX:%d/%d][L:%d] parent:"MACSTR", receive from "MACSTR", size:%d, heap:%d, flag:%d[err:0x%x, proto:%d, tos:%d]", + recv_count, send_count, mesh_layer, + MAC2STR(mesh_parent_addr.addr), MAC2STR(from.addr), + data.size, esp_get_free_heap_size(), flag, err, data.proto, + data.tos) + } + } + vTaskDelete(NULL); +} + +esp_err_t esp_mesh_comm_p2p_start(void) +{ + static bool is_comm_p2p_started = false; + if (!is_comm_p2p_started) { + is_comm_p2p_started = true; + xTaskCreate(esp_mesh_p2p_tx_main, "MPTX", 3072, NULL, 5, NULL); + xTaskCreate(esp_mesh_p2p_rx_main, "MPRX", 3072, NULL, 5, NULL); + } + return ESP_OK; +} + +void esp_mesh_event_handler(mesh_event_t event) +{ +#ifdef MESH_ROOT_TO_GROUP + mesh_addr_t group; +#endif + static uint8_t last_layer = 0; + static int disconnect_count = 0; + ESP_LOGD(MESH_TAG, "esp_event_handler:%d", event.id) + + switch (event.id) { + case MESH_EVENT_STARTED: + ESP_LOGI(MESH_TAG, "") + break; + case MESH_EVENT_STOPPED: + ESP_LOGI(MESH_TAG, "") + break; + case MESH_EVENT_CHILD_CONNECTED: + ESP_LOGI(MESH_TAG, "aid:%d, "MACSTR"", + event.info.child_connected.aid, + MAC2STR(event.info.child_connected.mac)) + break; + case MESH_EVENT_CHILD_DISCONNECTED: + ESP_LOGI(MESH_TAG, "aid:%d, "MACSTR"", + event.info.child_disconnected.aid, + MAC2STR(event.info.child_disconnected.mac)) + break; + case MESH_EVENT_ROUTING_TABLE_ADD: + ESP_LOGW(MESH_TAG, "add %d, new:%d", + event.info.routing_table.rt_size_change, + event.info.routing_table.rt_size_new) + break; + + case MESH_EVENT_ROUTING_TABLE_REMOVE: + ESP_LOGW(MESH_TAG, "remove %d, new:%d", + event.info.routing_table.rt_size_change, + event.info.routing_table.rt_size_new) + break; + + case MESH_EVENT_NO_PARNET_FOUND: + ESP_LOGI(MESH_TAG, "scan times:%d", + event.info.no_parent.scan_times) + /* TODO handler for the failure */ + break; + + case MESH_EVENT_PARENT_CONNECTED: + mesh_layer = event.info.connected.self_layer; + memcpy(&mesh_parent_addr.addr, event.info.connected.connected.bssid, 6); + ESP_LOGI(MESH_TAG, + "layer:%d-->%d, parent:"MACSTR"%s, discnx:%d", + last_layer, mesh_layer, MAC2STR(mesh_parent_addr.addr), + esp_mesh_is_root() ? "" : + (mesh_layer == 2) ? "" : "", disconnect_count) + disconnect_count = 0; + last_layer = mesh_layer; + mesh_connected_indicator(mesh_layer); + is_mesh_connected = true; + if (esp_mesh_is_root()) { + tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA); + } +#ifdef MESH_ROOT_TO_GROUP + if (mesh_layer == 3) { + ESP_ERROR_CHECK( + esp_mesh_set_group_id((mesh_addr_t * ) MESH_GROUP_ID, 1)) + ESP_ERROR_CHECK(esp_mesh_get_group_list(&group, 1)) + ESP_LOGI(MESH_TAG, "num:%d, group "MACSTR"\n", + esp_mesh_get_group_num(), MAC2STR(group.addr)) + } +#endif + esp_mesh_comm_p2p_start(); + break; + + case MESH_EVENT_PARENT_DISCONNECTED: + ESP_LOGI(MESH_TAG, + "reason:%d, count:%d", + event.info.disconnected.reason, disconnect_count) + if (event.info.disconnected.reason == 201) { + disconnect_count++; + } + is_mesh_connected = false; + mesh_disconnected_indicator(); + break; + + case MESH_EVENT_LAYER_CHANGE: + mesh_layer = event.info.layer_change.new_layer; + ESP_LOGI(MESH_TAG, "layer:%d-->%d%s", + last_layer, mesh_layer, + esp_mesh_is_root() ? "" : + (mesh_layer == 2) ? "" : "") + last_layer = mesh_layer; + mesh_connected_indicator(mesh_layer); + break; + + case MESH_EVENT_ROOT_ADDRESS: + ESP_LOGI(MESH_TAG, "rc_addr:"MACSTR"", + MAC2STR(event.info.root_addr.addr)) + break; + + case MESH_EVENT_ROOT_GOT_IP: + /* root starts to connect to server */ + ESP_LOGI(MESH_TAG, + "sta ip: " IPSTR ", mask: " IPSTR ", gw: " IPSTR, + IP2STR(&event.info.got_ip.ip_info.ip), + IP2STR(&event.info.got_ip.ip_info.netmask), + IP2STR(&event.info.got_ip.ip_info.gw)) + break; + + case MESH_EVENT_ROOT_LOST_IP: + ESP_LOGI(MESH_TAG, "") + break; + + case MESH_EVENT_VOTE_STARTED: + ESP_LOGI(MESH_TAG, + "attempts:%d, reason:%d, rc_addr:"MACSTR"", + event.info.vote_started.attempts, + event.info.vote_started.reason, + MAC2STR(event.info.vote_started.rc_addr.addr)) + break; + + case MESH_EVENT_VOTE_STOPPED: + ESP_LOGI(MESH_TAG, "") + break; + + case MESH_EVENT_ROOT_SWITCH_REQ: + ESP_LOGI(MESH_TAG, + "reason:%d, rc_addr:"MACSTR"", + event.info.switch_req.reason, + MAC2STR( event.info.switch_req.rc_addr.addr)) + break; + case MESH_EVENT_ROOT_SWITCH_ACK: + ESP_LOGI(MESH_TAG, "") + break; + case MESH_EVENT_TODS_STATE: + ESP_LOGI(MESH_TAG, "state:%d", + event.info.toDS_state) + ; + break; + default: + ESP_LOGI(MESH_TAG, "unknown") + break; + } +} + +void app_main(void) +{ + ESP_ERROR_CHECK(mesh_light_init()); + ESP_ERROR_CHECK(nvs_flash_init()); + /* tcpip initialization */ + tcpip_adapter_init(); + /* for mesh + * stop DHCP server on softAP interface by default + * stop DHCP client on station interface by default + * */ + ESP_ERROR_CHECK(tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP)); + ESP_ERROR_CHECK(tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA)); +#if 0 + /* static ip settings */ + tcpip_adapter_ip_info_t sta_ip; + sta_ip.ip.addr = ipaddr_addr("192.168.1.102"); + sta_ip.gw.addr = ipaddr_addr("192.168.1.1"); + sta_ip.netmask.addr = ipaddr_addr("255.255.255.0"); + tcpip_adapter_set_ip_info(WIFI_IF_STA, &sta_ip); +#endif + /* wifi initialization */ + ESP_ERROR_CHECK(esp_event_loop_init(NULL, NULL)); + wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&config)); + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH)); + ESP_ERROR_CHECK(esp_wifi_start()); + /* mesh initialization */ + ESP_ERROR_CHECK(esp_mesh_init()); + ESP_ERROR_CHECK(esp_mesh_set_max_layer(CONFIG_MESH_MAX_LAYER)); + ESP_ERROR_CHECK(esp_mesh_set_ap_authmode(CONFIG_MESH_AP_AUTHMODE)); + ESP_ERROR_CHECK(esp_mesh_set_vote_percentage(1)); + ESP_ERROR_CHECK(esp_mesh_set_ap_assoc_expire(10)); + mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT(); + /* mesh ID */ + memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6); + /* mesh event callback */ + cfg.event_cb = &esp_mesh_event_handler; + /* router */ + cfg.channel = CONFIG_MESH_CHANNEL; + cfg.router.ssid_len = strlen(CONFIG_MESH_ROUTER_SSID); + memcpy((uint8_t *) &cfg.router.ssid, CONFIG_MESH_ROUTER_SSID, cfg.router.ssid_len); + memcpy((uint8_t *) &cfg.router.password, CONFIG_MESH_ROUTER_PASSWD, + strlen(CONFIG_MESH_ROUTER_PASSWD)); + /* mesh softAP */ + cfg.mesh_ap.max_connection = CONFIG_MESH_AP_CONNECTIONS; + memcpy((uint8_t *) &cfg.mesh_ap.password, CONFIG_MESH_AP_PASSWD, + strlen(CONFIG_MESH_AP_PASSWD)); + ESP_ERROR_CHECK(esp_mesh_set_config(&cfg)); + /* mesh start */ + ESP_ERROR_CHECK(esp_mesh_start()); + ESP_LOGI(MESH_TAG, "mesh starts successfully, heap:%d\n", esp_get_free_heap_size()) +}