# ESP-WIFI-MESH 编程指南

[English]

本文是 ESP-WIFI-MESH 的编程指南，包括 API 参考和编码示例。本指南分为以下部分：

1. ESP-WIFI-MESH 编程模型

2. 编写 ESP-WIFI-MESH 应用程序

3. 自组网

4. 应用实例

5. API 参考

有关 ESP-WIFI-MESH 协议的文档，请见 ESP-WIFI-MESH API 指南。有关 ESP-WIFI-MESH 开发框架的更多内容，请见 ESP-WIFI-MESH 开发框架。

## ESP-WIFI-MESH 编程模型

### 软件栈

ESP-WIFI-MESH 软件栈基于 Wi-Fi 驱动程序和 FreeRTOS 构建，某些情况下（如根节点）也会使用 LwIP 软件栈。下图展示了 ESP-WIFI-MESH 软件栈。

ESP-WIFI-MESH 软件栈

### 系统事件

应用程序可通过 ESP-WIFI-MESH 事件 与 ESP-WIFI-MESH 交互。由于 ESP-WIFI-MESH 构建在 Wi-Fi 软件栈之上，因此也可以通过 Wi-Fi 事件任务 与 Wi-Fi 驱动程序进行交互。下图展示了 ESP-WIFI-MESH 应用程序中各种系统事件的接口。

ESP-WIFI-MESH 系统事件交付

`mesh_event_id_t` 定义了所有可能的 ESP-WIFI-MESH 事件，并且可以指示父节点和子节点的连接或断开等事件。应用程序如需使用 ESP-WIFI-MESH 事件，则必须通过 `esp_event_handler_register()` 将 Mesh 事件处理程序 注册在默认事件任务中。注册完成后，ESP-WIFI-MESH 事件将包含与应用程序所有相关事件相关的处理程序。

Mesh 事件的典型应用场景包括：使用 `MESH_EVENT_PARENT_CONNECTED` 和 `MESH_EVENT_CHILD_CONNECTED` 事件来指示节点何时可以分别开始传输上行和下行的数据。同样，也可以使用 `IP_EVENT_STA_GOT_IP` 和 `IP_EVENT_STA_LOST_IP` 事件来指示根节点何时可以向外部 IP 网络传输数据。

警告

在自组网模式下使用 ESP-WIFI-MESH 时，用户必须确保不得调用 Wi-Fi API。原因在于：自组网模式将在内部调用 Wi-Fi API 实现连接/断开/扫描等操作。 此时，如果外部应用程序调用 Wi-Fi API（包括来自回调函数和 Wi-Fi 事件处理程序的调用）都可能会干扰 ESP-WIFI-MESH 的自组网行为。因此，用户不应该在 `esp_mesh_start()` 和 `esp_mesh_stop()` 之间调用 Wi-Fi API。

### LwIP & ESP-WIFI-MESH

应用程序无需通过 LwIP 层便可直接访问 ESP-WIFI-MESH 软件栈，LwIP 层仅在根节点和外部 IP 网络的数据发送与接收时会用到。但是，由于每个节点都有可能成为根节点（由于自动根节点选择机制的存在），每个节点仍必须初始化 LwIP 软件栈。

可成为根节点的每个节点都需要通过调用 `esp_netif_init()` 来初始化 LwIP 软件栈。为了防止非根节点访问 LwIP，应用程序不应使用 esp_netif API 创建或注册任何网络接口。

> ESP-WIFI-MESH 的根节点必须与路由器连接。因此，当一个节点成为根节点时，该节点对应的处理程序必须启动 DHCP 客户端服务并立即获取 IP 地址。这样做将允许其他节点开始向/从外部 IP 网络发送/接收数据包。如果使用静态 IP 设置，则不需要执行此步骤。

## 编写 ESP-WIFI-MESH 应用程序

ESP-WIFI-MESH 在正常启动前必须先初始化 LwIP 和 Wi-Fi 软件栈。下方代码展示了 ESP-WIFI-MESH 在开始自身初始化前必须完成的步骤。

    ESP_ERROR_CHECK(esp_netif_init());

    /* 事件初始化 */
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    /* Wi-Fi 初始化 */
    wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&config));
    /* 注册 IP 事件处理程序 */
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &ip_event_handler, NULL));
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH));
    ESP_ERROR_CHECK(esp_wifi_start());

在完成 LwIP 和 Wi-Fi 的初始化后，需完成以下三个步骤以启动并运行 ESP-WIFI-MESH。

1. 初始化 Mesh

2. 配置 ESP-WIFI-MESH 网络

3. 启动 Mesh

### 初始化 Mesh

下方代码片段展示如何初始化 ESP-WIFI-MESH。

    /* Mesh 初始化 */
    ESP_ERROR_CHECK(esp_mesh_init());
    /* 注册 mesh 事件处理程序 */
    ESP_ERROR_CHECK(esp_event_handler_register(MESH_EVENT, ESP_EVENT_ANY_ID, &mesh_event_handler, NULL));

### 配置 ESP-WIFI-MESH 网络

ESP-WIFI-MESH 可通过 `esp_mesh_set_config()` 进行配置，并使用 `mesh_cfg_t` 结构体传递参数。该结构体包含以下 ESP-WIFI-MESH 的配置参数：

参数 | 描述
--- | ---
Channel（信道） | 1 到 14 信道
Mesh ID | ESP-WIFI-MESH 网络的 ID，见 `mesh_addr_t`。
Router（路由器） | 路由器配置，见 `mesh_router_t`。
Mesh AP | Mesh AP 配置，见 `mesh_ap_cfg_t`
Crypto Functions（加密函数） | Mesh IE 的加密函数，见 `mesh_crypto_funcs_t`。

下方代码片段展示如何配置 ESP-WIFI-MESH。

    /* 默认启用 MESH IE 加密 */
    mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT();
    /* Mesh ID */
    memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6);
    /* 信道（需与路由器信道匹配）*/
    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

下方代码片段展示如何启动 ESP-WIFI-MESH。

    /* 启动 Mesh */
    ESP_ERROR_CHECK(esp_mesh_start());

启动 ESP-WIFI-MESH 后，应用程序应检查 ESP-WIFI-MESH 事件，以确定它是何时连接到网络的。连接后，应用程序可使用 `esp_mesh_send()` 和 `esp_mesh_recv()` 在 ESP-WIFI-MESH 网络中发送、接收数据包。

## 自组网

自组网是 ESP-WIFI-MESH 的功能之一，允许节点自动扫描/选择/连接/重新连接到其他节点和路由器。此功能允许 ESP-WIFI-MESH 网络具有很高的自主性，可适应变化的动态网络拓扑结构和环境。启用自组网功能后，ESP-WIFI-MESH 网络中的节点能够自主完成以下操作：

- 选择或选举根节点（见 建立网络 中的 自动根节点选择）

- 选择首选的父节点（见 建立网络 中的 父节点选择）

