text
stringlengths
1
3.82k
__index_level_0__
int64
0
366
After the Ethernet driver installation, the flow control feature is disabled by default. You can enable it by: .. highlight:: c :: bool flow_ctrl_enable = true; esp_eth_ioctl(eth_handle, ETH_CMD_S_FLOW_CTRL, &flow_ctrl_enable); One thing that should be kept in mind is that the pause frame ability is advertised to the peer end by PHY during auto-negotiation. The Ethernet driver sends a pause frame only when both sides of the link support it. .. Examples Application Examples .. Advanced Topics .. _advanced-topics: Advanced Topics Custom PHY Driver There are multiple PHY manufacturers with wide portfolios of chips available. The ESP-IDF already supports several PHY chips however one can easily get to a point where none of them satisfies the user's actual needs due to price, features, stock availability, etc. Luckily, a management interface between EMAC and PHY is standardized by IEEE 802.3 in Section 22.2.4 Management Functions. It defines provisions of the so-called "MII Management Interface" to control the PHY and gather status from the PHY.
48
A set of management registers is defined to control chip behavior, link properties, auto-negotiation configuration, etc. This basic management functionality is addressed by :component_file:`esp_eth/src/esp_eth_phy_802_3.c` in ESP-IDF and so it makes the creation of a new custom PHY chip driver quite a simple task. .. note:: Always consult with PHY datasheet since some PHY chips may not comply with IEEE 802.3, Section 22.2.4. It does not mean you are not able to create a custom PHY driver, but it just requires more effort. You will have to define all PHY management functions. The majority of PHY management functionality required by the ESP-IDF Ethernet driver is covered by the :component_file:`esp_eth/src/esp_eth_phy_802_3.c`. However, the following may require developing chip-specific management functions: **Steps to create a custom PHY driver:** Once you finish the new custom PHY driver implementation, consider sharing it among other users via `IDF Component Registry `_. .. API Reference API Reference .
48
. include-build-file:: inc/eth_types.inc .. include-build-file:: inc/esp_eth.inc .. include-build-file:: inc/esp_eth_driver.inc .. include-build-file:: inc/esp_eth_com.inc .. include-build-file:: inc/esp_eth_mac.inc .. include-build-file:: inc/esp_eth_phy.inc .. include-build-file:: inc/esp_eth_phy_802_3.inc .. include-build-file:: inc/esp_eth_netif_glue.inc
48
Wi-Fi Easy Connect\ :sup:`TM` (DPP) Wi-Fi Easy Connect\ :sup:`TM`, also known as Device Provisioning Protocol (DPP) or Easy Connect, is a provisioning protocol certified by Wi-Fi Alliance. It is a secure and standardized provisioning protocol for configuration of Wi-Fi Devices. With Easy Connect, adding a new device to a network is as simple as scanning a QR Code. This reduces complexity and enhances user experience while onboarding devices without UI like Smart Home and IoT products. Unlike old protocols like Wi-Fi Protected Setup (WPS), Wi-Fi Easy Connect in corporates strong encryption through public key cryptography to ensure networks remain secure as new devices are added. Easy Connect brings many benefits in the user experience: - Simple and intuitive to use; no lengthy instructions to follow for new device setup - No need to remember and enter passwords into the device being provisioned - Works with electronic or printed QR codes, or human-readable strings - Supports both WPA2 and WPA3 networks Please refer to Wi-Fi Alliance's official page on `Easy Connect `_ for more information.
49
{IDF_TARGET_NAME} supports Enrollee mode of Easy Connect with QR Code as the provisioning method. A display is required to display this QR Code. Users can scan this QR Code using their capable device and provision the {IDF_TARGET_NAME} to their Wi-Fi network. The provisioning device needs to be connected to the AP which need not support Wi-Fi Easy Connect\ :sup:`TM`. Easy Connect is still an evolving protocol. Of known platforms that support the QR Code method are some Android smartphones with Android 10 or higher. To use Easy Connect, no additional App needs to be installed on the supported smartphone. Application Example Example on how to provision {IDF_TARGET_NAME} using a supported smartphone: :example:`wifi/wifi_easy_connect/dpp-enrollee`. API Reference .. include-build-file:: inc/esp_dpp.inc
49
Wi-Fi Introduction The Wi-Fi libraries provide support for configuring and monitoring the {IDF_TARGET_NAME} Wi-Fi networking functionality. This includes configuration for: - Station mode (aka STA mode or Wi-Fi client mode). {IDF_TARGET_NAME} connects to an access point. - AP mode (aka Soft-AP mode or Access Point mode). Stations connect to the {IDF_TARGET_NAME}. - Station/AP-coexistence mode ({IDF_TARGET_NAME} is concurrently an access point and a station connected to another access point). - Various security modes for the above (WPA, WPA2, WPA3, etc.) - Scanning for access points (active & passive scanning). - Promiscuous mode for monitoring of IEEE802.11 Wi-Fi packets. Application Examples Several application examples demonstrating the functionality of Wi-Fi library are provided in :example:`wifi` directory of ESP-IDF repository. Please check the :example_file:`README ` for more details. API Reference .. include-build-file:: inc/esp_wifi.inc .. include-build-file:: inc/esp_wifi_types.
50
inc .. include-build-file:: inc/esp_eap_client.inc .. include-build-file:: inc/esp_wps.inc .. include-build-file:: inc/esp_rrm.inc .. include-build-file:: inc/esp_wnm.inc .. include-build-file:: inc/esp_mbo.inc
50
ESP-NOW Overview ESP-NOW is a kind of connectionless Wi-Fi communication protocol that is defined by Espressif. In ESP-NOW, application data is encapsulated in a vendor-specific action frame and then transmitted from one Wi-Fi device to another without connection. CTR with CBC-MAC Protocol (CCMP) is used to protect the action frame for security. ESP-NOW is widely used in smart light, remote controlling, sensor, etc. Frame Format ESP-NOW uses a vendor-specific action frame to transmit ESP-NOW data. The default ESP-NOW bit rate is 1 Mbps. The format of the vendor-specific action frame is as follows: .. highlight:: none :: | MAC Header | Category Code | Organization Identifier | Random Values | Vendor Specific Content | FCS | 24 bytes 1 byte 3 bytes 4 bytes 7-257 bytes 4 bytes - Category Code: The Category Code field is set to the value (127) indicating the vendor-specific category. - Organization Identifier: The Organization Identifier contains a unique identifier (0x18fe34), which is the first three bytes of MAC address applied by Espressif.
51
- Random Value: The Random Value filed is used to prevents relay attacks. - Vendor Specific Content: The Vendor Specific Content contains vendor-specific fields as follows: .. highlight:: none :: | Element ID | Length | Organization Identifier | Type | Version | Body | 1 byte 1 byte 3 bytes 1 byte 1 byte 0-250 bytes - Element ID: The Element ID field is set to the value (221), indicating the vendor-specific element. - Length: The length is the total length of Organization Identifier, Type, Version and Body. - Organization Identifier: The Organization Identifier contains a unique identifier (0x18fe34), which is the first three bytes of MAC address applied by Espressif. - Type: The Type field is set to the value (4) indicating ESP-NOW. - Version: The Version field is set to the version of ESP-NOW. - Body: The Body contains the ESP-NOW data. As ESP-NOW is connectionless, the MAC header is a little different from that of standard frames.
51
The FromDS and ToDS bits of FrameControl field are both 0. The first address field is set to the destination address. The second address field is set to the source address. The third address field is set to broadcast address (0xff:0xff:0xff:0xff:0xff:0xff). Security ESP-NOW uses the CCMP method, which is described in IEEE Std. 802.11-2012, to protect the vendor-specific action frame. The Wi-Fi device maintains a Primary Master Key (PMK) and several Local Master Keys (LMK). The lengths of both PMK and LMk are 16 bytes. Encrypting multicast vendor-specific action frame is not supported. Initialization and Deinitialization Call :cpp:func:`esp_now_init()` to initialize ESP-NOW and :cpp:func:`esp_now_deinit()` to de-initialize ESP-NOW. ESP-NOW data must be transmitted after Wi-Fi is started, so it is recommended to start Wi-Fi before initializing ESP-NOW and stop Wi-Fi after de-initializing ESP-NOW. When :cpp:func:`esp_now_deinit()` is called, all of the information of paired devices are deleted.
51
Add Paired Device Call :cpp:func:`esp_now_add_peer()` to add the device to the paired device list before you send data to this device. If security is enabled, the LMK must be set. You can send ESP-NOW data via both the Station and the SoftAP interface. Make sure that the interface is enabled before sending ESP-NOW data. .. only:: esp32c2 The maximum number of paired devices is 20, and the paired encryption devices are no more than 4, the default is 2. If you want to change the number of paired encryption devices, set :ref:`CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM` in the Wi-Fi component configuration menu. .. only:: esp32 or esp32s2 or esp32s3 or esp32c3 or esp32c6 The maximum number of paired devices is 20, and the paired encryption devices are no more than 17, the default is 7. If you want to change the number of paired encryption devices, set :ref:`CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM` in the Wi-Fi component configuration menu. A device with a broadcast MAC address must be added before sending broadcast data.
51
The range of the channel of paired devices is from 0 to 14. If the channel is set to 0, data will be sent on the current channel. Otherwise, the channel must be set as the channel that the local device is on. Send ESP-NOW Data Call :cpp:func:`esp_now_send()` to send ESP-NOW data and :cpp:func:`esp_now_register_send_cb()` to register sending callback function. It will return `ESP_NOW_SEND_SUCCESS` in sending callback function if the data is received successfully on the MAC layer. Otherwise, it will return `ESP_NOW_SEND_FAIL`. Several reasons can lead to ESP-NOW fails to send data. For example, the destination device does not exist; the channels of the devices are not the same; the action frame is lost when transmitting on the air, etc. It is not guaranteed that application layer can receive the data. If necessary, send back ack data when receiving ESP-NOW data. If receiving ack data timeouts, retransmit the ESP-NOW data. A sequence number can also be assigned to ESP-NOW data to drop the duplicate data.
51
If there is a lot of ESP-NOW data to send, call :cpp:func:`esp_now_send()` to send less than or equal to 250 bytes of data once a time. Note that too short interval between sending two ESP-NOW data may lead to disorder of sending callback function. So, it is recommended that sending the next ESP-NOW data after the sending callback function of the previous sending has returned. The sending callback function runs from a high-priority Wi-Fi task. So, do not do lengthy operations in the callback function. Instead, post the necessary data to a queue and handle it from a lower priority task. Receiving ESP-NOW Data Call :cpp:func:`esp_now_register_recv_cb()` to register receiving callback function. Call the receiving callback function when receiving ESP-NOW. The receiving callback function also runs from the Wi-Fi task. So, do not do lengthy operations in the callback function. Instead, post the necessary data to a queue and handle it from a lower priority task. Config ESP-NOW Rate .
51
. only:: esp32 or esp32s2 or esp32s3 or esp32c2 or esp32c3 Call :cpp:func:`esp_wifi_config_espnow_rate()` to config ESP-NOW rate of specified interface. Make sure that the interface is enabled before config rate. This API should be called after :cpp:func:`esp_wifi_start()`. .. only:: esp32c6 Call :cpp:func:`esp_now_set_peer_rate_config()` to configure ESP-NOW rate of each peer. Make sure that the peer is added before configuring the rate. This API should be called after :cpp:func:`esp_wifi_start()` and :cpp:func:`esp_now_add_peer()`. .. note:: :cpp:func:`esp_wifi_config_espnow_rate()` is deprecated, please use cpp::func:`esp_now_set_peer_rate_config()` instead. Config ESP-NOW Power-saving Parameter Sleep is supported only when {IDF_TARGET_NAME} is configured as station. Call :cpp:func:`esp_now_set_wake_window()` to configure Window for ESP-NOW RX at sleep. The default value is the maximum, which allowing RX all the time. If Power-saving is needed for ESP-NOW, call :cpp:func:`esp_wifi_connectionless_module_set_wake_interval()` to configure Interval as well.
51
.. only:: SOC_WIFI_SUPPORTED Please refer to :ref:`connectionless module power save ` to get more detail. Application Examples API Reference .. include-build-file:: inc/esp_now.inc
51
SmartConfig The SmartConfig\ :sup:`TM` is a provisioning technology developed by TI to connect a new Wi-Fi device to a Wi-Fi network. It uses a mobile application to broadcast the network credentials from a smartphone, or a tablet, to an un-provisioned Wi-Fi device. The advantage of this technology is that the device does not need to directly know SSID or password of an Access Point (AP). This information is provided using the smartphone. This is particularly important to headless device and systems, due to their lack of a user interface. If you are looking for other options to provision your {IDF_TARGET_NAME} devices, check :doc:`../provisioning/index`. Application Example Connect {IDF_TARGET_NAME} to the target AP using SmartConfig: :example:`wifi/smart_config`. API Reference .. include-build-file:: inc/esp_smartconfig.inc
52
ESP-WIFI-MESH Programming Guide This is a programming guide for ESP-WIFI-MESH, including the API reference and coding examples. This guide is split into the following parts: For documentation regarding the ESP-WIFI-MESH protocol, please see the :doc:`ESP-WIFI-MESH API Guide `. For more information about ESP-WIFI-MESH Development Framework, please see `ESP-WIFI-MESH Development Framework `_. .. ESP-WIFI-MESH Programming Model .. _mesh-programming-model: ESP-WIFI-MESH Programming Model Software Stack The ESP-WIFI-MESH software stack is built atop the Wi-Fi Driver/FreeRTOS and may use the LwIP Stack in some instances (i.e., the root node). The following diagram illustrates the ESP-WIFI-MESH software stack. .. _mesh-going-to-software-stack: .. figure:: ../../../_static/mesh-software-stack.png :align: center :alt: ESP-WIFI-MESH Software Stack :figclass: align-center ESP-WIFI-MESH Software Stack .. _mesh-events: System Events An application interfaces with ESP-WIFI-MESH via **ESP-WIFI-MESH Events**.
53
Since ESP-WIFI-MESH is built atop the Wi-Fi stack, it is also possible for the application to interface with the Wi-Fi driver via the **Wi-Fi Event Task**. The following diagram illustrates the interfaces for the various System Events in an ESP-WIFI-MESH application. .. figure:: ../../../_static/mesh-events-delivery.png :align: center :alt: ESP-WIFI-MESH System Events Delivery :figclass: align-center ESP-WIFI-MESH System Events Delivery The :cpp:type:`mesh_event_id_t` defines all possible ESP-WIFI-MESH events and can indicate events such as the connection/disconnection of parent/child. Before ESP-WIFI-MESH events can be used, the application must register a **Mesh Events handler** via :cpp:func:`esp_event_handler_register` to the default event task. The Mesh Events handler that is registered contain handlers for each ESP-WIFI-MESH event relevant to the application. Typical use cases of mesh events include using events such as :cpp:enumerator:`MESH_EVENT_PARENT_CONNECTED` and :cpp:enumerator:`MESH_EVENT_CHILD_CONNECTED` to indicate when a node can begin transmitting data upstream and downstream respectively.
53
Likewise, :cpp:enumerator:`IP_EVENT_STA_GOT_IP` and :cpp:enumerator:`IP_EVENT_STA_LOST_IP` can be used to indicate when the root node can and cannot transmit data to the external IP network. .. warning:: When using ESP-WIFI-MESH under self-organized mode, users must ensure that no calls to Wi-Fi API are made. This is due to the fact that the self-organizing mode will internally make Wi-Fi API calls to connect/disconnect/scan etc. **Any Wi-Fi calls from the application (including calls from callbacks and handlers of Wi-Fi events) may interfere with ESP-WIFI-MESH's self-organizing behavior**. Therefore, users should not call Wi-Fi APIs after :cpp:func:`esp_mesh_start` is called, and before :cpp:func:`esp_mesh_stop` is called. LwIP & ESP-WIFI-MESH The application can access the ESP-WIFI-MESH stack directly without having to go through the LwIP stack. The LwIP stack is only required by the root node to transmit/receive data to/from an external IP network. However, since every node can potentially become the root node (due to automatic root node selection), each node must still initialize the LwIP stack.
53
**Each node that could become root is required to initialize LwIP by calling** :cpp:func:`esp_netif_init`. In order to prevent non-root node access to LwIP, the application should not create or register any network interfaces using esp_netif APIs. ESP-WIFI-MESH requires a root node to be connected with a router. Therefore, in the event that a node becomes the root, **the corresponding handler must start the DHCP client service and immediately obtain an IP address**. Doing so will allow other nodes to begin transmitting/receiving packets to/from the external IP network. However, this step is unnecessary if static IP settings are used. .. Writing a Mesh Application .. _mesh-writing-mesh-application: Writing an ESP-WIFI-MESH Application The prerequisites for starting ESP-WIFI-MESH is to initialize LwIP and Wi-Fi, The following code snippet demonstrates the necessary prerequisite steps before ESP-WIFI-MESH itself can be initialized. .. code-block:: c ESP_ERROR_CHECK(esp_netif_init()); /* event initialization */ ESP_ERROR_CHECK(esp_event_loop_create_default()); /* Wi-Fi initialization */ wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&config)); /* register IP events handler */ 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()); After initializing LwIP and Wi-Fi, the process of getting an ESP-WIFI-MESH network up and running can be summarized into the following three steps: .
53
. _mesh-initialize-mesh: Initialize Mesh The following code snippet demonstrates how to initialize ESP-WIFI-MESH .. code-block:: c /* mesh initialization */ ESP_ERROR_CHECK(esp_mesh_init()); /* register mesh events handler */ ESP_ERROR_CHECK(esp_event_handler_register(MESH_EVENT, ESP_EVENT_ANY_ID, &mesh_event_handler, NULL)); .. _mesh-configuring-mesh: Configuring an ESP-WIFI-MESH Network .. todo - Add note about unified configuration ESP-WIFI-MESH is configured via :cpp:func:`esp_mesh_set_config` which receives its arguments using the :cpp:type:`mesh_cfg_t` structure. The structure contains the following parameters used to configure ESP-WIFI-MESH: .. list-table:: :header-rows: 1 :widths: 15 25 - Description - Range from 1 to 14 - ID of ESP-WIFI-MESH Network, see :cpp:type:`mesh_addr_t` - Router Configuration, see :cpp:type:`mesh_router_t` - Mesh AP Configuration, see :cpp:type:`mesh_ap_cfg_t` - Crypto Functions for Mesh IE, see :cpp:type:`mesh_crypto_funcs_t` The following code snippet demonstrates how to configure ESP-WIFI-MESH.
53
.. code-block:: c /* Enable the Mesh IE encryption by default */ mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT(); /* mesh ID */ memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6); /* channel (must match the router's channel) */ cfg.channel = CONFIG_MESH_CHANNEL; /* router */ 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-mesh: Start Mesh The following code snippet demonstrates how to start ESP-WIFI-MESH. .. code-block:: c /* mesh start */ ESP_ERROR_CHECK(esp_mesh_start()); After starting ESP-WIFI-MESH, the application should check for ESP-WIFI-MESH events to determine when it has connected to the network.
53
After connecting, the application can start transmitting and receiving packets over the ESP-WIFI-MESH network using :cpp:func:`esp_mesh_send` and :cpp:func:`esp_mesh_recv`. .. ESP-WIFI-MESH Application Examples .. _mesh-self-organized-behavior: Self-Organized Networking Self-organized networking is a feature of ESP-WIFI-MESH where nodes can autonomously scan/select/connect/reconnect to other nodes and routers. This feature allows an ESP-WIFI-MESH network to operate with high degree of autonomy by making the network robust to dynamic network topologies and conditions. With self-organized networking enabled, nodes in an ESP-WIFI-MESH network are able to carry out the following actions without autonomously: - Selection or election of the root node (see **Automatic Root Node Selection** in :ref:`mesh-building-a-network`) - Selection of a preferred parent node (see **Parent Node Selection** in :ref:`mesh-building-a-network`) - Automatic reconnection upon detecting a disconnection (see **Intermediate Parent Node Failure** in :ref:`mesh-managing-a-network`) When self-organized networking is enabled, the ESP-WIFI-MESH stack will internally make calls to Wi-Fi APIs.
53
Therefore, **the application layer should not make any calls to Wi-Fi APIs whilst self-organized networking is enabled as doing so would risk interfering with ESP-WIFI-MESH**. Toggling Self-Organized Networking Self-organized networking can be enabled or disabled by the application at runtime by calling the :cpp:func:`esp_mesh_set_self_organized` function. The function has the two following parameters: - ``bool enable`` specifies whether to enable or disable self-organized networking. - ``bool select_parent`` specifies whether a new parent node should be selected when enabling self-organized networking. Selecting a new parent has different effects depending the node type and the node's current state. This parameter is unused when disabling self-organized networking. Disabling Self-Organized Networking """"""""""""""""""""""""""""""""""" The following code snippet demonstrates how to disable self-organized networking. .. code-block:: c //Disable self-organized networking esp_mesh_set_self_organized(false, false); ESP-WIFI-MESH will attempt to maintain the node's current Wi-Fi state when disabling self-organized networking.
53
- If the node was previously connected to other nodes, it will remain connected. - If the node was previously disconnected and was scanning for a parent node or router, it will stop scanning. - If the node was previously attempting to reconnect to a parent node or router, it will stop reconnecting. Enabling Self-Organized Networking """""""""""""""""""""""""""""""""" ESP-WIFI-MESH will attempt to maintain the node's current Wi-Fi state when enabling self-organized networking. However, depending on the node type and whether a new parent is selected, the Wi-Fi state of the node can change. The following table shows effects of enabling self-organized networking. ++++ | Select Parent | Is Root Node | Effects | ++++ | N | N | - Nodes already connected to a parent node will remain connected. | | | | - Nodes previously scanning for a parent nodes will stop scanning.
53
Call :cpp:func:`esp_mesh_connect` to restart. | | +++ | | Y | - A root node already connected to router will stay connected. | | | | - A root node disconnected from router will need to call :cpp:func:`esp_mesh_connect` to reconnect. | ++++ | Y | N | - Nodes without a parent node will automatically select a preferred parent and connect. | | | | - Nodes already connected to a parent node will disconnect, reselect a preferred parent node, and connect. | | +++ | | Y | - For a root node to connect to a parent node, it must give up it's role as root. Therefore, a root node will | | | | disconnect from the router and all child nodes, select a preferred parent node, and connect. | ++++ The following code snipping demonstrates how to enable self-organized networking.
53
.. code-block:: c //Enable self-organized networking and select a new parent esp_mesh_set_self_organized(true, true); ... //Enable self-organized networking and manually reconnect esp_mesh_set_self_organized(true, false); esp_mesh_connect(); Calling Wi-Fi API There can be instances in which an application may want to directly call Wi-Fi API whilst using ESP-WIFI-MESH. For example, an application may want to manually scan for neighboring APs. However, **self-organized networking must be disabled before the application calls any Wi-Fi APIs**. This will prevent the ESP-WIFI-MESH stack from attempting to call any Wi-Fi APIs and potentially interfering with the application's calls. Therefore, application calls to Wi-Fi APIs should be placed in between calls of :cpp:func:`esp_mesh_set_self_organized` which disable and enable self-organized networking. The following code snippet demonstrates how an application can safely call :cpp:func:`esp_wifi_scan_start` whilst using ESP-WIFI-MESH.
53
.. code-block:: c //Disable self-organized networking esp_mesh_set_self_organized(0, 0); //Stop any scans already in progress esp_wifi_scan_stop(); //Manually start scan. Will automatically stop when run to completion esp_wifi_scan_start(); //Process scan results ... //Re-enable self-organized networking if still connected esp_mesh_set_self_organized(1, 0); ... //Re-enable self-organized networking if non-root and disconnected esp_mesh_set_self_organized(1, 1); ... //Re-enable self-organized networking if root and disconnected esp_mesh_set_self_organized(1, 0); //Do not select new parent esp_mesh_connect(); //Manually reconnect to router .. ESP-WIFI-MESH Application Examples .. _mesh-application-examples: Application Examples ESP-IDF contains these ESP-WIFI-MESH example projects: :example:`The Internal Communication Example ` demonstrates how to set up a ESP-WIFI-MESH network and have the root node send a data packet to every node within the network.
53
:example:`The Manual Networking Example ` demonstrates how to use ESP-WIFI-MESH without the self-organizing features. This example shows how to program a node to manually scan for a list of potential parent nodes and select a parent node based on custom criteria. .. ESP-WIFI-MESH API Reference .. _mesh-api-reference: API Reference .. include-build-file:: inc/esp_mesh.inc
53
Wi-Fi Aware\ :sup:`TM` (NAN) Wi-Fi Aware\ :sup:`TM` or NAN (Neighbor Awareness Networking) is a protocol that allows Wi-Fi devices to discover services in their proximity. Typically, location-based services are based on querying servers for information about the environment and the location knowledge is based on GPS or other location reckoning techniques. However, NAN does not require real-time connection to servers, GPS or other geo-location, but instead uses direct device-to-device Wi-Fi to discover and exchange information. NAN scales effectively in dense Wi-Fi environments and complements the connectivity of Wi-Fi by providing information about people and services in the proximity. Multiple NAN devices which are in the vicinity form a NAN cluster which allows them to communicate with each other. Devices within a NAN cluster can advertise (Publish method) or look for (Subscribe method) services using NAN Service Discovery protocols. Matching of services is done by service name, once a match is found, a device can either send a message or establish an IPv6 Datapath with the peer.
54
{IDF_TARGET_NAME} supports Wi-Fi Aware in standalone mode with support for both Service Discovery and Datapath. Wi-Fi Aware is still an evolving protocol. Please refer to Wi-Fi Alliance's official page on `Wi-Fi Aware `_ for more information. Many Android smartphones with Android 8 or higher support Wi-Fi Aware. Refer to Android's developer guide on Wi-Fi Aware `Wi-Fi Aware `_ for more information. Application Example A pair of examples for a Publisher-Subscriber use case: :example:`wifi/wifi_aware/nan_publisher` and :example:`wifi/wifi_aware/nan_subscriber`. A user interactive console example to explore full functionality of Wi-Fi Aware: :example:`wifi/wifi_aware/nan_console`. Please check the `README` for more details in respective example directories. API Reference .. include-build-file:: inc/esp_nan.inc
54
ESP-NETIF The purpose of the ESP-NETIF library is twofold: - It provides an abstraction layer for the application on top of the TCP/IP stack. This allows applications to choose between IP stacks in the future. - The APIs it provides are thread-safe, even if the underlying TCP/IP stack APIs are not. ESP-IDF currently implements ESP-NETIF for the lwIP TCP/IP stack only. However, the adapter itself is TCP/IP implementation-agnostic and allows different implementations. It is also possible to use a custom TCP/IP stack with ESP-IDF, provided it implements BSD API. For more information on building ESP-IDF without lwIP, please refer to :idf_file:`components/esp_netif_stack/README.md`. Some ESP-NETIF API functions are intended to be called by application code, for example, to get or set interface IP addresses, and configure DHCP. Other functions are intended for internal ESP-IDF use by the network driver layer. In many cases, applications do not need to call ESP-NETIF APIs directly as they are called by the default network event handlers.
55
.. _esp-netif structure: ESP-NETIF Architecture .. code-block:: text | (A) USER CODE | | Apps | .................| init settings events | . ++ . . | * . . | * + ++ * ++ | | new/config get/set/apps | * | init | | | |...*.....| Apps (DHCP, SNTP) | | || * | | init | | |**** | | start || event handler || DHCP | stop | | | | | | || | | | | | | NETIF | +| | | ++ | | glue||---| esp_netif_receive |-->| netif_input | | | | | | | + + | | |.
55
..--| esp_vfs_l2tap_eth_filter |>---| read | | | | | | (E) | ++ ++ USER CODE ESP-NETIF L2 TAP Data and Event Flow in the Diagram ESP-NETIF Interaction A) User Code, Boilerplate Overall application interaction with a specific IO driver for communication media and configured TCP/IP network stack is abstracted using ESP-NETIF APIs and is outlined as below: A) Initialization code 1) Initializes IO driver 2) Creates a new instance of ESP-NETIF and configure it with 3) Attaches the IO driver handle to the ESP-NETIF instance created in the above steps 4) Configures event handlers B) Interaction with network interfaces using ESP-NETIF API 1) Gets and sets TCP/IP-related parameters (DHCP, IP, etc) 2) Receives IP events (connect or disconnect) 3) Controls application lifecycle (set interface up or down) B) Communication Driver, IO Driver, and Media Driver Communication driver plays these two important roles in relation to ESP-NETIF: 1) Event handlers: Defines behavior patterns of interaction with ESP-NETIF (e.
55
g., ethernet link-up -> turn netif on) 2) Glue IO layer: Adapts the input or output functions to use ESP-NETIF transmit, receive, and free receive buffer C) ESP-NETIF ESP-NETIF serves as an intermediary between an IO driver and a network stack, connecting the packet data path between the two. It provides a set of interfaces for attaching a driver to an ESP-NETIF object at runtime and configures a network stack during compiling. Additionally, a set of APIs is provided to control the network interface lifecycle and its TCP/IP properties. As an overview, the ESP-NETIF public interface can be divided into six groups: 1) Initialization APIs (to create and configure ESP-NETIF instance) 2) Input or Output API (for passing data between IO driver and network stack) 3) Event or Action API 4) Setters and Getters API for basic network interface properties 5) Network stack abstraction API: enabling user interaction with TCP/IP stack 6) Driver conversion utilities API D) Network Stack The network stack has no public interaction with application code with regard to public interfaces and shall be fully abstracted by ESP-NETIF API.
55
E) ESP-NETIF L2 TAP Interface The ESP-NETIF L2 TAP interface is a mechanism in ESP-IDF used to access Data Link Layer (L2 per OSI/ISO) for frame reception and transmission from the user application. Its typical usage in the embedded world might be the implementation of non-IP-related protocols, e.g., PTP, Wake on LAN. Note that only Ethernet (IEEE 802.3) is currently supported. From a user perspective, the ESP-NETIF L2 TAP interface is accessed using file descriptors of VFS, which provides file-like interfacing (using functions like ``open()``, ``read()``, ``write()``, etc). To learn more, refer to :doc:`/api-reference/storage/vfs`. There is only one ESP-NETIF L2 TAP interface device (path name) available. However multiple file descriptors with different configurations can be opened at a time since the ESP-NETIF L2 TAP interface can be understood as a generic entry point to the Layer 2 infrastructure. What is important is then the specific configuration of the particular file descriptor.
55
It can be configured to give access to a specific Network Interface identified by ``if_key`` (e.g., `ETH_DEF`) and to filter only specific frames based on their type (e.g., Ethernet type in the case of IEEE 802.3). Filtering only specific frames is crucial since the ESP-NETIF L2 TAP needs to exist along with the IP stack and so the IP-related traffic (IP, ARP, etc.) should not be passed directly to the user application. Even though this option is still configurable, it is not recommended in standard use cases. Filtering is also advantageous from the perspective of the user's application, as it only gets access to the frame types it is interested in, and the remaining traffic is either passed to other L2 TAP file descriptors or to the IP stack. ESP-NETIF L2 TAP Interface Usage Manual Initialization To be able to use the ESP-NETIF L2 TAP interface, it needs to be enabled in Kconfig by :ref:`CONFIG_ESP_NETIF_L2_TAP` first and then registered by :cpp:func:`esp_vfs_l2tap_intf_register()` prior usage of any VFS function.
55
``open()`` Once the ESP-NETIF L2 TAP is registered, it can be opened at path name "/dev/net/tap". The same path name can be opened multiple times up to :ref:`CONFIG_ESP_NETIF_L2_TAP_MAX_FDS` and multiple file descriptors with a different configuration may access the Data Link Layer frames. The ESP-NETIF L2 TAP can be opened with the ``O_NONBLOCK`` file status flag to make sure the ``read()`` does not block. Note that the ``write()`` may block in the current implementation when accessing a Network interface since it is a shared resource among multiple ESP-NETIF L2 TAP file descriptors and IP stack, and there is currently no queuing mechanism deployed. The file status flag can be retrieved and modified using ``fcntl()``. On success, ``open()`` returns the new file descriptor (a nonnegative integer). On error, -1 is returned, and ``errno`` is set to indicate the error. ``ioctl()`` The newly opened ESP-NETIF L2 TAP file descriptor needs to be configured prior to its usage since it is not bounded to any specific Network Interface and no frame type filter is configured.
55
The following configuration options are available to do so: All above-set configuration options have a getter counterpart option to read the current settings. .. warning:: The file descriptor needs to be firstly bounded to a specific Network Interface by ``L2TAP_S_INTF_DEVICE`` or ``L2TAP_S_DEVICE_DRV_HNDL`` to make ``L2TAP_S_RCV_FILTER`` option available. .. note:: VLAN-tagged frames are currently not recognized. If the user needs to process VLAN-tagged frames, they need a set filter to be equal to the VLAN tag (i.e., 0x8100 or 0x88A8) and process the VLAN-tagged frames in the user application. .. note:: ``L2TAP_S_DEVICE_DRV_HNDL`` is particularly useful when the user's application does not require the usage of an IP stack and so ESP-NETIF is not required to be initialized too. As a result, Network Interface cannot be identified by its ``if_key`` and hence it needs to be identified directly by its IO Driver handle. | On success, ``ioctl()`` returns 0. On error, -1 is returned, and ``errno`` is set to indicate the error.
55
| * EBADF - not a valid file descriptor. | * EACCES - options change is denied in this state (e.g., file descriptor has not been bounded to Network interface yet). | * EINVAL - invalid configuration argument. Ethernet type filter is already used by other file descriptors on that same Network interface. | * ENODEV - no such Network Interface which is tried to be assigned to the file descriptor exists. | * ENOSYS - unsupported operation, passed configuration option does not exist. ``fcntl()`` ``fcntl()`` is used to manipulate with properties of opened ESP-NETIF L2 TAP file descriptor. The following commands manipulate the status flags associated with the file descriptor: | On success, ``ioctl()`` returns 0. On error, -1 is returned, and ``errno`` is set to indicate the error. | * EBADF - not a valid file descriptor. | * ENOSYS - unsupported command. ``read()`` Opened and configured ESP-NETIF L2 TAP file descriptor can be accessed by ``read()`` to get inbound frames. The read operation can be either blocking or non-blocking based on the actual state of the ``O_NONBLOCK`` file status flag.
55
When the file status flag is set to blocking, the read operation waits until a frame is received and the context is switched to other tasks. When the file status flag is set to non-blocking, the read operation returns immediately. In such case, either a frame is returned if it was already queued or the function indicates the queue is empty. The number of queued frames associated with one file descriptor is limited by :ref:`CONFIG_ESP_NETIF_L2_TAP_RX_QUEUE_SIZE` Kconfig option. Once the number of queued frames reached a configured threshold, the newly arrived frames are dropped until the queue has enough room to accept incoming traffic (Tail Drop queue management). | On success, ``read()`` returns the number of bytes read. Zero is returned when the size of the destination buffer is 0. On error, -1 is returned, and ``errno`` is set to indicate the error. | * EBADF - not a valid file descriptor. | * EAGAIN - the file descriptor has been marked non-blocking (``O_NONBLOCK``), and the read would block.
55
``write()`` A raw Data Link Layer frame can be sent to Network Interface via opened and configured ESP-NETIF L2 TAP file descriptor. The user's application is responsible to construct the whole frame except for fields which are added automatically by the physical interface device. The following fields need to be constructed by the user's application in case of an Ethernet link: source/destination MAC addresses, Ethernet type, actual protocol header, and user data. The length of these fields is as follows: .. list-table:: :header-rows: 1 :widths: 20 20 20 30 :align: center - Source MAC - Type/Length - Payload (protocol header/data) - 6 B - 2 B - 0-1486 B In other words, there is no additional frame processing performed by the ESP-NETIF L2 TAP interface. It only checks the Ethernet type of the frame is the same as the filter configured in the file descriptor. If the Ethernet type is different, an error is returned and the frame is not sent.
55
Note that the ``write()`` may block in the current implementation when accessing a Network interface since it is a shared resource among multiple ESP-NETIF L2 TAP file descriptors and IP stack, and there is currently no queuing mechanism deployed. | On success, ``write()`` returns the number of bytes written. Zero is returned when the size of the input buffer is 0. On error, -1 is returned, and ``errno`` is set to indicate the error. | * EBADF - not a valid file descriptor. | * EBADMSG - The Ethernet type of the frame is different from the file descriptor configured filter. | * EIO - Network interface not available or busy. ``close()`` Opened ESP-NETIF L2 TAP file descriptor can be closed by the ``close()`` to free its allocated resources. The ESP-NETIF L2 TAP implementation of ``close()`` may block. On the other hand, it is thread-safe and can be called from a different task than the file descriptor is actually used. If such a situation occurs and one task is blocked in the I/O operation and another task tries to close the file descriptor, the first task is unblocked.
55
The first's task read operation then ends with an error. | On success, ``close()`` returns zero. On error, -1 is returned, and ``errno`` is set to indicate the error. | * EBADF - not a valid file descriptor. ``select()`` Select is used in a standard way, just :ref:`CONFIG_VFS_SUPPORT_SELECT` needs to be enabled to make the ``select()`` function available. .. _esp_netif-sntp-api: SNTP API You can find a brief introduction to SNTP in general, its initialization code, and basic modes in Section :ref:`system-time-sntp-sync` in :doc:`System Time `. This section provides more details about specific use cases of the SNTP service, with statically configured servers, or use the DHCP-provided servers, or both. The workflow is usually very simple: 1) Initialize and configure the service using :cpp:func:`esp_netif_sntp_init()`. This operations can only be called once (unless the SNTP service has been destroyed by :cpp:func:`esp_netif_sntp_deinit()`) 2) Start the service via :cpp:func:`esp_netif_sntp_start()`.
55
This step is not needed if we auto-started the service in the previous step (default). It is useful to start the service explicitly after connecting if we want to use the DHCP-obtained NTP servers. Please note, this option needs to be enabled before connecting, but the SNTP service should be started after. 3) Wait for the system time to synchronize using :cpp:func:`esp_netif_sntp_sync_wait()` (only if needed). 4) Stop and destroy the service using :cpp:func:`esp_netif_sntp_deinit()`. Basic Mode with Statically Defined Server(s) Initialize the module with the default configuration after connecting to the network. Note that it is possible to provide multiple NTP servers in the configuration struct: .. code-block:: c esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(2, ESP_SNTP_SERVER_LIST("time.windows.com", "pool.ntp.org" ) ); esp_netif_sntp_init(&config); .. note:: If we want to configure multiple SNTP servers, we have to update the lwIP configuration :ref:`CONFIG_LWIP_SNTP_MAX_SERVERS`.
55
Use DHCP-Obtained SNTP Server(s) First of all, we have to enable the lwIP configuration option :ref:`CONFIG_LWIP_DHCP_GET_NTP_SRV`. Then we have to initialize the SNTP module with the DHCP option and without the NTP server: .. code-block:: c esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(0, {} ); config.start = false; // start the SNTP service explicitly config.server_from_dhcp = true; // accept the NTP offer from the DHCP server esp_netif_sntp_init(&config); Then, once we are connected, we could start the service using: .. code-block:: c esp_netif_sntp_start(); .. note:: It is also possible to start the service during initialization (default ``config.start=true``). This would likely to cause the initial SNTP request to fail (since we are not connected yet) and lead to some back-off time for subsequent requests. Use Both Static and Dynamic Servers Very similar to the scenario above (DHCP provided SNTP server), but in this configuration, we need to make sure that the static server configuration is refreshed when obtaining NTP servers by DHCP.
55
The underlying lwIP code cleans up the rest of the list of NTP servers when the DHCP-provided information gets accepted. Thus the ESP-NETIF SNTP module saves the statically configured server(s) and reconfigures them after obtaining a DHCP lease. The typical configuration now looks as per below, providing the specific ``IP_EVENT`` to update the config and index of the first server to reconfigure (for example setting ``config.index_of_first_server=1`` would keep the DHCP provided server at index 0, and the statically configured server at index 1). .. code-block:: c esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org"); config.start = false; // start the SNTP service explicitly (after connecting) config.server_from_dhcp = true; // accept the NTP offers from DHCP server config.renew_servers_after_new_IP = true; // let esp-netif update the configured SNTP server(s) after receiving the DHCP lease config.index_of_first_server = 1; // updates from server num 1, leaving server 0 (from DHCP) intact config.
55
ip_event_to_renew = IP_EVENT_STA_GOT_IP; // IP event on which we refresh the configuration Then we start the service normally with :cpp:func:`esp_netif_sntp_start()`. ESP-NETIF Programmer's Manual Please refer to the following example to understand the initialization process of the default interface: .. only:: SOC_WIFI_SUPPORTED - Wi-Fi Station: :example_file:`wifi/getting_started/station/main/station_example_main.c` - Ethernet: :example_file:`ethernet/basic/main/ethernet_example_main.c` - L2 TAP: :example_file:`protocols/l2tap/main/l2tap_main.c` .. only:: CONFIG_ESP_WIFI_SOFTAP_SUPPORT - Wi-Fi Access Point: :example_file:`wifi/getting_started/softAP/main/softap_example_main.c` For more specific cases, please consult this guide: :doc:`/api-reference/network/esp_netif_driver`. .. only:: SOC_WIFI_SUPPORTED Wi-Fi Default Initialization The initialization code as well as registering event handlers for default interfaces, such as softAP and station, are provided in separate APIs to facilitate simple startup code for most applications: .
55
. only:: CONFIG_ESP_WIFI_SOFTAP_SUPPORT Please note that these functions return the ``esp_netif`` handle, i.e., a pointer to a network interface object allocated and configured with default settings, as a consequence, which means that: .. only:: CONFIG_ESP_WIFI_SOFTAP_SUPPORT API Reference .. include-build-file:: inc/esp_netif.inc .. include-build-file:: inc/esp_netif_sntp.inc .. include-build-file:: inc/esp_netif_types.inc .. include-build-file:: inc/esp_netif_ip_addr.inc .. include-build-file:: inc/esp_vfs_l2tap.inc .. only:: SOC_WIFI_SUPPORTED Wi-Fi Default API Reference .. include-build-file:: inc/esp_wifi_default.inc
55
Thread Introduction `Thread `_ is an IP-based mesh networking protocol. It is based on the 802.15.4 physical and MAC layer. Application Examples The :example:`openthread` directory of ESP-IDF examples contains the following applications: - The OpenThread interactive shell :example:`openthread/ot_cli` - The Thread Border Router :example:`openthread/ot_br` - The Thread Radio Co-Processor :example:`openthread/ot_rcp` API Reference For manipulating the Thread network, the OpenThread API shall be used. The OpenThread API docs can be found at the `OpenThread API docs `_. ESP-IDF provides extra APIs for launching and managing the OpenThread stack, binding to network interfaces and border routing features. .. include-build-file:: inc/esp_openthread.inc .. include-build-file:: inc/esp_openthread_types.inc .. include-build-file:: inc/esp_openthread_lock.inc .. include-build-file:: inc/esp_openthread_netif_glue.inc .. include-build-file:: inc/esp_openthread_border_router.inc
56
ESP-NETIF Custom I/O Driver This section outlines implementing a new I/O driver with ESP-NETIF connection capabilities. By convention, the I/O driver has to register itself as an ESP-NETIF driver, and thus holds a dependency on ESP-NETIF component and is responsible for providing data path functions, post-attach callback and in most cases, also default event handlers to define network interface actions based on driver's lifecycle transitions. Packet Input/Output According to the diagram shown in the :ref:`esp-netif structure` part, the following three API functions for the packet data path must be defined for connecting with ESP-NETIF: The first two functions for transmitting and freeing the rx buffer are provided as callbacks, i.e., they get called from ESP-NETIF (and its underlying TCP/IP stack) and I/O driver provides their implementation. The receiving function on the other hand gets called from the I/O driver, so that the driver's code simply calls :cpp:func:`esp_netif_receive()` on a new data received event.
57
Post Attach Callback A final part of the network interface initialization consists of attaching the ESP-NETIF instance to the I/O driver, by means of calling the following API: .. code:: c esp_err_t esp_netif_attach(esp_netif_t *esp_netif, esp_netif_iodriver_handle driver_handle); It is assumed that the ``esp_netif_iodriver_handle`` is a pointer to driver's object, a struct derived from ``struct esp_netif_driver_base_s``, so that the first member of I/O driver structure must be this base structure with pointers to: As a result, the I/O driver has to create an instance of the struct per below: .. code:: c typedef struct my_netif_driver_s { esp_netif_driver_base_t base; /*!driver_impl }; driver->base.netif = esp_netif; ESP_ERROR_CHECK(esp_netif_set_driver_config(esp_netif, &driver_ifconfig)); my_driver_start(driver->driver_impl); return ESP_OK; } Default Handlers I/O drivers also typically provide default definitions of lifecycle behavior of related network interfaces based on state transitions of I/O drivers.
57
For example *driver start* ``->`` *network start*, etc. An example of such a default handler is provided below: .. code:: c esp_err_t my_driver_netif_set_default_handlers(my_netif_driver_t *driver, esp_netif_t * esp_netif) { driver_set_event_handler(driver->driver_impl, esp_netif_action_start, MY_DRV_EVENT_START, esp_netif); driver_set_event_handler(driver->driver_impl, esp_netif_action_stop, MY_DRV_EVENT_STOP, esp_netif); return ESP_OK; } Network Stack Connection The packet data path functions for transmitting and freeing the rx buffer (defined in the I/O driver) are called from the ESP-NETIF, specifically from its TCP/IP stack connecting layer. Note that ESP-IDF provides several network stack configurations for the most common network interfaces, such as for the Wi-Fi station or Ethernet. These configurations are defined in :component_file:`esp_netif/include/esp_netif_defaults.h` and should be sufficient for most network drivers. In rare cases, expert users might want to define custom lwIP based interface layers; it is possible, but an explicit dependency to lwIP needs to be set.
57
The following API reference outlines these network stack interaction with the ESP-NETIF: .. include-build-file:: inc/esp_netif_net_stack.inc
57
Provisioning API .. toctree:: :maxdepth: 1 protocomm :SOC_WIFI_SUPPORTED: provisioning :SOC_WIFI_SUPPORTED: wifi_provisioning .. only:: SOC_WIFI_SUPPORTED Code examples for above API are provided in the :example:`provisioning` directory of ESP-IDF examples. .. toctree:: :maxdepth: 1 ../network/esp_smartconfig Code example for above API is provided in :example:`wifi/smart_config`. .. toctree:: :maxdepth: 1 ../network/esp_dpp Code example for above API is provided in :example:`wifi/wifi_easy_connect/dpp-enrollee`.
58
Wi-Fi Provisioning Overview This component provides APIs that control the Wi-Fi provisioning service for receiving and configuring Wi-Fi credentials over SoftAP or Bluetooth LE transport via secure :doc:`protocomm` sessions. The set of ``wifi_prov_mgr_`` APIs help quickly implement a provisioning service that has necessary features with minimal amount of code and sufficient flexibility. .. _wifi-prov-mgr-init: Initialization :cpp:func:`wifi_prov_mgr_init()` is called to configure and initialize the provisioning manager, and thus must be called prior to invoking any other ``wifi_prov_mgr_`` APIs. Note that the manager relies on other components of ESP-IDF, namely NVS, TCP/IP, Event Loop and Wi-Fi, and optionally mDNS, hence these components must be initialized beforehand. The manager can be de-initialized at any moment by making a call to :cpp:func:`wifi_prov_mgr_deinit()`. .. code-block:: c wifi_prov_mgr_config_t config = { .scheme = wifi_prov_scheme_ble, .
59
scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM }; ESP_ERROR_CHECK( wifi_prov_mgr_init(config) ); The configuration structure :cpp:type:`wifi_prov_mgr_config_t` has a few fields to specify the desired behavior of the manager: .. code-block:: c static void event_handler(void* arg, esp_event_base_t event_base, int event_id, void* event_data) { if (event_base == WIFI_PROV_EVENT) { switch (event_id) { case WIFI_PROV_START: ESP_LOGI(TAG, "Provisioning started"); break; case WIFI_PROV_CRED_RECV: { wifi_sta_config_t *wifi_sta_cfg = (wifi_sta_config_t *)event_data; ESP_LOGI(TAG, "Received Wi-Fi credentials" "\n\tSSID : %s\n\tPassword : %s", (const char *) wifi_sta_cfg->ssid, (const char *) wifi_sta_cfg->password); break; } case WIFI_PROV_CRED_FAIL: { wifi_prov_sta_fail_reason_t *reason = (wifi_prov_sta_fail_reason_t *)event_data; ESP_LOGE(TAG, "Provisioning failed!
59
\n\tReason : %s" "\n\tPlease reset to factory and retry provisioning", (*reason == WIFI_PROV_STA_AUTH_ERROR) ? "Wi-Fi station authentication failed" : "Wi-Fi access-point not found"); break; } case WIFI_PROV_CRED_SUCCESS: ESP_LOGI(TAG, "Provisioning successful"); break; case WIFI_PROV_END: /* De-initialize manager once provisioning is finished */ wifi_prov_mgr_deinit(); break; default: break; } } } The manager can be de-initialized at any moment by making a call to :cpp:func:`wifi_prov_mgr_deinit()`. .. _wifi-prov-check-state: Check the Provisioning State Whether the device is provisioned or not can be checked at runtime by calling :cpp:func:`wifi_prov_mgr_is_provisioned()`.
59
This internally checks if the Wi-Fi credentials are stored in NVS. Note that presently the manager does not have its own NVS namespace for storage of Wi-Fi credentials, instead it relies on the ``esp_wifi_`` APIs to set and get the credentials stored in NVS from the default location. If the provisioning state needs to be reset, any of the following approaches may be taken: .. code-block:: c bool provisioned = false; ESP_ERROR_CHECK( wifi_prov_mgr_is_provisioned(&provisioned) ); Start the Provisioning Service At the time of starting provisioning we need to specify a service name and the corresponding key, that is to say: Also, since internally the manager uses ``protocomm``, we have the option of choosing one of the security features provided by it: See :doc:`provisioning` for details about the security features. .. highlight:: c :: const char *service_name = "my_device"; const char *service_key = "password"; wifi_prov_security_t security = WIFI_PROV_SECURITY_1; const char *pop = "abcd1234"; ESP_ERROR_CHECK( wifi_prov_mgr_start_provisioning(security, pop, service_name, service_key) ); The provisioning service automatically finishes only if it receives valid Wi-Fi AP credentials followed by successful connection of device to the AP with IP obtained.
59
Regardless of that, the provisioning service can be stopped at any moment by making a call to :cpp:func:`wifi_prov_mgr_stop_provisioning()`. .. note:: If the device fails to connect with the provided credentials, it does not accept new credentials anymore, but the provisioning service keeps on running, only to convey failure to the client, until the device is restarted. Upon restart, the provisioning state turns out to be true this time, as credentials are found in NVS, but the device does fail again to connect with those same credentials, unless an AP with the matching credentials somehow does become available. This situation can be fixed by resetting the credentials in NVS or force starting the provisioning service. This has been explained above in :ref:`wifi-prov-check-state`. Waiting for Completion Typically, the main application waits for the provisioning to finish, then de-initializes the manager to free up resources, and finally starts executing its own logic. There are two ways for making this possible.
59
The simpler way is to use a blocking call to :cpp:func:`wifi_prov_mgr_wait()`. .. code-block:: c // Start provisioning service ESP_ERROR_CHECK( wifi_prov_mgr_start_provisioning(security, pop, service_name, service_key) ); // Wait for service to complete wifi_prov_mgr_wait(); // Finally de-initialize the manager wifi_prov_mgr_deinit(); The other way is to use the default event loop handler to catch ``WIFI_PROV_EVENT`` and call :cpp:func:`wifi_prov_mgr_deinit()` when event ID is ``WIFI_PROV_END``: .. code-block:: c static void event_handler(void* arg, esp_event_base_t event_base, int event_id, void* event_data) { if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_END) { /* De-initialize the manager once the provisioning is finished */ wifi_prov_mgr_deinit(); } } User Side Implementation When the service is started, the device to be provisioned is identified by the advertised service name, which, depending upon the selected transport, is either the Bluetooth LE device name or the SoftAP SSID.
59
When using SoftAP transport, for allowing service discovery, mDNS must be initialized before starting provisioning. In this case, the host name set by the main application is used, and the service type is internally set to ``_esp_wifi_prov``. When using Bluetooth LE transport, a custom 128-bit UUID should be set using :cpp:func:`wifi_prov_scheme_ble_set_service_uuid()`. This UUID is to be included in the Bluetooth LE advertisement and corresponds to the primary GATT service that provides provisioning endpoints as GATT characteristics. Each GATT characteristic is formed using the primary service UUID as the base, with different auto-assigned 12th and 13th bytes, presumably counting from the 0th byte. Since an endpoint characteristic UUID is auto-assigned, it should not be used to identify the endpoint. Instead, client-side applications should identify the endpoints by reading the User Characteristic Description (``0x2901``) descriptor for each characteristic, which contains the endpoint name of the characteristic.
59
For example, if the service UUID is set to ``55cc035e-fb27-4f80-be02-3c60828b7451``, each endpoint characteristic is assigned a UUID like ``55cc____-fb27-4f80-be02-3c60828b7451``, with unique values at the 12th and 13th bytes. Once connected to the device, the provisioning-related protocomm endpoints can be identified as follows: .. |br| raw:: html .. list-table:: Endpoints Provided by the Provisioning Service :widths: 35 35 30 :header-rows: 1 - URI, i.e., SoftAP |br| + HTTP Server + mDNS - Description - http://.local/prov-session - Security endpoint used for session establishment - http://wifi-prov.local/prov-scan - the endpoint used for starting Wi-Fi scan and receiving scan results - http://wifi-prov.local/prov-ctrl - the endpoint used for controlling Wi-Fi provisioning state - http://.local/prov-config - the endpoint used for configuring Wi-Fi credentials on device - http://.local/proto-ver - the endpoint for retrieving version info Immediately after connecting, the client application may fetch the version/capabilities information from the ``proto-ver`` endpoint.
59
All communications to this endpoint are unencrypted, hence necessary information, which may be relevant for deciding compatibility, can be retrieved before establishing a secure session. The response is in JSON format and looks like : ``prov: { ver: v1.1, cap: [no_pop] }, my_app: { ver: 1.345, cap: [cloud, local_ctrl] },....``. Here label ``prov`` provides provisioning service version ``ver`` and capabilities ``cap``. For now, only the ``no_pop`` capability is supported, which indicates that the service does not require proof of possession for authentication. Any application-related version or capabilities are given by other labels, e.g., ``my_app`` in this example. These additional fields are set using :cpp:func:`wifi_prov_mgr_set_app_info()`. User side applications need to implement the signature handshaking required for establishing and authenticating secure protocomm sessions as per the security scheme configured for use, which is not needed when the manager is configured to use protocomm security 0.
59
See :doc:`provisioning` for more details about the secure handshake and encryption used. Applications must use the ``.proto`` files found under :component:`protocomm/proto`, which define the Protobuf message structures supported by ``prov-session`` endpoint. Once a session is established, Wi-Fi credentials are configured using the following set of ``wifi_config`` commands, serialized as Protobuf messages with the corresponding ``.proto`` files that can be found under :component:`wifi_provisioning/proto`: After session establishment, the client can also request Wi-Fi scan results from the device. The results returned is a list of AP SSIDs, sorted in descending order of signal strength. This allows client applications to display APs nearby to the device at the time of provisioning, and users can select one of the SSIDs and provide the password which is then sent using the ``wifi_config`` commands described above. The ``wifi_scan`` endpoint supports the following protobuf commands : The client can also control the provisioning state of the device using ``wifi_ctrl`` endpoint.
59
The ``wifi_ctrl`` endpoint supports the following protobuf commands: Additional Endpoints In case users want to have some additional protocomm endpoints customized to their requirements, this is done in two steps. First is creation of an endpoint with a specific name, and the second step is the registration of a handler for this endpoint. See :doc:`protocomm` for the function signature of an endpoint handler. A custom endpoint must be created after initialization and before starting the provisioning service. Whereas, the protocomm handler is registered for this endpoint only after starting the provisioning service. Note that in the custom endpoint handler function, memory for the response of such protocomm endpoints should be allocated using heap as it gets freed by the protocomm layer once it has been sent by the transport layer. .. code-block:: c wifi_prov_mgr_init(config); wifi_prov_mgr_endpoint_create("custom-endpoint"); wifi_prov_mgr_start_provisioning(security, pop, service_name, service_key); wifi_prov_mgr_endpoint_register("custom-endpoint", custom_ep_handler, custom_ep_data); When the provisioning service stops, the endpoint is unregistered automatically.
59
One can also choose to call :cpp:func:`wifi_prov_mgr_endpoint_unregister()` to manually deactivate an endpoint at runtime. This can also be used to deactivate the internal endpoints used by the provisioning service. When/How to Stop the Provisioning Service? The default behavior is that once the device successfully connects using the Wi-Fi credentials set by the ``apply_config`` command, the provisioning service stops, and Bluetooth LE or SoftAP turns off, automatically after responding to the next ``get_status`` command. If ``get_status`` command is not received by the device, the service stops after a 30 s timeout. On the other hand, if device is not able to connect using the provided Wi-Fi credentials, due to incorrect SSID or passphrase, the service keeps running, and ``get_status`` keeps responding with disconnected status and reason for disconnection. Any further attempts to provide another set of Wi-Fi credentials, are to be rejected. These credentials are preserved, unless the provisioning service is force started, or NVS erased.
59
If this default behavior is not desired, it can be disabled by calling :cpp:func:`wifi_prov_mgr_disable_auto_stop()`. Now the provisioning service stops only after an explicit call to :cpp:func:`wifi_prov_mgr_stop_provisioning()`, which returns immediately after scheduling a task for stopping the service. The service stops after a certain delay and ``WIFI_PROV_END`` event gets emitted. This delay is specified by the argument to :cpp:func:`wifi_prov_mgr_disable_auto_stop()`. The customized behavior is useful for applications which want the provisioning service to be stopped some time after the Wi-Fi connection is successfully established. For example, if the application requires the device to connect to some cloud service and obtain another set of credentials, and exchange these credentials over a custom protocomm endpoint, then after successfully doing so, stop the provisioning service by calling :cpp:func:`wifi_prov_mgr_stop_provisioning()` inside the protocomm handler itself. The right amount of delay ensures that the transport resources are freed only after the response from the protocomm handler reaches the client side application.
59
Application Examples For complete example implementation see :example:`provisioning/wifi_prov_mgr`. Provisioning Tools Provisioning applications are available for various platforms, along with source code: The phone applications offer simple UI and are thus more user centric, while the command-line application is useful as a debugging tool for developers. API Reference .. include-build-file:: inc/manager.inc .. include-build-file:: inc/scheme_ble.inc .. include-build-file:: inc/scheme_softap.inc .. include-build-file:: inc/scheme_console.inc .. include-build-file:: inc/wifi_config.inc
59
Protocol Communication Overview The Protocol Communication (protocomm) component manages secure sessions and provides the framework for multiple transports. The application can also use the protocomm layer directly to have application-specific extensions for the provisioning or non-provisioning use cases. Following features are available for provisioning: Protocomm internally uses protobuf (protocol buffers) for secure session establishment. Users can choose to implement their own security (even without using protobuf). Protocomm can also be used without any security layer. Protocomm provides the framework for various transports: .. list:: :SOC_BLE_SUPPORTED: - Bluetooth LE :SOC_WIFI_SUPPORTED: - Wi-Fi (SoftAP + HTTPD) - Console, in which case the handler invocation is automatically taken care of on the device side. See Transport Examples below for code snippets. Note that for protocomm_security1 and protocomm_security2, the client still needs to establish sessions by performing the two-way handshake.
60
.. only:: SOC_WIFI_SUPPORTED See :doc:`provisioning` for more details about the secure handshake logic. .. _enabling-protocomm-security-version: Enabling Protocomm Security Version The protocomm component provides a project configuration menu to enable/disable support of respective security versions. The respective configuration options are as follows: .. note:: Enabling multiple security versions at once offers the ability to control them dynamically but also increases the firmware size. .. only:: SOC_WIFI_SUPPORTED SoftAP + HTTP Transport Example with Security 2 For sample usage, see :component_file:`wifi_provisioning/src/scheme_softap.c`. .. highlight:: c :: /* The endpoint handler to be registered with protocomm. This simply echoes back the received data. */ esp_err_t echo_req_handler (uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) { /* Session ID may be used for persistence.
60
*/ printf("Session ID : %d", session_id); /* Echo back the received data. */ *outlen = inlen; /* Output the data length updated. */ *outbuf = malloc(inlen); /* This is to be deallocated outside. */ memcpy(*outbuf, inbuf, inlen); /* Private data that was passed at the time of endpoint creation. */ uint32_t *priv = (uint32_t *) priv_data; if (priv) { printf("Private data : %d", *priv); } return ESP_OK; } static const char sec2_salt[] = {0xf7, 0x5f, 0xe2, 0xbe, 0xba, 0x7c, 0x81, 0xcd}; static const char sec2_verifier[] = {0xbf, 0x86, 0xce, 0x63, 0x8a, 0xbb, 0x7e, 0x2f, 0x38, 0xa8, 0x19, 0x1b, 0x35, 0xc9, 0xe3, 0xbe, 0xc3, 0x2b, 0x45, 0xee, 0x10, 0x74, 0x22, 0x1a, 0x95, 0xbe, 0x62, 0xf7, 0x0c, 0x65, 0x83, 0x50, 0x08, 0xef, 0xaf, 0xa5, 0x94, 0x4b, 0xcb, 0xe1, 0xce, 0x59, 0x2a, 0xe8, 0x7b, 0x27, 0xc8, 0x72, 0x26, 0x71, 0xde, 0xb2, 0xf2, 0x80, 0x02, 0xdd, 0x11, 0xf0, 0x38, 0x0e, 0x95, 0x25, 0x00, 0xcf, 0xb3, 0x3f, 0xf0, 0x73, 0x2a, 0x25, 0x03, 0xe8, 0x51, 0x72, 0xef, 0x6d, 0x3e, 0x14, 0xb9, 0x2e, 0x9f, 0x2a, 0x90, 0x9e, 0x26, 0xb6, 0x3e, 0xc7, 0xe4, 0x9f, 0xe3, 0x20, 0xce, 0x28, 0x7c, 0xbf, 0x89, 0x50, 0xc9, 0xb6, 0xec, 0xdd, 0x81, 0x18, 0xf1, 0x1a, 0xd9, 0x7a, 0x21, 0x99, 0xf1, 0xee, 0x71, 0x2f, 0xcc, 0x93, 0x16, 0x34, 0x0c, 0x79, 0x46, 0x23, 0xe4, 0x32, 0xec, 0x2d, 0x9e, 0x18, 0xa6, 0xb9, 0xbb, 0x0a, 0xcf, 0xc4, 0xa8, 0x32, 0xc0, 0x1c, 0x32, 0xa3, 0x97, 0x66, 0xf8, 0x30, 0xb2, 0xda, 0xf9, 0x8d, 0xc3, 0x72, 0x72, 0x5f, 0xe5, 0xee, 0xc3, 0x5c, 0x24, 0xc8, 0xdd, 0x54, 0x49, 0xfc, 0x12, 0x91, 0x81, 0x9c, 0xc3, 0xac, 0x64, 0x5e, 0xd6, 0x41, 0x88, 0x2f, 0x23, 0x66, 0xc8, 0xac, 0xb0, 0x35, 0x0b, 0xf6, 0x9c, 0x88, 0x6f, 0xac, 0xe1, 0xf4, 0xca, 0xc9, 0x07, 0x04, 0x11, 0xda, 0x90, 0x42, 0xa9, 0xf1, 0x97, 0x3d, 0x94, 0x65, 0xe4, 0xfb, 0x52, 0x22, 0x3b, 0x7a, 0x7b, 0x9e, 0xe9, 0xee, 0x1c, 0x44, 0xd0, 0x73, 0x72, 0x2a, 0xca, 0x85, 0x19, 0x4a, 0x60, 0xce, 0x0a, 0xc8, 0x7d, 0x57, 0xa4, 0xf8, 0x77, 0x22, 0xc1, 0xa5, 0xfa, 0xfb, 0x7b, 0x91, 0x3b, 0xfe, 0x87, 0x5f, 0xfe, 0x05, 0xd2, 0xd6, 0xd3, 0x74, 0xe5, 0x2e, 0x68, 0x79, 0x34, 0x70, 0x40, 0x12, 0xa8, 0xe1, 0xb4, 0x6c, 0xaa, 0x46, 0x73, 0xcd, 0x8d, 0x17, 0x72, 0x67, 0x32, 0x42, 0xdc, 0x10, 0xd3, 0x71, 0x7e, 0x8b, 0x00, 0x46, 0x9b, 0x0a, 0xe9, 0xb4, 0x0f, 0xeb, 0x70, 0x52, 0xdd, 0x0a, 0x1c, 0x7e, 0x2e, 0xb0, 0x61, 0xa6, 0xe1, 0xa3, 0x34, 0x4b, 0x2a, 0x3c, 0xc4, 0x5d, 0x42, 0x05, 0x58, 0x25, 0xd3, 0xca, 0x96, 0x5c, 0xb9, 0x52, 0xf9, 0xe9, 0x80, 0x75, 0x3d, 0xc8, 0x9f, 0xc7, 0xb2, 0xaa, 0x95, 0x2e, 0x76, 0xb3, 0xe1, 0x48, 0xc1, 0x0a, 0xa1, 0x0a, 0xe8, 0xaf, 0x41, 0x28, 0xd2, 0x16, 0xe1, 0xa6, 0xd0, 0x73, 0x51, 0x73, 0x79, 0x98, 0xd9, 0xb9, 0x00, 0x50, 0xa2, 0x4d, 0x99, 0x18, 0x90, 0x70, 0x27, 0xe7, 0x8d, 0x56, 0x45, 0x34, 0x1f, 0xb9, 0x30, 0xda, 0xec, 0x4a, 0x08, 0x27, 0x9f, 0xfa, 0x59, 0x2e, 0x36, 0x77, 0x00, 0xe2, 0xb6, 0xeb, 0xd1, 0x56, 0x50, 0x8e}; /* The example function for launching a protocomm instance over HTTP.
60
*/ protocomm_t *start_pc() { protocomm_t *pc = protocomm_new(); /* Config for protocomm_httpd_start(). */ protocomm_httpd_config_t pc_config = { .data = { .config = PROTOCOMM_HTTPD_DEFAULT_CONFIG() } }; /* Start the protocomm server on top of HTTP. */ protocomm_httpd_start(pc, &pc_config); /* Create Security2 params object from salt and verifier. It must be valid throughout the scope of protocomm endpoint. This does not need to be static, i.e., could be dynamically allocated and freed at the time of endpoint removal. */ const static protocomm_security2_params_t sec2_params = { .salt = (const uint8_t *) salt, .salt_len = sizeof(salt), .verifier = (const uint8_t *) verifier, .verifier_len = sizeof(verifier), }; /* Set security for communication at the application level.
60
Just like for request handlers, setting security creates an endpoint and registers the handler provided by protocomm_security1. One can similarly use protocomm_security0. Only one type of security can be set for a protocomm instance at a time. */ protocomm_set_security(pc, "security_endpoint", &protocomm_security2, &sec2_params); /* Private data passed to the endpoint must be valid throughout the scope of protocomm endpoint. This need not be static, i.e., could be dynamically allocated and freed at the time of endpoint removal. */ static uint32_t priv_data = 1234; /* Add a new endpoint for the protocomm instance, identified by a unique name, and register a handler function along with the private data to be passed at the time of handler execution. Multiple endpoints can be added as long as they are identified by unique names. */ protocomm_add_endpoint(pc, "echo_req_endpoint", echo_req_handler, (void *) &priv_data); return pc; } /* The example function for stopping a protocomm instance.
60
*/ void stop_pc(protocomm_t *pc) { /* Remove the endpoint identified by its unique name. */ protocomm_remove_endpoint(pc, "echo_req_endpoint"); /* Remove the security endpoint identified by its name. */ protocomm_unset_security(pc, "security_endpoint"); /* Stop the HTTP server. */ protocomm_httpd_stop(pc); /* Delete, namely deallocate the protocomm instance. */ protocomm_delete(pc); } SoftAP + HTTP Transport Example with Security 1 For sample usage, see :component_file:`wifi_provisioning/src/scheme_softap.c`. .. highlight:: c :: /* The endpoint handler to be registered with protocomm. This simply echoes back the received data. */ esp_err_t echo_req_handler (uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) { /* Session ID may be used for persistence.
60
*/ printf("Session ID : %d", session_id); /* Echo back the received data. */ *outlen = inlen; /* Output the data length updated. */ *outbuf = malloc(inlen); /* This is to be deallocated outside. */ memcpy(*outbuf, inbuf, inlen); /* Private data that was passed at the time of endpoint creation. */ uint32_t *priv = (uint32_t *) priv_data; if (priv) { printf("Private data : %d", *priv); } return ESP_OK; } /* The example function for launching a protocomm instance over HTTP. */ protocomm_t *start_pc(const char *pop_string) { protocomm_t *pc = protocomm_new(); /* Config for protocomm_httpd_start(). */ protocomm_httpd_config_t pc_config = { .data = { .config = PROTOCOMM_HTTPD_DEFAULT_CONFIG() } }; /* Start the protocomm server on top of HTTP.
60
*/ protocomm_httpd_start(pc, &pc_config); /* Create security1 params object from pop_string. It must be valid throughout the scope of protocomm endpoint. This need not be static, i.e., could be dynamically allocated and freed at the time of endpoint removal. */ const static protocomm_security1_params_t sec1_params = { .data = (const uint8_t *) strdup(pop_string), .len = strlen(pop_string) }; /* Set security for communication at the application level. Just like for request handlers, setting security creates an endpoint and registers the handler provided by protocomm_security1. One can similarly use protocomm_security0. Only one type of security can be set for a protocomm instance at a time. */ protocomm_set_security(pc, "security_endpoint", &protocomm_security1, &sec1_params); /* Private data passed to the endpoint must be valid throughout the scope of protocomm endpoint.
60
This need not be static, i.e., could be dynamically allocated and freed at the time of endpoint removal. */ static uint32_t priv_data = 1234; /* Add a new endpoint for the protocomm instance identified by a unique name, and register a handler function along with the private data to be passed at the time of handler execution. Multiple endpoints can be added as long as they are identified by unique names. */ protocomm_add_endpoint(pc, "echo_req_endpoint", echo_req_handler, (void *) &priv_data); return pc; } /* The example function for stopping a protocomm instance. */ void stop_pc(protocomm_t *pc) { /* Remove the endpoint identified by its unique name. */ protocomm_remove_endpoint(pc, "echo_req_endpoint"); /* Remove the security endpoint identified by its name. */ protocomm_unset_security(pc, "security_endpoint"); /* Stop the HTTP server.
60
*/ protocomm_httpd_stop(pc); /* Delete, namely deallocate the protocomm instance. */ protocomm_delete(pc); } .. only:: SOC_BLE_SUPPORTED Bluetooth LE Transport Example with Security 0 For sample usage, see :component_file:`wifi_provisioning/src/scheme_ble.c`. .. highlight:: c :: /* The example function for launching a secure protocomm instance over Bluetooth LE. */ protocomm_t *start_pc() { protocomm_t *pc = protocomm_new(); /* Endpoint UUIDs */ protocomm_ble_name_uuid_t nu_lookup_table[] = { {"security_endpoint", 0xFF51}, {"echo_req_endpoint", 0xFF52} }; /* Config for protocomm_ble_start(). */ protocomm_ble_config_t config = { .service_uuid = { /* LSB MSB */ 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, }, .
60
nu_lookup_count = sizeof(nu_lookup_table)/sizeof(nu_lookup_table[0]), .nu_lookup = nu_lookup_table }; /* Start protocomm layer on top of Bluetooth LE. */ protocomm_ble_start(pc, &config); /* For protocomm_security0, Proof of Possession is not used, and can be kept NULL. */ protocomm_set_security(pc, "security_endpoint", &protocomm_security0, NULL); protocomm_add_endpoint(pc, "echo_req_endpoint", echo_req_handler, NULL); return pc; } /* The example function for stopping a protocomm instance. */ void stop_pc(protocomm_t *pc) { protocomm_remove_endpoint(pc, "echo_req_endpoint"); protocomm_unset_security(pc, "security_endpoint"); /* Stop the Bluetooth LE protocomm service. */ protocomm_ble_stop(pc); protocomm_delete(pc); } API Reference .. include-build-file:: inc/protocomm.inc .. include-build-file:: inc/protocomm_security.
60
inc .. include-build-file:: inc/protocomm_security0.inc .. include-build-file:: inc/protocomm_security1.inc .. include-build-file:: inc/protocomm_security2.inc .. include-build-file:: inc/esp_srp.inc .. include-build-file:: inc/protocomm_httpd.inc .. only:: SOC_BLE_SUPPORTED .. include-build-file:: inc/protocomm_ble.inc
60
Unified Provisioning Overview >>>>>>>> The unified provisioning support in the ESP-IDF provides an extensible mechanism to the developers to configure the device with the Wi-Fi credentials and/or other custom configuration using various transports and different security schemes. Depending on the use case, it provides a complete and ready solution for Wi-Fi network provisioning along with example iOS and Android applications. The developers can choose to extend the device-side and phone-app side implementations to accommodate their requirements for sending additional configuration data. The followings are the important features of this implementation: The protocol is completely flexible and it offers the ability for the developers to send custom configuration in the provisioning process. The data representation is also left to the application to decide. The protocol can work on Wi-Fi (SoftAP + HTTP server) or on Bluetooth LE as a transport protocol. The framework provides an ability to add support for any other transport easily as long as command-response behavior can be supported on the transport.
61
It is understood that each use case may require different security scheme to secure the data that is exchanged in the provisioning process. Some applications may work with SoftAP that is WPA2 protected or Bluetooth LE with the "just-works" security. Or the applications may consider the transport to be insecure and may want application-level security. The unified provisioning framework allows the application to choose the security as deemed suitable. The protocol uses `Google Protobufs `_ as a data representation for session setup and Wi-Fi provisioning. They provide a compact data representation and ability to parse the data in multiple programming languages in native format. Please note that this data representation is not forced on application-specific data and the developers may choose the representation of their choice. Typical Provisioning Process >>>>>>>>>>>>>>>>>>>>>>>>>>>> .. seqdiag:: :caption: Typical Provisioning Process :align: center seqdiag typical-prov-process { activation = none; node_width = 80; node_height = 60; edge_length = 360; span_height = 5; default_shape = roundedbox; default_fontsize = 12; CLIENT [label = "Client"]; DEVICE [label = "Device"]; === 1.
61
Transport-specific discovery and connection === DEVICE -> CLIENT [label="Some form of beaconing"]; CLIENT -> DEVICE [label="Client connects"]; === 2. Session Establishment CLIENT -> DEVICE [label="Get Version Request"]; DEVICE -> CLIENT [label="Get Version Response"]; CLIENT -> DEVICE [label="Session Setup Request"]; DEVICE -> CLIENT [label="Session Setup Response"]; CLIENT --> DEVICE; ... One or multiple steps as per protocol ... DEVICE --> CLIENT === 3. Configuration === CLIENT --> DEVICE [label="App-specific Set Config (optional)"]; DEVICE --> CLIENT [label="Set Config Response (optional)"]; CLIENT -> DEVICE [label="Wi-Fi SetConfig(SSID, Passphrase...)"]; DEVICE -> CLIENT [label="Wi-Fi SetConfig response"]; CLIENT -> DEVICE [label="Wi-Fi ApplyConfig cmd"]; DEVICE -> CLIENT [label="Wi-Fi ApplyConfig resp"]; CLIENT -> DEVICE [label="Wi-Fi GetStatus cmd (repeated)"]; DEVICE -> CLIENT [label="Wi-Fi GetStatus resp (repeated)"]; === 4.
61
Close connection === DEVICE -> CLIENT [label="Close Connection"]; } Deciding on Transport >>>>>>>>>>>>>>>>>>>>> The unified provisioning subsystem supports Wi-Fi (SoftAP+HTTP server) and Bluetooth LE (GATT based) transport schemes. The following points need to be considered while selecting the best possible transport for provisioning: - The device uses the same radio to host the SoftAP and also to connect to the configured AP. Since these could potentially be on different channels, it may cause connection status updates not to be reliably received by the phone - The phone (client) has to disconnect from its current AP in order to connect to the SoftAP. The original network will get restored only when the provisioning process is complete, and the softAP is taken down. Deciding on Security >>>>>>>>>>>>>>>>>>>> Depending on the transport and other constraints, the security scheme needs to be selected by the application developers. The following considerations need to be given from the provisioning-security perspective: There are two levels of security schemes, of which the developer may select one or a combination, depending on requirements.
61
For SoftAP provisioning, developers may choose WPA2-protected security with unique per-device passphrase. Unique per-device passphrase can also act as a proof-of-possession. For Bluetooth LE, the "just-works" security can be used as a transport-level security after assessing its provided level of security. The unified provisioning subsystem provides the application-level security (`Security 1 Scheme`_) that provides data protection and authentication through PoP, if the application does not use the transport-level security, or if the transport-level security is not sufficient for the use case. Device Discovery >>>>>>>>>>>>>>>> The advertisement and device discovery is left to the application and depending on the protocol chosen, the phone apps and device-firmware application can choose appropriate method for advertisement and discovery. For the SoftAP+HTTP transport, typically the SSID (network name) of the AP hosted by the device can be used for discovery. For the Bluetooth LE transport, device name or primary service included in the advertisement or a combination of both can be used for discovery.
61
Architecture >>>>>>>>>>>> The below diagram shows the architecture of unified provisioning: .. figure:: ../../../_static/unified_provisioning.png :align: center :alt: Unified Provisioning Architecture Unified Provisioning Architecture It relies on the base layer called :doc:`protocomm` (protocomm) which provides a framework for security schemes and transport mechanisms. The Wi-Fi Provisioning layer uses protocomm to provide simple callbacks to the application for setting the configuration and getting the Wi-Fi status. The application has control over implementation of these callbacks. In addition, the application can directly use protocomm to register custom handlers. The application creates a protocomm instance which is mapped to a specific transport and specific security scheme. Each transport in the protocomm has a concept of an "end-point" which corresponds to the logical channel for communication for specific type of information. For example, security handshake happens on a different endpoint from the Wi-Fi configuration endpoint.
61
Each end-point is identified using a string and depending on the transport internal representation of the end-point changes. In case of the SoftAP+HTTP transport, the end-point corresponds to URI, whereas in case of Bluetooth LE, the end-point corresponds to the GATT characteristic with specific UUID. Developers can create custom end-points and implement handler for the data that is received or sent over the same end-point. .. _provisioning_security_schemes: Security Schemes >>>>>>>>>>>>>>>> At present, the unified provisioning supports the following security schemes: No security (No encryption). Curve25519-based key exchange, shared key derivation and AES256-CTR mode encryption of the data. It supports two modes : a. Authorized - Proof of Possession (PoP) string used to authorize session and derive shared key. b. No Auth (Null PoP) - Shared key derived through key exchange only. SRP6a-based shared key derivation and AES256-GCM mode encryption of the data. .. note:: The respective security schemes need to be enabled through the project configuration menu.
61
Please refer to :ref:`enabling-protocomm-security-version` for more details. Security 1 Scheme >>>>>>>>>>>>>>>>> The Security 1 scheme details are shown in the below sequence diagram: .. seqdiag:: :caption: Security 1 :align: center seqdiag security1 { activation = none; node_width = 80; node_height = 60; edge_length = 480; span_height = 5; default_shape = roundedbox; default_fontsize = 12; CLIENT [label = "Client"]; DEVICE [label = "Device"]; === Security 1 === CLIENT -> CLIENT [label = "Generate\nKey Pair", rightnote = "{cli_privkey, cli_pubkey} = curve25519_keygen()"]; CLIENT -> DEVICE [label = "SessionCmd0(cli_pubkey)"]; DEVICE -> DEVICE [label = "Generate\nKey Pair", leftnote = "{dev_privkey, dev_pubkey} = curve25519_keygen()"]; DEVICE -> DEVICE [label = "Initialization\nVector", leftnote = "dev_rand = gen_16byte_random()"]; DEVICE -> DEVICE [label = "Shared Key", leftnote = "shared_key(No PoP) = curve25519(dev_privkey, cli_pubkey) \nshared_key(with PoP) = curve25519(dev_privkey, cli_pubkey) ^ SHA256(pop)"]; DEVICE -> CLIENT [label = "SessionResp0(dev_pubkey, dev_rand)"]; CLIENT -> CLIENT [label = "Shared Key", rightnote = "shared_key(No PoP) = curve25519(cli_privkey, dev_pubkey)\nshared_key(with PoP) = curve25519(cli_privkey, dev_pubkey) ^ SHA256(pop)"]; CLIENT -> CLIENT [label = "Verification\nToken", rightnote = "cli_verify = aes_ctr_enc(key=shared_key, data=dev_pubkey, nonce=dev_rand)"]; CLIENT -> DEVICE [label = "SessionCmd1(cli_verify)"]; DEVICE -> DEVICE [label = "Verify Client", leftnote = "check (dev_pubkey == aes_ctr_dec(cli_verify.
61
..)"]; DEVICE -> DEVICE [label = "Verification\nToken", leftnote = "dev_verify = aes_ctr_enc(key=shared_key, data=cli_pubkey, nonce=(prev-context))"]; DEVICE -> CLIENT [label = "SessionResp1(dev_verify)"]; CLIENT -> CLIENT [label = "Verify Device", rightnote = "check (cli_pubkey == aes_ctr_dec(dev_verify...)"]; } Security 2 Scheme >>>>>>>>>>>>>>>>> The Security 2 scheme is based on the Secure Remote Password (SRP6a) protocol, see `RFC 5054 `_. The protocol requires the Salt and Verifier to be generated beforehand with the help of the identifying username ``I`` and the plaintext password ``p``. The Salt and Verifier are then stored on {IDF_TARGET_NAME}. - The password ``p`` and the username ``I`` are to be provided to the Phone App (Provisioning entity) by suitable means, e.g., QR code sticker. Details about the Security 2 scheme are shown in the below sequence diagram: .. seqdiag:: :caption: Security 2 :align: center seqdiag security2 { activation = none; node_width = 80; node_height = 60; edge_length = 550; span_height = 5; default_shape = roundedbox; default_fontsize = 12; CLIENT [label = "Client\n(PhoneApp)"]; DEVICE [label = "Device\n(ESP)"]; === Security 2 === CLIENT -> CLIENT [label = "Generate\nKey Pair", rightnote = "a (cli_privkey) = 256 bit random value, A (cli_pubkey) = g^a.
61
g - generator, N - large safe prime, All arithmetic operations are performed in ring of integers modulo N, thus all occurrences like y^z should be read as y^z modulo N."]; CLIENT -> DEVICE [label = "SessionCmd0(cli_pubkey A, username I)"]; DEVICE -> DEVICE [label = "Obtain\n Salt and Verifier", leftnote = "Obtain salt and verifier stored on esp Salt s = 256 bit random value, Verifier v = g^x where x = H(s | I | p)"]; DEVICE -> DEVICE [label = "Generate\nKey Pair", leftnote = "b (dev_privkey) = 256 bit random value B(dev_pubkey) = k*v + g^b where k = H(N, g)"]; DEVICE -> DEVICE [label = "Shared Key", leftnote = "Shared Key K = H(S) where, S = (A * v^u) ^ b u = H(A, B)"]; DEVICE -> CLIENT [label = "SessionResp0(dev_pubkey B, dev_rand)"]; CLIENT -> CLIENT [label = "Shared Key", rightnote = "shared_key(K) = H(S) where, S = (B - k*v) ^ (a + ux), u = H(A, B), k = H(N, g), v = g^x, x = H(s | I | p).
61
"]; CLIENT -> CLIENT [label = "Verification\nToken", rightnote = "client_proof M = H[H(N) XOR H(g) | H(I) | s | A | B | K]"]; CLIENT -> DEVICE [label = "SessionCmd1(client_proof M1)"]; DEVICE -> DEVICE [label = "Verify Client", leftnote = "device generates M1 = H[H(N) XOR H(g) | H(I) | s | A | B | K] device verifies this M1 with the M1 obtained from Client"]; DEVICE -> DEVICE [label = "Verification\nToken", leftnote = " Device generate device_proof M2 = H(A, M, K)"]; DEVICE -> DEVICE [label = "Initialization\nVector", leftnote = "dev_rand = gen_16byte_random() This random number is to be used for AES-GCM operation for encryption and decryption of the data using the shared secret"]; DEVICE -> CLIENT [label = "SessionResp1(device_proof M2, dev_rand)"]; CLIENT -> CLIENT [label = "Verify Device", rightnote = "Client calculates device proof M2 as M2 = H(A, M, K) client verifies this M2 with M2 obtained from device"]; } Sample Code >>>>>>>>>>> Please refer to :doc:`protocomm` and :doc:`wifi_provisioning` for API guides and code snippets on example usage.
61
Application implementation can be found as an example under :example:`provisioning`. Provisioning Tools >>>>>>>>>>>>>>>>>> Provisioning applications are available for various platforms, along with source code: The phone applications offer simple UI and are thus more user centric, while the command-line application is useful as a debugging tool for developers.
61
SD/SDIO/MMC Driver Overview The SD/SDIO/MMC driver currently supports SD memory, SDIO cards, and eMMC chips. This is a protocol layer driver (:component_file:`sdmmc/include/sdmmc_cmd.h`) which can be implemented by: .. list:: :SOC_SDMMC_HOST_SUPPORTED: - SDMMC host driver (:component_file:`esp_driver_sdmmc/include/driver/sdmmc_host.h`), see :doc:`SDMMC Host API ` for more details. - SDSPI host driver (:component_file:`esp_driver_sdspi/include/driver/sdspi_host.h`), see :doc:`SD SPI Host API ` for more details. Protocol Layer vs Host Layer The SDMMC protocol layer described in this document handles the specifics of the SD protocol, such as the card initialization flow and variours data transfer command flows. The protocol layer works with the host via the :cpp:class:`sdmmc_host_t` structure. This structure contains pointers to various functions of the host. Host layer driver(s) implement the protocol layer driver by supporting these functions: - Sending commands to slave devices - Sending and receiving data - Handling error conditions within the bus .
62
. blockdiag:: /../_static/diagrams/sd/sd_arch.diag :scale: 100% :caption: SD Host Side Component Architecture :align: center Application Example An example which combines the SDMMC driver with the FATFS library is provided in the :example:`storage/sd_card` directory of ESP-IDF examples. This example initializes the card, then writes and reads data from it using POSIX and C library APIs. See README.md file in the example directory for more information. .. only:: SOC_SDMMC_HOST_SUPPORTED Protocol Layer API The protocol layer is given the :cpp:class:`sdmmc_host_t` structure. This structure describes the SD/MMC host driver, lists its capabilities, and provides pointers to functions for the implementation driver. The protocol layer stores card-specific information in the :cpp:class:`sdmmc_card_t` structure. When sending commands to the SD/MMC host driver, the protocol layer uses the :cpp:class:`sdmmc_command_t` structure to describe the command, arguments, expected return values, and data to transfer if there is any.
62
Using API with SD Memory Cards Using API with eMMC Chips From the protocol layer's perspective, eMMC memory chips behave exactly like SD memory cards. Even though eMMCs are chips and do not have a card form factor, the terminology for SD cards can still be applied to eMMC due to the similarity of the protocol (`sdmmc_card_t`, `sdmmc_card_init`). Note that eMMC chips cannot be used over SPI, which makes them incompatible with the SD SPI host driver. To initialize eMMC memory and perform read/write operations, follow the steps listed for SD cards in the previous section. Using API with SDIO Cards Initialization and the probing process are the same as with SD memory cards. The only difference is in data transfer commands in SDIO mode. During the card initialization and probing, performed with :cpp:func:`sdmmc_card_init`, the driver only configures the following registers of the IO card: In particular, the driver does not set any bits in (1) I/O Enable and Int Enable registers, (2) I/O block sizes, etc.
62
Applications can set them by calling :cpp:func:`sdmmc_io_write_byte`. For card configuration and data transfer, choose the pair of functions relevant to your case from the table below. .. list-table:: :widths: 55 25 20 :header-rows: 1 - Read Function - Write Function - :cpp:func:`sdmmc_io_read_byte` - :cpp:func:`sdmmc_io_write_byte` - :cpp:func:`sdmmc_io_read_bytes` - :cpp:func:`sdmmc_io_write_bytes` - :cpp:func:`sdmmc_io_read_blocks` - :cpp:func:`sdmmc_io_write_blocks` SDIO interrupts can be enabled by the application using the function :cpp:func:`sdmmc_io_enable_int`. When using SDIO in 1-line mode, the D1 line also needs to be connected to use SDIO interrupts. If you want the application to wait until the SDIO interrupt occurs, use :cpp:func:`sdmmc_io_wait_int`. .. only:: esp32 There is a component ESSL (ESP Serial Slave Link) to use if you are communicating with an ESP32 SDIO slave.
62
See :doc:`/api-reference/protocols/esp_serial_slave_link` and example :example:`peripherals/sdio/host`. Combo (Memory + IO) Cards The driver does not support SD combo cards. Combo cards are treated as IO cards. Thread Safety Most applications need to use the protocol layer only in one task. For this reason, the protocol layer does not implement any kind of locking on the :cpp:class:`sdmmc_card_t` structure, or when accessing SDMMC or SD SPI host drivers. Such locking is usually implemented on a higher layer, e.g., in the filesystem driver. API Reference .. include-build-file:: inc/sdmmc_cmd.inc .. include-build-file:: inc/sdmmc_types.inc
62
Storage API This section contains reference of the high-level storage APIs. They are based on low-level drivers such as SPI flash, SD/MMC. - :doc:`Partitions API ` allow block based access to SPI flash according to the :doc:`/api-guides/partition-tables`. - :doc:`Non-Volatile Storage library (NVS) ` implements a fault-tolerant wear-levelled key-value storage in SPI NOR flash. - :doc:`Virtual File System (VFS) ` library provides an interface for registration of file system drivers. SPIFFS, FAT and various other file system libraries are based on the VFS. - :doc:`SPIFFS ` is a wear-levelled file system optimized for SPI NOR flash, well suited for small partition sizes and low throughput - :doc:`FAT ` is a standard file system which can be used in SPI flash or on SD/MMC cards - :doc:`Wear Levelling ` library implements a flash translation layer (FTL) suitable for SPI NOR flash. It is used as a container for FAT partitions in flash. .. note:: It is suggested to use high-level APIs (``esp_partition`` or file system) instead of low-level driver APIs to access the SPI NOR flash.
63
Due to the restriction of NOR flash and ESP hardware, accessing the main flash will affect the performance of the whole system. See :doc:`/api-reference/peripherals/spi_flash/index` to learn more about the limitations. .. toctree:: :maxdepth: 1 fatfs mass_mfg.rst nvs_flash nvs_encryption nvs_partition_gen.rst nvs_partition_parse.rst sdmmc partition spiffs vfs wear-levelling Code examples for this API section are provided in the :example:`storage` directory of ESP-IDF examples.
63