- 网络断开时自动重新连接（见 管理网络 中的 中间父节点失败）

启用自组网功能后，ESP-WIFI-MESH 软件栈将内部调用 Wi-Fi API。因此，在启用自组网功能时，应用层不得调用 Wi-Fi API，否则会干扰 ESP-WIFI-MESH 的工作。

### 开关自组网

应用程序可以在运行时通过调用 `esp_mesh_set_self_organized()` 函数，启用或禁用自组网功能。该函数具有以下两个参数：

- `bool enable` 指定启用或禁用自组网功能。

- `bool select_parent` 指定在启用自组网功能时是否应选择新的父节点。根据节点类型和节点当前状态，选择新的父节点具有不同的作用。在禁用自组网功能时，此参数不使用。

#### 禁用自组网

下方代码片段展示了如何禁用自组网功能。

    //禁用自组网
    esp_mesh_set_self_organized(false, false);

ESP-WIFI-MESH 将在禁用自组网时尝试维护节点的当前 Wi-Fi 状态。

- 如果节点先前已连接到其他节点，则将保持连接。

- 如果节点先前已断开连接并且正在扫描父节点或路由器，则将停止扫描。

- 如果节点以前尝试重新连接到父节点或路由器，则将停止重新连接。

#### 启用自组网

ESP-WIFI-MESH 将尝试在启用自组网时保持节点的当前 Wi-Fi 状态。但是，根据节点类型以及是否选择了新的父节点，节点的 Wi-Fi 状态可能会发生变化。下表显示了启用自组网的效果。

是否选择父节点 | 是否为根结点 | 作用
N | N | 已连接到父节点的节点将保持连接。
之前扫描父节点的节点将停止扫描。调用 `esp_mesh_connect()` 重新启动。
Y | 已连接到路由器的根节点将保持连接。
从路由器断开的根结点需调用 `esp_mesh_connect()` 进行重连。
Y | N | 没有父节点的节点将自动选择首选父节点并连接。
已连接到父节点的节点将断开连接，重新选择首选父节点并进行重连。
Y | 根结点在连接至父节点前必须放弃“根结点”的角色。因此，根节点将断开与路由器和所有子节点的连接，选择首选父节点并进行连接。

下方代码片段展示了如何启用自组网功能。

    //启用自组网，并选择一个新的父节点
    esp_mesh_set_self_organized(true, true);

    ...

    //启用自组网并手动重新连接
    esp_mesh_set_self_organized(true, false);
    esp_mesh_connect();

### 调用 Wi-Fi API

在有些情况下，应用程序可能希望在使用 ESP-WIFI-MESH 期间调用 Wi-Fi API。例如，应用程序可能需要手动扫描邻近的接入点 (AP)。但在应用程序调用任何 Wi-Fi API 之前，必须先禁用自组网。 否则，ESP-WIFI-MESH 软件栈可能会同时调用 Wi-Fi API，进而影响应用程序的正常调用。

应用程序不应在 `esp_mesh_set_self_organized()` 之间调用 Wi-Fi API。下方代码片段展示了应用程序如何在 ESP-WIFI-MESH 运行期间安全地调用 `esp_wifi_scan_start()`。

    //禁用自组网
    esp_mesh_set_self_organized(0, 0);

    //停止任何正在进行的扫描
    esp_wifi_scan_stop();
    //手动启动扫描运行完成时自动停止
    esp_wifi_scan_start();

    //进程扫描结果

    ...

    //如果仍为连接状态，则重新启用自组网
    esp_mesh_set_self_organized(1, 0);

    ...

    //如果不为根节点且未连接，则重新启用自组网
    esp_mesh_set_self_organized(1, 1);

    ...

    //如果为根节点且未连接，则重新启用
    esp_mesh_set_self_organized(1, 0);  //不选择新的父节点
    esp_mesh_connect();                 //手动重新连接到路由器

## 应用实例

ESP-IDF 包含以下 ESP-WIFI-MESH 示例项目：

内部通信示例 展示了如何搭建 ESP-WIFI-MESH 网络，并让根节点向网络中的每个节点发送数据包。

手动连网示例 展示了如何在禁用自组网功能的情况下使用 ESP-WIFI-MESH。此示例展示了如何对节点进行编程，以手动扫描潜在父节点的列表，并根据自定义标准选择父节点。

## API 参考

### Header File

- components/esp_wifi/include/esp_mesh.h

- This header file can be included with:

  >     #include "esp_mesh.h"

- This header file is a part of the API provided by the `esp_wifi` component. To declare that your component depends on `esp_wifi`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_wifi

  > or

  >     PRIV_REQUIRES esp_wifi

### Functions

esp_err_t esp_mesh_init(void)

  Mesh initialization.

  - Check whether Wi-Fi is started.

  - Initialize mesh global variables with default values.

  Attention

    This API shall be called after Wi-Fi is started.

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_deinit(void)

  Mesh de-initialization.

              - Release resources and stop the mesh

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_start(void)

  Start mesh.

  - Initialize mesh IE.

  - Start mesh network management service.

  - Create TX and RX queues according to the configuration.

  - Register mesh packets receive callback.

  Attention

    This API shall be called after mesh initialization and configuration.

  返回:

    - ESP_OK

    - ESP_FAIL

    - ESP_ERR_MESH_NOT_INIT

    - ESP_ERR_MESH_NOT_CONFIG

    - ESP_ERR_MESH_NO_MEMORY

esp_err_t esp_mesh_stop(void)

  Stop mesh.

  - Deinitialize mesh 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 Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled.

  - Set Wi-Fi Power Save type to WIFI_PS_NONE.

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, int flag, const mesh_opt_t opt[], int opt_count)

  Send a packet over the mesh network.

  - Send a packet to any device in the mesh network.

  - Send a packet to external IP network.

  Attention

    This API is not reentrant.

  参数:

    - to -- [in] the address of the final destination of the packet

      - If the packet is to the root, set this parameter to NULL.

      - If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then users need to call esp_mesh_recv_toDS() on the root node to forward this packet to the final IP server address.

    - data -- [in] pointer to a sending mesh packet

      - Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU.

      - Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary).

      - Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable).

        - If the packet is to the root, MESH_TOS_P2P must be set to ensure reliable transmission.

        - As long as the MESH_TOS_P2P is set, the API is blocking, even if the flag is set with MESH_DATA_NONBLOCK.

        - As long as the MESH_TOS_DEF is set, the API is non-blocking.

    - flag -- [in] bitmap for data sent

      - Flag is at least one of the three MESH_DATA_P2P/MESH_DATA_FROMDS/MESH_DATA_TODS, which represents the direction of packet sending.

      - Speed up the route search

        - If the packet is to an internal device, MESH_DATA_P2P should be set.

        - If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set.

        - If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set.

      - Specify whether this API is blocking or non-blocking, blocking by default.

      - In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but there is a risk that the 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.

    - opt -- [in] options

      - In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group.

      - Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address.

    - opt_count -- [in] option count

      - Currently, this API only takes one option, so opt_count is only supported to be 1.

  返回:

    - 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_block_time(uint32_t time_ms)

  Set blocking time of esp_mesh_send()

  - Suggest to set the blocking time to at least 5s when the environment is poor. Otherwise, esp_mesh_send() may timeout frequently.

  Attention

    This API shall be called before mesh is started.

  参数:

    time_ms -- [in] blocking time of esp_mesh_send(), unit:ms

  返回:

    - ESP_OK

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)

  Receive a packet targeted to self over the mesh network.

  flag could be MESH_DATA_FROMDS or MESH_DATA_TODS.

  Attention

    Mesh RX queue should be checked regularly to avoid running out of memory.

    - Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications.

  参数:

    - from -- [out] the address of the original source of the packet

    - data -- [out] pointer to the received mesh packet

      - Field proto is the data protocol in use. Should follow it to parse the received data.

      - Field tos is the transmission tos (type of service) in use.

    - timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever)

    - flag -- [out] bitmap for data received

      - MESH_DATA_FROMDS represents data from external IP network

      - MESH_DATA_TODS represents data directed upward within the mesh network

    - opt -- [out] options desired to receive

      - MESH_OPT_RECV_DS_ADDR attaches the DS address

    - opt_count -- [in] option count desired to receive

      - Currently, this API only takes one option, so opt_count is only supported to be 1.

  返回:

    - 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)

  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 the root.

  Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. 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.

  flag could be MESH_DATA_TODS.

  Attention

    This API is only called by the root.

  参数:

    - from -- [out] the address of the original source of the packet

    - to -- [out] the address contains remote IP address and port (IPv4:PORT)

    - data -- [out] pointer to the received packet

      - Contain the protocol and applications should follow it to parse the data.

    - timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever)

    - flag -- [out] bitmap for data received

      - MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router.

    - opt -- [out] options desired to receive

    - opt_count -- [in] option count desired to receive

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

    - ESP_ERR_MESH_NOT_START

    - ESP_ERR_MESH_TIMEOUT

    - ESP_ERR_MESH_DISCARD

    - ESP_ERR_MESH_RECV_RELEASE

esp_err_t esp_mesh_set_config(const mesh_cfg_t *config)

  Set mesh stack configuration.

  - Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh 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 the root to guarantee devices in different mesh networks can communicate with each other. max_connection of mesh softAP is limited by the max number of Wi-Fi softAP supported (max:10).

  Attention

    This API shall be called before mesh is started after mesh is initialized.

  参数:

    config -- [in] pointer to mesh stack configuration

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

    - ESP_ERR_MESH_NOT_ALLOWED

esp_err_t esp_mesh_get_config(mesh_cfg_t *config)

  Get mesh stack configuration.

  参数:

    config -- [out] pointer to mesh stack configuration

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_set_router(const mesh_router_t *router)

  Get router configuration.

  Attention

    This API is used to dynamically modify the router configuration after mesh is configured.

  参数:

    router -- [in] pointer to router configuration

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_get_router(mesh_router_t *router)

  Get router configuration.

  参数:

    router -- [out] pointer to router configuration

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_set_id(const mesh_addr_t *id)

  Set mesh network ID.

  Attention

    This API is used to dynamically modify the mesh network ID.

  参数:

    id -- [in] pointer to mesh network ID

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT: invalid argument

esp_err_t esp_mesh_get_id(mesh_addr_t *id)

  Get mesh network ID.

  参数:

    id -- [out] pointer to mesh network ID

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_set_type(mesh_type_t type)

  Designate device type over the mesh network.

  - MESH_IDLE: designates a device as a self-organized node for a mesh network

  - MESH_ROOT: designates the root node for a mesh network

  - MESH_LEAF: designates a device as a standalone Wi-Fi station that connects to a parent

  - MESH_STA: designates a device as a standalone Wi-Fi station that connects to a router

  参数:

    type -- [in] device type

  返回:

    - ESP_OK

    - ESP_ERR_MESH_NOT_ALLOWED

mesh_type_t esp_mesh_get_type(void)

  Get device type over mesh network.

  Attention

    This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED.

  返回:

    mesh type

esp_err_t esp_mesh_set_max_layer(int max_layer)

  Set network max layer value.

  - for tree topology, the max is 25.

  - for chain topology, the max is 1000.

  - Network max layer limits the max hop count.

  Attention

    This API shall be called before mesh is started.

  参数:

    max_layer -- [in] max layer value

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

    - ESP_ERR_MESH_NOT_ALLOWED

int esp_mesh_get_max_layer(void)

  Get max layer value.

  返回:

    max layer value

esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len)

  Set mesh softAP password.

  Attention

    This API shall be called before mesh is started.

  参数:

    - pwd -- [in] pointer to the password

    - len -- [in] password length

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

    - ESP_ERR_MESH_NOT_ALLOWED

esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode)

  Set mesh softAP authentication mode.

  Attention

    This API shall be called before mesh is started.

  参数:

    authmode -- [in] authentication mode

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

    - ESP_ERR_MESH_NOT_ALLOWED

wifi_auth_mode_t esp_mesh_get_ap_authmode(void)

  Get mesh softAP authentication mode.

  返回:

    authentication mode

esp_err_t esp_mesh_set_ap_connections(int connections)

  Set mesh max connection value.

  - Set mesh softAP max connection = mesh max connection + non-mesh max connection

  Attention

    This API shall be called before mesh is started.

  参数:

    connections -- [in] the number of max connections

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

int esp_mesh_get_ap_connections(void)

  Get mesh max connection configuration.

  返回:

    the number of mesh max connections

int esp_mesh_get_non_mesh_connections(void)

  Get non-mesh max connection configuration.

  返回:

    the number of non-mesh max connections

int esp_mesh_get_layer(void)

  Get current layer value over the mesh network.

  Attention

    This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED.

  返回:

    layer value

esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid)

  Get the parent BSSID.

  Attention

    This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED.

  参数:

    bssid -- [out] pointer to parent BSSID

  返回:

    - ESP_OK

    - ESP_FAIL

bool esp_mesh_is_root(void)

  Return whether the device is the root node of the network.

  返回:

    true/false

esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent)

  Enable/disable self-organized networking.

  - Self-organized networking has three main functions: select the root node; find a preferred parent; initiate reconnection if a disconnection is detected.

  - Self-organized networking is enabled by default.

  - If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent().

  Attention

    This API is used to dynamically modify whether to enable the self organizing.

  参数:

    - enable -- [in] enable or disable self-organized networking

    - select_parent -- [in] Only valid when self-organized networking is enabled.

      - if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices.

  返回:

    - ESP_OK

    - ESP_FAIL

bool esp_mesh_get_self_organized(void)

  Return whether enable self-organized networking or not.

  返回:

    true/false

esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason)

  Cause the root device to give up (waive) its mesh root status.

  - A device is elected root primarily based on RSSI from the external router.

  - If external router conditions change, users can 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 number of attempts (at least 15). 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 acknowledgment.

  - 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.

  Root switch is completed with minimal disruption to the whole mesh network.

  Attention

    This API is only called by the root.

  参数:

    - vote -- [in] vote configuration

      - If this parameter is set NULL, the vote will perform the default 15 times.

      - Field percentage threshold is 0.9 by default.

      - Field is_rc_specified shall be false.

      - Field attempts shall be at least 15 times.

    - reason -- [in] only accept MESH_VOTE_REASON_ROOT_INITIATED for now

  返回:

    - ESP_OK

    - ESP_ERR_MESH_QUEUE_FULL

    - ESP_ERR_MESH_DISCARD

    - ESP_FAIL

esp_err_t esp_mesh_set_vote_percentage(float percentage)

  Set vote percentage threshold for approval of being a root (default:0.9)

  - During the networking, only obtaining vote percentage reaches this threshold, the device could be a root.

  Attention

    This API shall be called before mesh is started.

  参数:

    percentage -- [in] vote percentage threshold

  返回:

    - ESP_OK

    - ESP_FAIL

float esp_mesh_get_vote_percentage(void)

  Get vote percentage threshold for approval of being a root.

  返回:

    percentage threshold

esp_err_t esp_mesh_set_ap_assoc_expire(int seconds)

  Set mesh softAP associate expired time (default:10 seconds)

  - 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.

  - If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds.

  参数:

    seconds -- [in] the expired time

  返回:

    - ESP_OK

    - ESP_FAIL

int esp_mesh_get_ap_assoc_expire(void)

  Get mesh softAP associate expired time.

  返回:

    seconds

int esp_mesh_get_total_node_num(void)

  Get total number of devices in current network (including the root)

  Attention

    The returned value might be incorrect when the network is changing.

  返回:

    total number of devices (including the root)

int esp_mesh_get_routing_table_size(void)

  Get the number of devices in this device's sub-network (including self)

  返回:

    the number of devices over this device's sub-network (including self)

esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size)

  Get routing table of this device's sub-network (including itself)

  参数:

    - mac -- [out] pointer to routing table

    - len -- [in] routing table size(in bytes)

    - size -- [out] pointer to the number of devices in routing table (including itself)

  返回:

    - ESP_OK

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_post_toDS_state(bool reachable)

  Post the toDS state to the mesh stack.

  Attention

    This API is only for the root.

  参数:

    reachable -- [in] this state represents whether the root is able to access external IP network

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending)

  Return the number of packets pending in the queue waiting to be sent by the mesh stack.

  参数:

    pending -- [out] pointer to the TX pending

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending)

  Return the number of packets available in the queue waiting to be received by applications.

  参数:

    pending -- [out] pointer to the RX pending

  返回:

    - ESP_OK

    - ESP_FAIL

int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in)

  Return the number of packets could be accepted from the specified address.

  参数:

    - addr -- [in] self address or an associate children address

    - xseqno_in -- [out] sequence number of the last received packet from the specified address

  返回:

    the number of upQ for a certain address

esp_err_t esp_mesh_set_xon_qsize(int qsize)

  Set the number of RX queue for the node, the average number of window allocated to one of its child node is: wnd = xon_qsize / (2 * max_connection + 1). However, the window of each child node is not strictly equal to the average value, it is affected by the traffic also.

  Attention

    This API shall be called before mesh is started.

  参数:

    qsize -- [in] default:32 (min:16)

  返回:

    - ESP_OK

    - ESP_FAIL

int esp_mesh_get_xon_qsize(void)

  Get queue size.

  返回:

    the number of queue

esp_err_t esp_mesh_allow_root_conflicts(bool allowed)

  Set whether allow more than one root existing in one network.

  - The default value is true, that is, multiple roots are allowed.

  参数:

    allowed -- [in] allow or not

  返回:

    - ESP_OK

    - ESP_WIFI_ERR_NOT_INIT

    - ESP_WIFI_ERR_NOT_START

bool esp_mesh_is_root_conflicts_allowed(void)

  Check whether allow more than one root to exist in one network.

  返回:

    true/false

esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num)

  Set group ID addresses.

  参数:

    - addr -- [in] pointer to new group ID addresses

    - num -- [in] the number of group ID addresses

  返回:

    - ESP_OK

    - ESP_MESH_ERR_ARGUMENT

esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num)

  Delete group ID addresses.

  参数:

    - addr -- [in] pointer to deleted group ID address

    - num -- [in] the number of group ID addresses

  返回:

    - ESP_OK

    - ESP_MESH_ERR_ARGUMENT

int esp_mesh_get_group_num(void)

  Get the number of group ID addresses.

  返回:

    the number of group ID addresses

esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num)

  Get group ID addresses.

  参数:

    - addr -- [out] pointer to group ID addresses

    - num -- [in] the number of group ID addresses

  返回:

    - ESP_OK

    - ESP_MESH_ERR_ARGUMENT

bool esp_mesh_is_my_group(const mesh_addr_t *addr)

  Check whether the specified group address is my group.

  返回:

    true/false

esp_err_t esp_mesh_set_capacity_num(int num)

  Set mesh network capacity (max:1000, default:300)

  Attention

    This API shall be called before mesh is started.

  参数:

    num -- [in] mesh network capacity

  返回:

    - ESP_OK

    - ESP_ERR_MESH_NOT_ALLOWED

    - ESP_MESH_ERR_ARGUMENT

int esp_mesh_get_capacity_num(void)

  Get mesh network capacity.

  返回:

    mesh network capacity

esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs)

  Set mesh IE crypto functions.

  Attention

    This API can be called at any time after mesh is configured.

  参数:

    crypto_funcs -- [in] crypto functions for mesh IE

    - If crypto_funcs is set to NULL, mesh IE is no longer encrypted.

  返回:

    - ESP_OK

esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len)

  Set mesh IE crypto key.

  Attention

    This API can be called at any time after mesh is configured.

  参数:

    - key -- [in] ASCII crypto key

    - len -- [in] length in bytes, range:8~64

  返回:

    - ESP_OK

    - ESP_MESH_ERR_ARGUMENT

esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len)

  Get mesh IE crypto key.

  参数:

    - key -- [out] ASCII crypto key

    - len -- [in] length in bytes, range:8~64

  返回:

    - ESP_OK

    - ESP_MESH_ERR_ARGUMENT

esp_err_t esp_mesh_set_root_healing_delay(int delay_ms)

  Set delay time before starting root healing.

  参数:

    delay_ms -- [in] delay time in milliseconds

  返回:

    - ESP_OK

int esp_mesh_get_root_healing_delay(void)

  Get delay time before network starts root healing.

  返回:

    delay time in milliseconds

esp_err_t esp_mesh_fix_root(bool enable)

  Enable network Fixed Root Setting.

  - Enabling fixed root disables automatic election of the root node via voting.

  - All devices in the network shall use the same Fixed Root Setting (enabled or disabled).

  - If Fixed Root is enabled, users should make sure a root node is designated for the network.

  参数:

    enable -- [in] enable or not

  返回:

    - ESP_OK

bool esp_mesh_is_root_fixed(void)

  Check whether network Fixed Root Setting is enabled.

  - Enable/disable network Fixed Root Setting by API esp_mesh_fix_root().

  - Network Fixed Root Setting also changes with the "flag" value in parent networking IE.

  返回:

    true/false

esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *parent_mesh_id, mesh_type_t my_type, int my_layer)

  Set a specified parent for the device.

  Attention

    This API can be called at any time after mesh is configured.

  参数:

    - parent -- [in] parent configuration, the SSID and the channel of the parent are mandatory.

      - If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent.

    - parent_mesh_id -- [in] parent mesh ID,

      - If this value is not set, the original mesh ID is used.

    - my_type -- [in] mesh type

      - MESH_STA is not supported.

      - If the parent set for the device is the same as the router in the network configuration, then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER.

    - my_layer -- [in] mesh layer

      - my_layer of the device may change after joining the network.

      - If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER.

      - If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer has the ability to extend the network.

  返回:

    - ESP_OK

    - ESP_ERR_ARGUMENT

    - ESP_ERR_MESH_NOT_CONFIG

esp_err_t esp_mesh_scan_get_ap_ie_len(int *len)

  Get mesh networking IE length of one AP.

  参数:

    len -- [out] mesh networking IE length

  返回:

    - ESP_OK

    - ESP_ERR_WIFI_NOT_INIT

    - ESP_ERR_INVALID_ARG

    - ESP_ERR_WIFI_FAIL

esp_err_t esp_mesh_scan_get_ap_record(wifi_ap_record_t *ap_record, void *buffer)

  Get AP record.

  Attention

    Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. See "manual_networking" example.

  参数:

    - ap_record -- [out] pointer to one AP record

    - buffer -- [out] pointer to the mesh networking IE of this AP

  返回:

    - ESP_OK

    - ESP_ERR_WIFI_NOT_INIT

    - ESP_ERR_INVALID_ARG

    - ESP_ERR_WIFI_FAIL

esp_err_t esp_mesh_flush_upstream_packets(void)

  Flush upstream packets pending in to_parent queue and to_parent_p2p queue.

  返回:

    - ESP_OK

esp_err_t esp_mesh_get_subnet_nodes_num(const mesh_addr_t *child_mac, int *nodes_num)

  Get the number of nodes in the subnet of a specific child.

  参数:

    - child_mac -- [in] an associated child address of this device

    - nodes_num -- [out] pointer to the number of nodes in the subnet of a specific child

  返回:

    - ESP_OK

    - ESP_ERR_MESH_NOT_START

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_get_subnet_nodes_list(const mesh_addr_t *child_mac, mesh_addr_t *nodes, int nodes_num)

  Get nodes in the subnet of a specific child.

  参数:

    - child_mac -- [in] an associated child address of this device

    - nodes -- [out] pointer to nodes in the subnet of a specific child

    - nodes_num -- [in] the number of nodes in the subnet of a specific child

  返回:

    - ESP_OK

    - ESP_ERR_MESH_NOT_START

    - ESP_ERR_MESH_ARGUMENT

esp_err_t esp_mesh_disconnect(void)

  Disconnect from current parent.

  返回:

    - ESP_OK

esp_err_t esp_mesh_connect(void)

  Connect to current parent.

  返回:

    - ESP_OK

esp_err_t esp_mesh_flush_scan_result(void)

  Flush scan result.

  返回:

    - ESP_OK

esp_err_t esp_mesh_switch_channel(const uint8_t *new_bssid, int csa_newchan, int csa_count)

  Cause the root device to add Channel Switch Announcement Element (CSA IE) to beacon.

  - Set the new channel

  - Set how many beacons with CSA IE will be sent before changing a new channel

  - Enable the channel switch function

  Attention

    This API is only called by the root.

  参数:

    - new_bssid -- [in] the new router BSSID if the router changes

    - csa_newchan -- [in] the new channel number to which the whole network is moving

    - csa_count -- [in] channel switch period(beacon count), unit is based on beacon interval of its softAP, the default value is 15.

  返回:

    - ESP_OK

esp_err_t esp_mesh_get_router_bssid(uint8_t *router_bssid)

  Get the router BSSID.

  参数:

    router_bssid -- [out] pointer to the router BSSID

  返回:

    - ESP_OK

    - ESP_ERR_WIFI_NOT_INIT

    - ESP_ERR_INVALID_ARG

int64_t esp_mesh_get_tsf_time(void)

  Get the TSF time.

  返回:

    the TSF time

esp_err_t esp_mesh_set_topology(esp_mesh_topology_t topo)

  Set mesh topology. The default value is MESH_TOPO_TREE.

  - MESH_TOPO_CHAIN supports up to 1000 layers

  Attention

    This API shall be called before mesh is started.

  参数:

    topo -- [in] MESH_TOPO_TREE or MESH_TOPO_CHAIN

  返回:

    - ESP_OK

    - ESP_MESH_ERR_ARGUMENT

    - ESP_ERR_MESH_NOT_ALLOWED

esp_mesh_topology_t esp_mesh_get_topology(void)

  Get mesh topology.

  返回:

    MESH_TOPO_TREE or MESH_TOPO_CHAIN

esp_err_t esp_mesh_enable_ps(void)

  Enable mesh Power Save function.

  Attention

    This API shall be called before mesh is started.

  返回:

    - ESP_OK

    - ESP_ERR_WIFI_NOT_INIT

    - ESP_ERR_MESH_NOT_ALLOWED

esp_err_t esp_mesh_disable_ps(void)

  Disable mesh Power Save function.

  Attention

    This API shall be called before mesh is started.

  返回:

    - ESP_OK

    - ESP_ERR_WIFI_NOT_INIT

    - ESP_ERR_MESH_NOT_ALLOWED

bool esp_mesh_is_ps_enabled(void)

  Check whether the mesh Power Save function is enabled.

  返回:

    true/false

bool esp_mesh_is_device_active(void)

  Check whether the device is in active state.

  - If the device is not in active state, it will neither transmit nor receive frames.

  返回:

    true/false

esp_err_t esp_mesh_set_active_duty_cycle(int dev_duty, int dev_duty_type)

  Set the device duty cycle and type.

  - The range of dev_duty values is 1 to 100. The default value is 10.

  - dev_duty = 100, the PS will be stopped.

  - dev_duty is better to not less than 5.

  - dev_duty_type could be MESH_PS_DEVICE_DUTY_REQUEST or MESH_PS_DEVICE_DUTY_DEMAND.

  - If dev_duty_type is set to MESH_PS_DEVICE_DUTY_REQUEST, the device will use a nwk_duty provided by the network.

  - If dev_duty_type is set to MESH_PS_DEVICE_DUTY_DEMAND, the device will use the specified dev_duty.

  Attention

    This API can be called at any time after mesh is started.

  参数:

    - dev_duty -- [in] device duty cycle

    - dev_duty_type -- [in] device PS duty cycle type, not accept MESH_PS_NETWORK_DUTY_MASTER

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_get_active_duty_cycle(int *dev_duty, int *dev_duty_type)

  Get device duty cycle and type.

  参数:

    - dev_duty -- [out] device duty cycle

    - dev_duty_type -- [out] device PS duty cycle type

  返回:

    - ESP_OK

esp_err_t esp_mesh_set_network_duty_cycle(int nwk_duty, int duration_mins, int applied_rule)

  Set the network duty cycle, duration and rule.

  - The range of nwk_duty values is 1 to 100. The default value is 10.

  - nwk_duty is the network duty cycle the entire network or the up-link path will use. A device that successfully sets the nwk_duty is known as a NWK-DUTY-MASTER.

  - duration_mins specifies how long the specified nwk_duty will be used. Once duration_mins expires, the root will take over as the NWK-DUTY-MASTER. If an existing NWK-DUTY-MASTER leaves the network, the root will take over as the NWK-DUTY-MASTER again.

  - duration_mins = (-1) represents nwk_duty will be used until a new NWK-DUTY-MASTER with a different nwk_duty appears.

  - Only the root can set duration_mins to (-1).

  - If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE, the nwk_duty will be used by the entire network.

  - If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_UPLINK, the nwk_duty will only be used by the up-link path nodes.

  - The root does not accept MESH_PS_NETWORK_DUTY_APPLIED_UPLINK.

  - A nwk_duty with duration_mins(-1) set by the root is the default network duty cycle used by the entire network.

  Attention

    This API can be called at any time after mesh is started.

    - In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of NWK-DUTY-MASTER.

    - If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network.

    - After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule.

  参数:

    - nwk_duty -- [in] network duty cycle

    - duration_mins -- [in] duration (unit: minutes)

    - applied_rule -- [in] only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_mesh_get_network_duty_cycle(int *nwk_duty, int *duration_mins, int *dev_duty_type, int *applied_rule)

  Get the network duty cycle, duration, type and rule.

  参数:

    - nwk_duty -- [out] current network duty cycle

    - duration_mins -- [out] the duration of current nwk_duty

    - dev_duty_type -- [out] if it includes MESH_PS_DEVICE_DUTY_MASTER, this device is the current NWK-DUTY-MASTER.

    - applied_rule -- [out] MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE

  返回:

    - ESP_OK

int esp_mesh_get_running_active_duty_cycle(void)

  Get the running active duty cycle.

  - The running active duty cycle of the root is 100.

  - If duty type is set to MESH_PS_DEVICE_DUTY_REQUEST, the running active duty cycle is nwk_duty provided by the network.

  - If duty type is set to MESH_PS_DEVICE_DUTY_DEMAND, the running active duty cycle is dev_duty specified by the users.

  - In a mesh network, devices are typically working with a certain duty-cycle (transmitting, receiving and sleep) to reduce the power consumption. The running active duty cycle decides the amount of awake time within a beacon interval. At each start of beacon interval, all devices wake up, broadcast beacons, and transmit packets if they do have pending packets for their parents or for their children. Note that Low-duty-cycle means devices may not be active in most of the time, the latency of data transmission might be greater.

  返回:

    the running active duty cycle

esp_err_t esp_mesh_ps_duty_signaling(int fwd_times)

  Duty signaling.

  参数:

    fwd_times -- [in] the times of forwarding duty signaling packets

  返回:

    - ESP_OK

### Unions

union mesh_addr_t
  #include <esp_mesh.h>

  Mesh address.

  Public Members

  uint8_t addr[6]

    mac address

  mip_t mip

    mip address

union mesh_event_info_t
  #include <esp_mesh.h>

  Mesh event information.

  Public Members

  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, devices shall check this state firstly before trying to send packets to external IP network. This state indicates right now whether the root is capable of sending packets out. If not, devices 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_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_root_fixed_t root_fixed

    fixed root

  mesh_event_scan_done_t scan_done

    scan done

  mesh_event_network_state_t network_state

    network state, such as whether current mesh network has a root.

  mesh_event_find_network_t find_network

    network found that can join

  mesh_event_router_switch_t router_switch

    new router information

  mesh_event_ps_duty_t ps_duty

    PS duty information

union mesh_rc_config_t
  #include <esp_mesh.h>

  Vote address configuration.

  Public Members

  int attempts

    max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default)

  mesh_addr_t rc_addr

    a new root address specified by users for API esp_mesh_waive_root()

### Structures

struct mip_t

  IP address and port.

  Public Members

  esp_ip4_addr_t ip4

    IP address

  uint16_t port

    port

struct mesh_event_channel_switch_t

  Channel switch information.

  Public Members

  uint8_t channel

    new channel

struct mesh_event_connected_t

  Parent connected information.

  Public Members

  wifi_event_sta_connected_t connected

    parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does

  uint16_t self_layer

    layer

  uint8_t duty

    parent duty

struct mesh_event_no_parent_found_t

  No parent found information.

  Public Members

  int scan_times

    scan times being through

struct mesh_event_layer_change_t

  Layer change information.

  Public Members

  uint16_t new_layer

    new layer

struct mesh_event_vote_started_t

  vote started information

  Public Members

  int reason

    vote reason, vote could be initiated by children or by the 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()

struct mesh_event_find_network_t

  find a mesh network that this device can join

  Public Members

  uint8_t channel

    channel number of the new found network

  uint8_t router_bssid[6]

    router BSSID

struct mesh_event_root_switch_req_t

  Root switch request information.

  Public Members

  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

struct mesh_event_root_conflict_t

  Other powerful root address.

  Public Members

  int8_t rssi

    rssi with router

  uint16_t capacity

    the number of devices in current network

  uint8_t addr[6]

    other powerful root address

struct mesh_event_routing_table_change_t

  Routing table change.

  Public Members

  uint16_t rt_size_new

    the new value

  uint16_t rt_size_change

    the changed value

struct mesh_event_root_fixed_t

  Root fixed.

  Public Members

  bool is_fixed

    status

struct mesh_event_scan_done_t

  Scan done　event information.

  Public Members

  uint8_t number

    the number of APs scanned

struct mesh_event_network_state_t

  Network state information.

  Public Members

  bool is_rootless

    whether current mesh network has a root

struct mesh_event_ps_duty_t

  PS duty information.

  Public Members

  uint8_t duty

    parent or child duty

  mesh_event_child_connected_t child_connected

    child info

struct mesh_opt_t

  Mesh option.

  Public Members

  uint8_t type

    option type

  uint16_t len

    option length

  uint8_t *val

    option value

struct mesh_data_t

  Mesh data for esp_mesh_send() and esp_mesh_recv()

  Public Members

  uint8_t *data

    data

  uint16_t size

    data size

  mesh_proto_t proto

    data protocol

  mesh_tos_t tos

    data type of service

struct mesh_router_t

  Router configuration.

  Public Members

  uint8_t ssid[32]

    SSID

  uint8_t ssid_len

    length of SSID

  uint8_t bssid[6]

    BSSID, if this value is specified, users should also specify "allow_router_switch".

  uint8_t password[64]

    password

  bool allow_router_switch

    if the BSSID is specified and this value is also set, when the router of this specified BSSID fails to be found after "fail" (mesh_attempts_t) times, the whole network is allowed to switch to another router with the same SSID. The new router might also be on a different channel. The default value is false. There is a risk that if the password is different between the new switched router and the previous one, the mesh network could be established but the root will never connect to the new switched router.

struct mesh_ap_cfg_t

  Mesh softAP configuration.

  Public Members

  uint8_t password[64]

    mesh softAP password

  uint8_t max_connection

    max number of stations allowed to connect in, default 6, max 10 = max_connection + nonmesh_max_connection max mesh connections

  uint8_t nonmesh_max_connection

    max non-mesh connections

struct mesh_cfg_t

  Mesh initialization configuration.

  Public Members

  uint8_t channel

    channel, the mesh network on

  bool allow_channel_switch

    if this value is set, when "fail" (mesh_attempts_t) times is reached, device will change to a full channel scan for a network that could join. The default value is false.

  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

struct mesh_vote_t

  Vote.

  Public Members

  float percentage

    vote percentage threshold for approval of being a root

  bool is_rc_specified

    if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make network start root election.

  mesh_rc_config_t config

    vote address configuration

struct mesh_tx_pending_t

  The number of packets pending in the queue waiting to be sent by the mesh stack.

  Public Members

  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

struct mesh_rx_pending_t

  The number of packets available in the queue waiting to be received by applications.

  Public Members

  int toDS

    to external DS

  int toSelf

    to self

### Macros

MESH_ROOT_LAYER

  root layer value

MESH_MTU

  max transmit unit(in bytes)

MESH_MPS

  max payload size(in bytes)

ESP_ERR_MESH_WIFI_NOT_START

  Mesh error code definition.

  Wi-Fi isn't started

ESP_ERR_MESH_NOT_INIT

  mesh isn't initialized

ESP_ERR_MESH_NOT_CONFIG

  mesh isn't configured

ESP_ERR_MESH_NOT_START

  mesh isn't started

ESP_ERR_MESH_NOT_SUPPORT

  not supported yet

ESP_ERR_MESH_NOT_ALLOWED

  operation is not allowed

ESP_ERR_MESH_NO_MEMORY

  out of memory

ESP_ERR_MESH_ARGUMENT

  illegal argument

ESP_ERR_MESH_EXCEED_MTU

  packet size exceeds MTU

ESP_ERR_MESH_TIMEOUT

  timeout

ESP_ERR_MESH_DISCONNECTED

  disconnected with parent on station interface

ESP_ERR_MESH_QUEUE_FAIL

  queue fail

ESP_ERR_MESH_QUEUE_FULL

  queue full

ESP_ERR_MESH_NO_PARENT_FOUND

  no parent found to join the mesh network

ESP_ERR_MESH_NO_ROUTE_FOUND

  no route found to forward the packet

ESP_ERR_MESH_OPTION_NULL

  no option found

ESP_ERR_MESH_OPTION_UNKNOWN

  unknown option

ESP_ERR_MESH_XON_NO_WINDOW

  no window for software flow control on upstream

ESP_ERR_MESH_INTERFACE

  low-level Wi-Fi interface error

ESP_ERR_MESH_DISCARD_DUPLICATE

  discard the packet due to the duplicate sequence number

ESP_ERR_MESH_DISCARD

  discard the packet

ESP_ERR_MESH_VOTING

  vote in progress

ESP_ERR_MESH_XMIT

  XMIT

ESP_ERR_MESH_QUEUE_READ

  error in reading queue

ESP_ERR_MESH_PS

  mesh PS is not specified as enable or disable

ESP_ERR_MESH_RECV_RELEASE

  release esp_mesh_recv_toDS

MESH_DATA_ENC

  Flags bitmap for esp_mesh_send() and esp_mesh_recv()

  data encrypted (Unimplemented)

MESH_DATA_P2P

  point-to-point delivery over the mesh network

MESH_DATA_FROMDS

  receive from external IP network

MESH_DATA_TODS

  identify this packet is target to external IP network

MESH_DATA_NONBLOCK

  esp_mesh_send() non-block

MESH_DATA_DROP

  in the situation of the root having been changed, identify this packet can be dropped by new root

MESH_DATA_GROUP

  identify this packet is target to a group address

MESH_OPT_SEND_GROUP

  Option definitions for esp_mesh_send() and esp_mesh_recv()

  data transmission by group; used with esp_mesh_send() and shall have payload

MESH_OPT_RECV_DS_ADDR

  return a remote IP address; used with esp_mesh_send() and esp_mesh_recv()

MESH_ASSOC_FLAG_MAP_ASSOC

  Flag of mesh networking IE.

  Mesh AP doesn't detect children leave yet

MESH_ASSOC_FLAG_VOTE_IN_PROGRESS

  station in vote, set when root vote start, clear when connect to router or when root switch

MESH_ASSOC_FLAG_STA_VOTED

  station vote done, set when connect to router

MESH_ASSOC_FLAG_NETWORK_FREE

  no root in current network

MESH_ASSOC_FLAG_STA_VOTE_EXPIRE

  the voted address is expired, means the voted device lose the chance to be root

MESH_ASSOC_FLAG_ROOTS_FOUND

  roots conflict is found, means that there are at least two roots in the mesh network

MESH_ASSOC_FLAG_ROOT_FIXED

  the root is fixed in the mesh network

MESH_PS_DEVICE_DUTY_REQUEST

  Mesh PS (Power Save) duty cycle type.

  requests to join a network PS without specifying a device duty cycle. After the device joins the network, a network duty cycle will be provided by the network

MESH_PS_DEVICE_DUTY_DEMAND

  requests to join a network PS and specifies a demanded device duty cycle

MESH_PS_NETWORK_DUTY_MASTER

  indicates the device is the NWK-DUTY-MASTER (network duty cycle master)

MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE

  Mesh PS (Power Save) duty cycle applied rule.

MESH_PS_NETWORK_DUTY_APPLIED_UPLINK

MESH_INIT_CONFIG_DEFAULT()

### Type Definitions

typedef mesh_addr_t mesh_event_root_address_t

  Root address.

typedef wifi_event_sta_disconnected_t mesh_event_disconnected_t

  Parent disconnected information.

typedef wifi_event_ap_staconnected_t mesh_event_child_connected_t

  Child connected information.

typedef wifi_event_ap_stadisconnected_t mesh_event_child_disconnected_t

  Child disconnected information.

typedef wifi_event_sta_connected_t mesh_event_router_switch_t

  New router information.

### Enumerations

enum mesh_event_id_t

  Enumerated list of mesh event id.

  Values:

  enumerator MESH_EVENT_STARTED

    mesh is started

  enumerator MESH_EVENT_STOPPED

    mesh is stopped

  enumerator MESH_EVENT_CHANNEL_SWITCH

    channel switch

  enumerator MESH_EVENT_CHILD_CONNECTED

    a child is connected on softAP interface

  enumerator MESH_EVENT_CHILD_DISCONNECTED

    a child is disconnected on softAP interface

  enumerator MESH_EVENT_ROUTING_TABLE_ADD

    routing table is changed by adding newly joined children

  enumerator MESH_EVENT_ROUTING_TABLE_REMOVE

    routing table is changed by removing leave children

  enumerator MESH_EVENT_PARENT_CONNECTED

    parent is connected on station interface

  enumerator MESH_EVENT_PARENT_DISCONNECTED

    parent is disconnected on station interface

  enumerator MESH_EVENT_NO_PARENT_FOUND

    no parent found

  enumerator MESH_EVENT_LAYER_CHANGE

    layer changes over the mesh network

  enumerator MESH_EVENT_TODS_STATE

    state represents whether the root is able to access external IP network. This state is a manual event that needs to be triggered with esp_mesh_post_toDS_state().

  enumerator MESH_EVENT_VOTE_STARTED

    the process of voting a new root is started either by children or by the root

  enumerator MESH_EVENT_VOTE_STOPPED

    the process of voting a new root is stopped

  enumerator MESH_EVENT_ROOT_ADDRESS

    the root address is obtained. It is posted by mesh stack automatically.

  enumerator MESH_EVENT_ROOT_SWITCH_REQ

    root switch request sent from a new voted root candidate

  enumerator MESH_EVENT_ROOT_SWITCH_ACK

    root switch acknowledgment responds the above request sent from current root

  enumerator MESH_EVENT_ROOT_ASKED_YIELD

    the 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.

  enumerator MESH_EVENT_ROOT_FIXED

    when devices join a network, if the setting of Fixed Root for one device is different from that of its parent, the device will update the setting the same as its parent's. Fixed Root Setting of each device is variable as that setting changes of the root.

  enumerator MESH_EVENT_SCAN_DONE

    if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add the corresponding scan done handler in this event.

  enumerator MESH_EVENT_NETWORK_STATE

    network state, such as whether current mesh network has a root.

  enumerator MESH_EVENT_STOP_RECONNECTION

    the root stops reconnecting to the router and non-root devices stop reconnecting to their parents.

  enumerator MESH_EVENT_FIND_NETWORK

    when the channel field in mesh configuration is set to zero, mesh stack will perform a full channel scan to find a mesh network that can join, and return the channel value after finding it.

  enumerator MESH_EVENT_ROUTER_SWITCH

    if users specify BSSID of the router in mesh configuration, when the root connects to another router with the same SSID, this event will be posted and the new router information is attached.

  enumerator MESH_EVENT_PS_PARENT_DUTY

    parent duty

  enumerator MESH_EVENT_PS_CHILD_DUTY

    child duty

  enumerator MESH_EVENT_PS_DEVICE_DUTY

    device duty

  enumerator MESH_EVENT_MAX

enum mesh_type_t

  Device type.

  Values:

  enumerator MESH_IDLE

    hasn't joined the mesh network yet

  enumerator MESH_ROOT

    the only sink of the mesh network. Has the ability to access external IP network

  enumerator MESH_NODE

    intermediate device. Has the ability to forward packets over the mesh network

  enumerator MESH_LEAF

    has no forwarding ability

  enumerator MESH_STA

    connect to router with a standalone Wi-Fi station mode, no network expansion capability

enum mesh_proto_t

  Protocol of transmitted application data.

  Values:

  enumerator MESH_PROTO_BIN

    binary

  enumerator MESH_PROTO_HTTP

    HTTP protocol

  enumerator MESH_PROTO_JSON

    JSON format

  enumerator MESH_PROTO_MQTT

    MQTT protocol

  enumerator MESH_PROTO_AP

    IP network mesh communication of node's AP interface

  enumerator MESH_PROTO_STA

    IP network mesh communication of node's STA interface

enum mesh_tos_t

  For reliable transmission, mesh stack provides three type of services.

  Values:

  enumerator MESH_TOS_P2P

    provide P2P (point-to-point) retransmission on mesh stack by default

  enumerator MESH_TOS_E2E

    provide E2E (end-to-end) retransmission on mesh stack (Unimplemented)

  enumerator MESH_TOS_DEF

    no retransmission on mesh stack

enum mesh_vote_reason_t

  Vote reason.

  Values:

  enumerator MESH_VOTE_REASON_ROOT_INITIATED

    vote is initiated by the root

  enumerator MESH_VOTE_REASON_CHILD_INITIATED

    vote is initiated by children

enum mesh_disconnect_reason_t

  Mesh disconnect reason code.

  Values:

  enumerator MESH_REASON_CYCLIC

    cyclic is detected

  enumerator MESH_REASON_PARENT_IDLE

    parent is idle

  enumerator MESH_REASON_LEAF

    the connected device is changed to a leaf

  enumerator MESH_REASON_DIFF_ID

    in different mesh ID

  enumerator MESH_REASON_ROOTS

    root conflict is detected

  enumerator MESH_REASON_PARENT_STOPPED

    parent has stopped the mesh

  enumerator MESH_REASON_SCAN_FAIL

    scan fail

  enumerator MESH_REASON_IE_UNKNOWN

    unknown IE

  enumerator MESH_REASON_WAIVE_ROOT

    waive root

  enumerator MESH_REASON_PARENT_WORSE

    parent with very poor RSSI

  enumerator MESH_REASON_EMPTY_PASSWORD

    use an empty password to connect to an encrypted parent

  enumerator MESH_REASON_PARENT_UNENCRYPTED

    connect to an unencrypted parent/router

enum esp_mesh_topology_t

  Mesh topology.

  Values:

  enumerator MESH_TOPO_TREE

    tree topology

  enumerator MESH_TOPO_CHAIN

    chain topology

enum mesh_event_toDS_state_t

  The reachability of the root to a DS (distribute system)

  Values:

  enumerator MESH_TODS_UNREACHABLE

    the root isn't able to access external IP network

  enumerator MESH_TODS_REACHABLE

    the root is able to access external IP network

提供有关此文档的反馈